<?php
// database.php

// ----------------------------------------
// INCLUDE CONNECTION FILE
// ----------------------------------------
// Adjust the path to conn.php as needed. Here, we assume conn.php is in the same directory.
include "../../../conn.php";

// ----------------------------------------
// HELPERS
// ----------------------------------------

/**
 * Send JSON response & exit
 */
function respondJson($data, $httpCode = 200) {
    header('Content-Type: application/json', true, $httpCode);
    echo json_encode($data, JSON_UNESCAPED_SLASHES);
    exit;
}

// ----------------------------------------
// VERIFY CONNECTION
// ----------------------------------------
// conn.php sets up $conn via mysqli_connect(...).
if (!isset($conn) || $conn === false) {
    respondJson([
        'status' => 'error',
        'error'  => 'DB connection failed'
    ], 500);
}

// Switch to using object‐oriented style on the same connection
$mysqli = $conn;
$mysqli->set_charset('utf8');

// ----------------------------------------
// ENTRYPOINT: Expect GET parameter "action"
// ----------------------------------------

$action = isset($_GET['action']) ? trim($_GET['action']) : '';
if (!in_array($action, ['get_balance','clear_balance','add_balance','get_prefix'])) {
    respondJson([
        'status' => 'error',
        'error'  => 'Invalid or missing action. Must be: get_balance, clear_balance, add_balance, get_prefix.'
    ], 400);
}

// “uid” corresponds to balakedara (username)
$uid = isset($_GET['uid']) ? trim($_GET['uid']) : '';
if ($uid === '') {
    respondJson([
        'status' => 'error',
        'error'  => 'Missing required parameter: uid'
    ], 400);
}

switch ($action) {
    // ----------------------------------------
    // 1) Return current balance (motta) for balakedara
    //    GET ...?action=get_balance&uid=...
    // ----------------------------------------
    case 'get_balance':
        $stmt = $mysqli->prepare('SELECT motta FROM shonu_kaichila WHERE balakedara = ?');
        $stmt->bind_param('i', $uid);
        $stmt->execute();
        $stmt->bind_result($balance);
        if (!$stmt->fetch()) {
            // No row → treat as zero
            $balance = 0.0;
        }
        $stmt->close();

        respondJson([
            'status'  => 'success',
            'balance' => floatval($balance)
        ], 200);
        break;

    // ----------------------------------------
    // 2) Clear balance (motta) to zero for balakedara
    //    GET ...?action=clear_balance&uid=...
    // ----------------------------------------
    case 'clear_balance':
        // Check existence
        $stmtCheck = $mysqli->prepare('SELECT 1 FROM shonu_kaichila WHERE balakedara = ?');
        $stmtCheck->bind_param('i', $uid);
        $stmtCheck->execute();
        $stmtCheck->store_result();

        if ($stmtCheck->num_rows > 0) {
            // Row exists → update motta = 0
            $stmtCheck->close();
            $stmtUpd = $mysqli->prepare('UPDATE shonu_kaichila SET motta = 0.0 WHERE balakedara = ?');
            $stmtUpd->bind_param('i', $uid);
            if (!$stmtUpd->execute()) {
                $stmtUpd->close();
                respondJson([
                    'status' => 'error',
                    'error'  => 'DB UPDATE failed: ' . $mysqli->error
                ], 500);
            }
            $stmtUpd->close();
        } else {
            // Row does not exist → insert with motta = 0
            $stmtCheck->close();
            $stmtIns = $mysqli->prepare('INSERT INTO shonu_kaichila (balakedara, motta) VALUES (?, 0.0)');
            $stmtIns->bind_param('i', $uid);
            if (!$stmtIns->execute()) {
                $stmtIns->close();
                respondJson([
                    'status' => 'error',
                    'error'  => 'DB INSERT failed: ' . $mysqli->error
                ], 500);
            }
            $stmtIns->close();
        }

        respondJson([
            'status' => 'success'
        ], 200);
        break;

    // ----------------------------------------
    // 3) Add amount to existing balance (motta) or insert new row
    //    GET ...?action=add_balance&uid=...&amount=...
    // ----------------------------------------
    case 'add_balance':
        $amount = isset($_GET['amount']) && is_numeric($_GET['amount'])
            ? floatval($_GET['amount'])
            : null;
        if ($amount === null) {
            respondJson([
                'status' => 'error',
                'error'  => 'Missing or invalid "amount"'
            ], 400);
        }

        // Check if row exists
        $stmtCheck = $mysqli->prepare('SELECT motta FROM shonu_kaichila WHERE balakedara = ?');
        $stmtCheck->bind_param('i', $uid);
        $stmtCheck->execute();
        $stmtCheck->bind_result($existing);
        if ($stmtCheck->fetch()) {
            // Row exists → update motta = existing + amount
            $stmtCheck->close();
            $newBal = $existing + $amount;
            $stmtUpd = $mysqli->prepare('UPDATE shonu_kaichila SET motta = ? WHERE balakedara = ?');
            $stmtUpd->bind_param('di', $newBal, $uid);
            if (!$stmtUpd->execute()) {
                $stmtUpd->close();
                respondJson([
                    'status' => 'error',
                    'error'  => 'DB UPDATE failed: ' . $mysqli->error
                ], 500);
            }
            $stmtUpd->close();
        } else {
            // Row does not exist → insert with motta = amount
            $stmtCheck->close();
            $stmtIns = $mysqli->prepare('INSERT INTO shonu_kaichila (balakedara, motta) VALUES (?, ?)');
            $stmtIns->bind_param('id', $uid, $amount);
            if (!$stmtIns->execute()) {
                $stmtIns->close();
                respondJson([
                    'status' => 'error',
                    'error'  => 'DB INSERT failed: ' . $mysqli->error
                ], 500);
            }
            $stmtIns->close();
        }

        respondJson([
            'status' => 'success'
        ], 200);
        break;

    // ----------------------------------------
    // 4) Return prefix (kramasankhye) for balakedara
    //    GET ...?action=get_prefix&uid=...
    // ----------------------------------------
    case 'get_prefix':
        $stmt = $mysqli->prepare('SELECT kramasankhye FROM shonu_kaichila WHERE balakedara = ?');
        $stmt->bind_param('i', $uid);
        $stmt->execute();
        $stmt->bind_result($prefix);
        if (!$stmt->fetch()) {
            // No row → default prefix
            $prefix = 'abcd';
        }
        $stmt->close();

        respondJson([
            'status' => 'success',
            'prefix' => $prefix
        ], 200);
        break;
}

$mysqli->close();
