<?php

header('Content-Type: text/plain');
include 'config.php';


$admin_username = $_POST['admin_username'];
$admin_password = $_POST['admin_password'];

$admin_stmt = $conn->prepare("SELECT username FROM admin WHERE username = ? AND password = ?");
$admin_stmt->bind_param("ss", $admin_username, $admin_password);
$admin_stmt->execute();
$admin_result = $admin_stmt->get_result();

if ($admin_result->num_rows === 0) {
    http_response_code(403);
    echo json_encode([
        "status" => "error",
        "message" => "Access Denied"
    ], JSON_PRETTY_PRINT);
    $admin_stmt->close();
    $conn->close();
    exit();
}

$order_id = trim($_POST['order_id'] ?? '');
$type     = trim($_POST['type'] ?? ''); // success / failed

if (empty($order_id) || empty($type)) {
    echo "All Fields Required";
    exit();
}

if ($type != "success" && $type != "failed") {
    echo "Invalid Type";
    exit();
}

$conn->autocommit(false); // 🔒 transaction start

try {

    /* =========================
       GET ORDER
    ========================= */
    $stmt = $conn->prepare("
        SELECT user_token, product_price, status
        FROM topup_orders
        WHERE id = ?
    ");

    $stmt->bind_param("i", $order_id);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 0) {
        echo "Order Not Found";
        $conn->rollback();
        exit();
    }

    $order = $result->fetch_assoc();

    $user_token = $order['user_token'];
    $price      = (float)$order['product_price'];
    $old_status = $order['status'];

    $stmt->close();

    /* =========================
       PREVENT DOUBLE UPDATE
    ========================= */
    if ($old_status == $type) {
        echo "Already Updated";
        $conn->rollback();
        exit();
    }

    /* =========================
       IF FAILED → REFUND MONEY
    ========================= */
    if ($type == "failed") {

        $u = $conn->prepare("
            SELECT balance, winning
            FROM users
            WHERE token = ?
        ");

        $u->bind_param("s", $user_token);
        $u->execute();
        $res = $u->get_result();
        $user = $res->fetch_assoc();
        $u->close();

        $balance = (float)$user['balance'];
        $winning = (float)$user['winning'];

        /* Refund priority: balance first */
        $new_balance = $balance + $price;

        $up = $conn->prepare("
            UPDATE users SET balance = ? WHERE token = ?
        ");

        $up->bind_param("ds", $new_balance, $user_token);

        if (!$up->execute()) {
            throw new Exception("Refund Failed");
        }

        $up->close();
    }

    /* =========================
       UPDATE ORDER STATUS
    ========================= */
    $update = $conn->prepare("
        UPDATE topup_orders
        SET status = ?
        WHERE id = ?
    ");

    $update->bind_param("si", $type, $order_id);

    if (!$update->execute()) {
        throw new Exception("Status Update Failed");
    }

    $update->close();

    /* =========================
       COMMIT
    ========================= */
    $conn->commit();

    echo "Order Updated Successfully";

}
catch (Exception $e) {

    $conn->rollback();
    echo "Failed To Update Order";
}

$conn->close();

?>