<?php
header('Access-Control-Allow-Origin: *');
include "../../../conn.php";

// Handle DB connection check again
if (!$conn) {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        header('Content-Type: application/json');
        echo json_encode(['status' => 'false', 'msg' => 'Database connection failed']);
    } else {
        header('Content-Type: text/html');
        echo "<h2>❌ Database connection failed</h2>";
    }
    exit;
}

// ───── POST REQUEST: Handle Account & Balance ─────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json');

    // Create webghost_cq9 table if not exists
    $createAccTable = "
    CREATE TABLE IF NOT EXISTS webghost_cq9 (
        id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
        user_id VARCHAR(100) NOT NULL,
        user_account VARCHAR(100) NOT NULL,
        user_password VARCHAR(100) NOT NULL,
        user_nickname VARCHAR(100) NOT NULL,
        user_token VARCHAR(255) NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;";
    mysqli_query($conn, $createAccTable);

    // Input
    $userId   = $_POST['userId']   ?? '';
    $account  = $_POST['account']  ?? '';
    $password = $_POST['password'] ?? '';
    $nickname = $_POST['nickname'] ?? '';

    if (empty($userId) || empty($account) || empty($password) || empty($nickname)) {
        echo json_encode(['status' => 'false', 'msg' => 'Missing required parameters']);
        exit;
    }

    // Check if user exists
    $check = mysqli_prepare($conn, "SELECT id FROM webghost_cq9 WHERE user_id = ?");
    mysqli_stmt_bind_param($check, "s", $userId);
    mysqli_stmt_execute($check);
    mysqli_stmt_store_result($check);

    if (mysqli_stmt_num_rows($check) === 0) {
        $user_token = "cq9_cq9_" . $userId;
        $insert = mysqli_prepare($conn, "INSERT INTO webghost_cq9 (user_id, user_account, user_password, user_nickname, user_token) VALUES (?, ?, ?, ?, ?)");
        mysqli_stmt_bind_param($insert, "sssss", $userId, $account, $password, $nickname, $user_token);
        if (!mysqli_stmt_execute($insert)) {
            echo json_encode(['status' => 'false', 'msg' => 'Insert failed', 'error' => mysqli_error($conn)]);
            exit;
        }
    }

    // Get & Reset Balance
    $balance = 0;
    $balStmt = mysqli_prepare($conn, "SELECT motta FROM shonu_kaichila WHERE balakedara = ?");
    mysqli_stmt_bind_param($balStmt, "s", $userId);
    mysqli_stmt_execute($balStmt);
    $result = mysqli_stmt_get_result($balStmt);

    if ($result && mysqli_num_rows($result) > 0) {
        $row = mysqli_fetch_assoc($result);
        $balance = $row['motta'];

        $resetStmt = mysqli_prepare($conn, "UPDATE shonu_kaichila SET motta = 0 WHERE balakedara = ?");
        mysqli_stmt_bind_param($resetStmt, "s", $userId);
        mysqli_stmt_execute($resetStmt);
    }

    echo json_encode([
        'status'   => 'true',
        'msg'      => 'Account handled, balance returned, and reset',
        'account'  => $account,
        'password' => $password,
        'amount'   => $balance
    ]);
    exit;
}

// ───── GET REQUEST: Withdraw View ─────
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    header('Content-Type: text/html');

    $status  = $_GET['status'] ?? '';
    $amount  = isset($_GET['amount']) ? floatval($_GET['amount']) : 0;
    $balance = isset($_GET['balance']) ? floatval($_GET['balance']) : 0;
    $user_id = $_GET['user_id'] ?? '';
    $msg     = $_GET['msg'] ?? '';

    if ($status === 'success' && !empty($user_id)) {
        $update = "UPDATE shonu_kaichila SET motta = motta + $amount WHERE balakedara = '$user_id'";
        if (mysqli_query($conn, $update)) {
            echo "<h2>✅ Withdraw Success</h2>";
            echo "<p>Amount: ₹$amount</p>";
            echo "<p>New CQ9 Balance: ₹$balance</p>";
        } else {
            echo "<h2>❌ DB Update Failed</h2><p>" . mysqli_error($conn) . "</p>";
        }
    } else {
        echo "<h2>❌ Withdraw Failed</h2><p>Reason: " . htmlspecialchars($msg) . "</p>";
    }
    exit;
}
?>
