<?php
// যেকোনো PHP Warning বা Notice যেন JSON রেসপন্স ভেঙে না দেয়
error_reporting(0);
header('Content-Type: application/json');
include 'config.php';

session_start();

try {
    $VALID_USERNAME = 'SKM eSPORTS';
    $VALID_PASSWORD = '2580';

    $admin_authenticated = false;
    if (isset($_SESSION['admin_logged_in']) && $_SESSION['admin_logged_in'] === true) {
        $admin_authenticated = true;
    }
    if (!$admin_authenticated) {
        $admin_username = $_POST['admin_username'] ?? '';
        $admin_password = $_POST['admin_password'] ?? '';
        if ($admin_username === $VALID_USERNAME && $admin_password === $VALID_PASSWORD) {
            $admin_authenticated = true;
            $_SESSION['admin_logged_in'] = true;
            $_SESSION['admin_username'] = $admin_username;
        }
    }
    if (!$admin_authenticated) {
        http_response_code(403);
        echo json_encode(["status" => "error", "message" => "Access Denied. Please login."]);
        exit;
    }

    $type = $_POST['type'] ?? '';

    // ---------- GET ALL ORDERS ----------
    if ($type === 'get_all') {
        $status = $conn->real_escape_string($_POST['status'] ?? ''); 
        $page = max(1, (int)($_POST['page'] ?? 1));
        $per_page = max(1, (int)($_POST['per_page'] ?? 20));
        $offset = ($page - 1) * $per_page;

        $where = "";
        if ($status && in_array($status, ['Pending', 'Success', 'Failed'])) {
            $where = " WHERE LOWER(status) = LOWER('$status')";
        }

        $countQuery = "SELECT COUNT(*) as total FROM topup_orders" . $where;
        $countResult = $conn->query($countQuery);
        $total = $countResult->fetch_assoc()['total'] ?? 0;
        $last_page = ceil($total / $per_page);

        // Assuming your table has an 'id' column as primary key
        $sql = "SELECT * FROM topup_orders " . $where . " ORDER BY id DESC LIMIT $offset, $per_page";
        $result = $conn->query($sql);
        $data = [];
        if ($result) {
            while ($row = $result->fetch_assoc()) {
                $data[] = $row;
            }
        }

        echo json_encode([
            "status" => "success",
            "data" => $data,
            "total" => (int)$total,
            "current_page" => $page,
            "per_page" => $per_page,
            "last_page" => $last_page
        ]);
        exit;
    }

    // ---------- COMPLETE (Success) ----------
    if ($type === 'complete') {
        $id = $conn->real_escape_string($_POST['id'] ?? '');
        if (!$id) {
            echo json_encode(["status" => "error", "message" => "Missing order ID"]);
            exit;
        }
        
        $check = $conn->query("SELECT LOWER(status) as status_lower FROM topup_orders WHERE id = '$id'");
        if (!$check || $check->num_rows === 0) {
            echo json_encode(["status" => "error", "message" => "Order not found"]);
            exit;
        }
        
        $row = $check->fetch_assoc();
        if ($row['status_lower'] !== 'pending') {
            echo json_encode(["status" => "error", "message" => "Order already processed"]);
            exit;
        }
        
        $update = $conn->query("UPDATE topup_orders SET status = 'Success' WHERE id = '$id'");
        if ($update) {
            echo json_encode(["status" => "success", "message" => "Order marked as Success"]);
        } else {
            echo json_encode(["status" => "error", "message" => "Failed to update status"]);
        }
        exit;
    }

    // ---------- FAIL (Failed + Refund) ----------
    if ($type === 'fail') {
        $id = $conn->real_escape_string($_POST['id'] ?? '');
        if (!$id) {
            echo json_encode(["status" => "error", "message" => "Missing order ID"]);
            exit;
        }
        
        $get = $conn->query("SELECT username, discount_price FROM topup_orders WHERE id = '$id' AND LOWER(status) = 'pending'");
        if (!$get || $get->num_rows === 0) {
            echo json_encode(["status" => "error", "message" => "Order not found or already processed"]);
            exit;
        }
        
        $order = $get->fetch_assoc();
        $username = $conn->real_escape_string($order['username']);
        
        // Discount price is considered as the paid amount
        $refund_amount = (float)($order['discount_price'] ?? 0);

        if ($refund_amount <= 0) {
            echo json_encode(["status" => "error", "message" => "Invalid refund amount (৳0). Can't refund."]);
            exit;
        }

        // Refund to users table using username (Change 'username' to 'user_token' if you use token for match)
        $refund = $conn->query("UPDATE users SET balance = balance + $refund_amount WHERE username = '$username'");
        if (!$refund) {
            echo json_encode(["status" => "error", "message" => "Failed to refund user"]);
            exit;
        }

        // Update status
        $update = $conn->query("UPDATE topup_orders SET status = 'Failed' WHERE id = '$id'");
        if ($update) {
            echo json_encode(["status" => "success", "message" => "Order Failed & ৳$refund_amount refunded to $username"]);
        } else {
            echo json_encode(["status" => "error", "message" => "Status update failed, but refund was done"]);
        }
        exit;
    }

    echo json_encode(["status" => "error", "message" => "Invalid request type"]);

} catch (Exception $e) {
    echo json_encode(["status" => "error", "message" => "Database Error: " . $e->getMessage()]);
}

if(isset($conn)) $conn->close();
?>