<?php
require_once "config.php";

session_start();

date_default_timezone_set("Asia/Dhaka");

if (!isset($conn) || !($conn instanceof mysqli)) {
    die(json_encode(["status" => "error", "message" => "Database connection error"]));
}
$conn->set_charset("utf8mb4");

function base64url_encode($data) { 
    return rtrim(strtr(base64_encode($data), '+/', '-_'), '='); 
}

function getAccessToken($jsonFilePath) {
    $credentials = json_decode(file_get_contents($jsonFilePath), true);
    if (!$credentials || !isset($credentials['private_key'])) return false;

    $clientEmail = $credentials['client_email'];
    $privateKey  = $credentials['private_key'];

    $header = json_encode(['alg' => 'RS256', 'typ' => 'JWT']);
    $now = time();
    $payload = json_encode([
        'iss'   => $clientEmail,
        'scope' => 'https://www.googleapis.com/auth/cloud-platform',
        'aud'   => 'https://oauth2.googleapis.com/token',
        'exp'   => $now + 3600,
        'iat'   => $now
    ]);

    $unsignedJwt = base64url_encode($header) . "." . base64url_encode($payload);
    $signature = '';
    openssl_sign($unsignedJwt, $signature, $privateKey, OPENSSL_ALGO_SHA256);
    $jwt = $unsignedJwt . "." . base64url_encode($signature);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://oauth2.googleapis.com/token');
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(['grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer', 'assertion' => $jwt]));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $response = curl_exec($ch);
    curl_close($ch);

    $responseData = json_decode($response, true);
    return isset($responseData['access_token']) ? $responseData['access_token'] : false;
}

function sendOrderNotification($conn, $user_token, $title, $body) {
    if (empty($user_token)) return;
    
    $stmt = $conn->prepare("SELECT fcm_key FROM users WHERE token = ? LIMIT 1");
    if (!$stmt) return;
    
    $stmt->bind_param("s", $user_token);
    $stmt->execute();
    $res = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    if (!$res || empty($res['fcm_key'])) return;
    $fcm_key = $res['fcm_key'];
    
    $serviceAccountFile = 'noti.json';
    if (!file_exists($serviceAccountFile)) return;
    
    $accessToken = getAccessToken($serviceAccountFile);
    if (!$accessToken) return;
    
    $credentials = json_decode(file_get_contents($serviceAccountFile), true);
    $projectId = $credentials['project_id'];
    $url = "https://fcm.googleapis.com/v1/projects/" . $projectId . "/messages:send";

    $messagePayload = [
        'token' => $fcm_key,
        'data' => [
            "title" => $title,
            "body"  => $body,
            "image" => "",
            "extra" => ""
        ]
    ];
    
    $postData = json_encode(["message" => $messagePayload]);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . $accessToken,
        'Content-Type: application/json; UTF-8'
    ]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_exec($ch);
    curl_close($ch);
}

function session_alive(int $timeout): bool {
    if (empty($_SESSION['auth_logged_in']) || empty($_SESSION['auth_last_activity'])) return false;
    if ((time() - (int)$_SESSION['auth_last_activity']) > $timeout) {
        $_SESSION = [];
        session_destroy();
        return false;
    }
    $_SESSION['auth_last_activity'] = time();
    return true;
}

if (!session_alive(1200)) {
    if (isset($_GET['api'])) {
        die(json_encode(["status" => "unauthorized"]));
    }
    header("Location: admin_login.php");
    exit;
}

$role = $_SESSION['auth_role'] ?? '';
$sess_username = $_SESSION['auth_username'] ?? '';
$sess_password = $_SESSION['auth_password'] ?? '';

$canRead = false;
$canEdit = false;
$canDelete = false;

if ($role === 'admin') {
    $canRead = true;
    $canEdit = true;
    $canDelete = true;
} elseif ($role === 'permission') {
    $stmt = $conn->prepare("SELECT Shop_TopUP_Read, Shop_TopUP_Edit, Shop_TopUP_Delete FROM `Zabbar_Admin_Permission` WHERE username = ? AND password = ? LIMIT 1");
    if ($stmt) {
        $stmt->bind_param("ss", $sess_username, $sess_password);
        $stmt->execute();
        $res = $stmt->get_result();
        if ($row = $res->fetch_assoc()) {
            $canRead = (strtolower(trim($row['Shop_TopUP_Read'] ?? '')) === 'yes' || $row['Shop_TopUP_Read'] == 1);
            $canEdit = (strtolower(trim($row['Shop_TopUP_Edit'] ?? '')) === 'yes' || $row['Shop_TopUP_Edit'] == 1);
            $canDelete = (strtolower(trim($row['Shop_TopUP_Delete'] ?? '')) === 'yes' || $row['Shop_TopUP_Delete'] == 1);
        }
        $stmt->close();
    }
}

if (isset($_GET['api'])) {
    header('Content-Type: application/json');
    
    if (!$canRead) {
        echo json_encode(["status" => "error", "message" => "Permission denied."]);
        exit;
    }

    $action = $_GET['api'];

    if ($action === 'fetch') {
        $sql = "SELECT t.*, u.username AS live_username FROM topup_orders t LEFT JOIN users u ON t.user_token = u.token ORDER BY t.id DESC";
        $result = $conn->query($sql);
        $data = [];
        if ($result) {
            while ($row = $result->fetch_assoc()) {
                $data[] = $row;
            }
        }
        echo json_encode(["status" => "success", "data" => $data]);
        exit;
    }

    if ($action === 'add' && $_SERVER['REQUEST_METHOD'] === 'POST') {
        if (!$canEdit) {
            echo json_encode(["status" => "error", "message" => "Permission denied to add."]);
            exit;
        }

        $product_id = (int)($_POST['product_id'] ?? 0);
        $user_token = trim($_POST['user_token'] ?? '');
        $username = trim($_POST['username'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $product_title = trim($_POST['product_title'] ?? '');
        $product_price = (float)($_POST['product_price'] ?? 0);
        $discount_price = (float)($_POST['discount_price'] ?? 0);
        $balance_deducted = (float)($_POST['balance_deducted'] ?? 0);
        $winning_deducted = (float)($_POST['winning_deducted'] ?? 0);
        $topup_uid = trim($_POST['topup_uid'] ?? '');
        $order_date = date("Y-m-d H:i:s");
        $status = trim($_POST['status'] ?? 'pending');

        if ($status === 'failed' && !empty($user_token)) {
            $uStmt = $conn->prepare("UPDATE users SET balance = balance + ?, winning = winning + ? WHERE token = ?");
            if ($uStmt) {
                $uStmt->bind_param("dds", $balance_deducted, $winning_deducted, $user_token);
                $uStmt->execute();
                $uStmt->close();
            }
        }

        $stmt = $conn->prepare("INSERT INTO topup_orders (product_id, user_token, username, email, product_title, product_price, discount_price, balance_deducted, winning_deducted, topup_uid, order_date, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        if ($stmt) {
            $stmt->bind_param("issssddddsss", $product_id, $user_token, $username, $email, $product_title, $product_price, $discount_price, $balance_deducted, $winning_deducted, $topup_uid, $order_date, $status);
            if ($stmt->execute()) {
                if ($status === 'success') {
                    $notiTitle = "🎉 " . $product_title . " টপ-আপ সফল";
                    $notiBody  = "আপনার " . $product_title . " টপ-আপ অর্ডার সফলভাবে সম্পন্ন হয়েছে। আমাদের সেবা ব্যবহার করার জন্য ধন্যবাদ! ❤️";
                } elseif ($status === 'failed') {
                    $notiTitle = "❌ " . $product_title . " টপ-আপ বাতিল";
                    $notiBody  = "দুঃখিত, আপনার " . $product_title . " টপ-আপ অর্ডারটি সম্পন্ন করা সম্ভব হয়নি। প্রয়োজনে অর্ডারটি পুনরায় করুন বা সাপোর্টের সাথে যোগাযোগ করুন।";
                } else {
                    $notiTitle = "ℹ️ টপ-আপ আপডেট";
                    $notiBody  = "আপনার " . $product_title . " টপ-আপের স্ট্যাটাস: " . $status;
                }
                sendOrderNotification($conn, $user_token, $notiTitle, $notiBody);
                echo json_encode(["status" => "success"]);
            } else {
                echo json_encode(["status" => "error", "message" => "Failed to add order."]);
            }
            $stmt->close();
        } else {
            echo json_encode(["status" => "error", "message" => $conn->error]);
        }
        exit;
    }

    if ($action === 'update' && $_SERVER['REQUEST_METHOD'] === 'POST') {
        if (!$canEdit) {
            echo json_encode(["status" => "error", "message" => "Edit permission denied."]);
            exit;
        }

        $id = (int)$_POST['id'];
        $product_id = (int)($_POST['product_id'] ?? 0);
        $user_token = trim($_POST['user_token'] ?? '');
        $username = trim($_POST['username'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $product_title = trim($_POST['product_title'] ?? '');
        $product_price = (float)($_POST['product_price'] ?? 0);
        $discount_price = (float)($_POST['discount_price'] ?? 0);
        $balance_deducted = (float)($_POST['balance_deducted'] ?? 0);
        $winning_deducted = (float)($_POST['winning_deducted'] ?? 0);
        $topup_uid = trim($_POST['topup_uid'] ?? '');
        $new_status = trim($_POST['status'] ?? 'pending');

        $checkStmt = $conn->prepare("SELECT status, balance_deducted, winning_deducted, user_token FROM topup_orders WHERE id = ? LIMIT 1");
        if ($checkStmt) {
            $checkStmt->bind_param("i", $id);
            $checkStmt->execute();
            $cRes = $checkStmt->get_result()->fetch_assoc();
            $checkStmt->close();

            if ($cRes) {
                $old_status = $cRes['status'];
                $current_balance_deducted = (float)$cRes['balance_deducted'];
                $current_winning_deducted = (float)$cRes['winning_deducted'];
                $current_token = $cRes['user_token'];

                if ($old_status === 'success' && $new_status === 'failed') {
                    echo json_encode(["status" => "error", "message" => "Success status cannot be changed to Failed."]);
                    exit;
                }

                if ($old_status === 'pending' && $new_status === 'failed') {
                    if (!empty($current_token)) {
                        $uStmt = $conn->prepare("UPDATE users SET balance = balance + ?, winning = winning + ? WHERE token = ?");
                        if ($uStmt) {
                            $uStmt->bind_param("dds", $current_balance_deducted, $current_winning_deducted, $current_token);
                            $uStmt->execute();
                            $uStmt->close();
                        }
                    }
                } elseif ($old_status === 'failed' && $new_status === 'success') {
                    if (!empty($current_token)) {
                        $uStmt = $conn->prepare("UPDATE users SET balance = balance - ?, winning = winning - ? WHERE token = ?");
                        if ($uStmt) {
                            $uStmt->bind_param("dds", $current_balance_deducted, $current_winning_deducted, $current_token);
                            $uStmt->execute();
                            $uStmt->close();
                        }
                    }
                }
            }
        }

        $stmt = $conn->prepare("UPDATE topup_orders SET product_id = ?, user_token = ?, username = ?, email = ?, product_title = ?, product_price = ?, discount_price = ?, balance_deducted = ?, winning_deducted = ?, topup_uid = ?, status = ? WHERE id = ?");
        if ($stmt) {
            $stmt->bind_param("issssddddssi", $product_id, $user_token, $username, $email, $product_title, $product_price, $discount_price, $balance_deducted, $winning_deducted, $topup_uid, $new_status, $id);
            if ($stmt->execute()) {
                if ($new_status === 'success') {
                    $notiTitle = "🎉 " . $product_title . " টপ-আপ সফল";
                    $notiBody  = "আপনার " . $product_title . " টপ-আপ অর্ডার সফলভাবে সম্পন্ন হয়েছে। আমাদের সেবা ব্যবহার করার জন্য ধন্যবাদ! ❤️";
                } elseif ($new_status === 'failed') {
                    $notiTitle = "❌ " . $product_title . " টপ-আপ বাতিল";
                    $notiBody  = "দুঃখিত, আপনার " . $product_title . " টপ-আপ অর্ডারটি সম্পন্ন করা সম্ভব হয়নি। প্রয়োজনে অর্ডারটি পুনরায় করুন বা সাপোর্টের সাথে যোগাযোগ করুন।";
                } else {
                    $notiTitle = "ℹ️ টপ-আপ আপডেট";
                    $notiBody  = "আপনার " . $product_title . " টপ-আপের স্ট্যাটাস: " . $new_status;
                }
                sendOrderNotification($conn, $user_token, $notiTitle, $notiBody);
                echo json_encode(["status" => "success"]);
            } else {
                echo json_encode(["status" => "error", "message" => "Failed to update order."]);
            }
            $stmt->close();
        } else {
            echo json_encode(["status" => "error", "message" => $conn->error]);
        }
        exit;
    }

    if ($action === 'quick_status' && $_SERVER['REQUEST_METHOD'] === 'POST') {
        if (!$canEdit) {
            echo json_encode(["status" => "error", "message" => "Permission denied."]);
            exit;
        }

        $id = (int)$_POST['id'];
        $new_status = trim($_POST['status'] ?? '');

        if (!in_array($new_status, ['success', 'failed'])) {
            echo json_encode(["status" => "error", "message" => "Invalid status requested."]);
            exit;
        }

        $checkStmt = $conn->prepare("SELECT status, balance_deducted, winning_deducted, user_token, product_title FROM topup_orders WHERE id = ? LIMIT 1");
        if ($checkStmt) {
            $checkStmt->bind_param("i", $id);
            $checkStmt->execute();
            $cRes = $checkStmt->get_result()->fetch_assoc();
            $checkStmt->close();

            if (!$cRes) {
                echo json_encode(["status" => "error", "message" => "Order not found."]);
                exit;
            }

            $old_status = $cRes['status'];
            $current_balance_deducted = (float)$cRes['balance_deducted'];
            $current_winning_deducted = (float)$cRes['winning_deducted'];
            $current_token = $cRes['user_token'];
            $current_product = $cRes['product_title'];

            if ($old_status === 'success' && $new_status === 'failed') {
                echo json_encode(["status" => "error", "message" => "Success status cannot be changed to Failed."]);
                exit;
            }

            if ($old_status === $new_status) {
                echo json_encode(["status" => "success", "message" => "Already in this status."]);
                exit;
            }

            if ($old_status === 'pending' && $new_status === 'failed') {
                if (!empty($current_token)) {
                    $uStmt = $conn->prepare("UPDATE users SET balance = balance + ?, winning = winning + ? WHERE token = ?");
                    if ($uStmt) {
                        $uStmt->bind_param("dds", $current_balance_deducted, $current_winning_deducted, $current_token);
                        $uStmt->execute();
                        $uStmt->close();
                    }
                }
            } elseif ($old_status === 'failed' && $new_status === 'success') {
                if (!empty($current_token)) {
                    $uStmt = $conn->prepare("UPDATE users SET balance = balance - ?, winning = winning - ? WHERE token = ?");
                    if ($uStmt) {
                        $uStmt->bind_param("dds", $current_balance_deducted, $current_winning_deducted, $current_token);
                        $uStmt->execute();
                        $uStmt->close();
                    }
                }
            }

            $stmt = $conn->prepare("UPDATE topup_orders SET status = ? WHERE id = ?");
            if ($stmt) {
                $stmt->bind_param("si", $new_status, $id);
                if ($stmt->execute()) {
                    if ($new_status === 'success') {
                        $notiTitle = "🎉 " . $current_product . " টপ-আপ সফল";
                        $notiBody  = "আপনার " . $current_product . " টপ-আপ অর্ডার সফলভাবে সম্পন্ন হয়েছে। আমাদের সেবা ব্যবহার করার জন্য ধন্যবাদ! ❤️";
                    } elseif ($new_status === 'failed') {
                        $notiTitle = "❌ " . $current_product . " টপ-আপ বাতিল";
                        $notiBody  = "দুঃখিত, আপনার " . $current_product . " টপ-আপ অর্ডারটি সম্পন্ন করা সম্ভব হয়নি। প্রয়োজনে অর্ডারটি পুনরায় করুন বা সাপোর্টের সাথে যোগাযোগ করুন।";
                    }
                    sendOrderNotification($conn, $current_token, $notiTitle, $notiBody);
                    echo json_encode(["status" => "success"]);
                } else {
                    echo json_encode(["status" => "error", "message" => "Failed to update status."]);
                }
                $stmt->close();
            }
        }
        exit;
    }

    if ($action === 'delete' && $_SERVER['REQUEST_METHOD'] === 'POST') {
        if (!$canDelete) {
            echo json_encode(["status" => "error", "message" => "Delete permission denied."]);
            exit;
        }
        
        $id = (int)$_POST['id'];
        $stmt = $conn->prepare("DELETE FROM topup_orders WHERE id = ?");
        if ($stmt) {
            $stmt->bind_param("i", $id);
            if ($stmt->execute()) {
                echo json_encode(["status" => "success"]);
            } else {
                echo json_encode(["status" => "error", "message" => "Failed to delete order."]);
            }
            $stmt->close();
        } else {
            echo json_encode(["status" => "error", "message" => $conn->error]);
        }
        exit;
    }
    
    exit;
}

if (!$canRead) {
    die("<!DOCTYPE html><html><head><title>Access Denied</title></head><body style='font-family:system-ui; display:grid; place-items:center; height:100vh; margin:0; background:#f8fafc;'><div style='text-align:center; padding:40px; background:#fff; border-radius:16px; box-shadow:0 10px 15px -3px rgba(0,0,0,0.1);'><h2 style='color:#be123c; margin-top:0;'>Access Denied</h2><p style='color:#334155;'>You do not have permission to view topup orders.</p><a href='index.php' style='display:inline-block; margin-top:16px; padding:10px 20px; background:#4f46e5; color:#fff; text-decoration:none; border-radius:8px; font-weight:600;'>Return Dashboard</a></div></body></html>");
}
require_once "header.php";
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TopUP Orders Management</title>
    <style>
        :root {
            --slate-50: #f8fafc;
            --slate-100: #f1f5f9;
            --slate-200: #e2e8f0;
            --slate-700: #334155;
            --slate-900: #0f172a;
            --primary: #4f46e5;
            --primary-light: #eeebff;
            --emerald-500: #10b981;
            --rose-500: #f43f5e;
            --amber-500: #f59e0b;
            --white: #ffffff;
            --shadow-sm: 0 1px 3px 0 rgba(0,0,0,0.05);
            --shadow-md: 0 4px 6px -1px rgba(0,0,0,0.05);
            --radius-md: 12px;
            --radius-lg: 16px;
        }
        * { box-sizing: border-box; margin: 0; padding: 0; font-family: 'Inter', system-ui, sans-serif; }
        body { background-color: var(--slate-50); color: var(--slate-900); display: flex; height: 100vh; overflow: hidden; }
        
        .main-content { flex-grow: 1; display: flex; flex-direction: column; overflow: hidden; }
        .header { padding: 24px 40px; background: var(--white); border-bottom: 1px solid var(--slate-200); display: flex; justify-content: space-between; align-items: center; }
        .header-title h1 { font-size: 24px; font-weight: 800; }
        .header-actions .btn-primary { padding: 10px 20px; background: var(--primary); color: white; border-radius: 8px; font-weight: 700; cursor: pointer; border: none; font-size: 14px; display: inline-flex; align-items: center; gap: 8px; transition: 0.2s; }
        .header-actions .btn-primary:hover { background: #4338ca; }
        
        .content-body { padding: 30px 40px; overflow-y: auto; flex-grow: 1; }

        /* Tabs UI */
        .tabs-container { display: flex; gap: 12px; margin-bottom: 24px; border-bottom: 1px solid var(--slate-200); padding-bottom: 16px; overflow-x: auto; scrollbar-width: none; }
        .tabs-container::-webkit-scrollbar { display: none; }
        .tab-btn { padding: 10px 18px; border-radius: 8px; font-weight: 600; font-size: 14px; color: var(--slate-700); background: var(--white); border: 1px solid var(--slate-200); cursor: pointer; transition: 0.2s; display: flex; align-items: center; gap: 8px; white-space: nowrap; }
        .tab-btn:hover { background: var(--slate-50); color: var(--primary); border-color: var(--slate-300); }
        .tab-btn.active { background: var(--primary); color: var(--white); border-color: var(--primary); box-shadow: 0 4px 10px rgba(79, 70, 229, 0.2); }
        .tab-badge { background: var(--slate-100); color: var(--slate-700); padding: 2px 8px; border-radius: 20px; font-size: 12px; font-weight: 700; transition: 0.2s; }
        .tab-btn.active .tab-badge { background: rgba(255, 255, 255, 0.25); color: var(--white); }
        
        .table-container { background: var(--white); border-radius: var(--radius-lg); border: 1px solid var(--slate-200); box-shadow: var(--shadow-sm); overflow-x: auto; margin-bottom: 20px; }
        table { width: 100%; border-collapse: collapse; text-align: left; }
        th, td { padding: 16px 24px; border-bottom: 1px solid var(--slate-100); font-size: 14px; }
        th { background: var(--slate-50); font-weight: 700; color: var(--slate-700); white-space: nowrap; }
        td { color: var(--slate-900); vertical-align: middle; font-weight: 500; }
        tr:last-child td { border-bottom: none; }
        tr:hover td { background-color: var(--slate-50); }

        .amount-badge { display: inline-flex; padding: 6px 12px; background: var(--slate-100); border-radius: 6px; font-weight: 700; color: var(--slate-900); gap: 4px; }
        .bonus-badge { display: inline-flex; padding: 6px 12px; background: #ecfdf5; border-radius: 6px; font-weight: 700; color: var(--emerald-500); gap: 4px; }
        
        .status-badge { display: inline-flex; padding: 6px 12px; border-radius: 50px; font-weight: 700; font-size: 12px; text-transform: uppercase; }
        .status-badge.pending { background: #fffbeb; color: var(--amber-500); }
        .status-badge.success { background: #ecfdf5; color: var(--emerald-500); }
        .status-badge.failed { background: #fff1f2; color: var(--rose-500); }

        .action-btns { display: flex; gap: 6px; align-items: center; }
        .icon-btn { border: none; background: none; cursor: pointer; border-radius: 8px; padding: 8px; transition: 0.2s; display: inline-flex; align-items: center; justify-content: center; }
        .icon-btn svg { width: 18px; height: 18px; }
        
        .icon-btn.edit { color: var(--primary); background: var(--primary-light); }
        .icon-btn.edit:hover { background: #dce0ff; transform: translateY(-2px); }
        
        .icon-btn.quick-success { color: #047857; background: #d1fae5; }
        .icon-btn.quick-success:hover { background: #a7f3d0; transform: translateY(-2px); }
        
        .icon-btn.quick-failed { color: #b91c1c; background: #fee2e2; }
        .icon-btn.quick-failed:hover { background: #fca5a5; transform: translateY(-2px); }

        .icon-btn.delete { color: var(--rose-500); background: #fff1f2; }
        .icon-btn.delete:hover { background: #ffe4e6; transform: translateY(-2px); }

        .modal-overlay { position: fixed; inset: 0; background: rgba(15,23,42,0.6); display: none; place-items: center; z-index: 100; backdrop-filter: blur(4px); padding: 20px; overflow-y: auto; }
        .modal { background: var(--white); width: 100%; max-width: 520px; border-radius: var(--radius-lg); box-shadow: 0 20px 25px -5px rgba(0,0,0,0.1); position: relative; margin: auto; }
        .modal-header { padding: 24px; border-bottom: 1px solid var(--slate-200); display: flex; justify-content: space-between; align-items: center; }
        .modal-header h3 { font-size: 18px; font-weight: 700; }
        .close-btn { background: none; border: none; cursor: pointer; color: var(--slate-700); }
        .close-btn svg { width: 24px; height: 24px; }
        .modal-body { padding: 24px; max-height: 70vh; overflow-y: auto; }
        
        .form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
        .form-group { display: flex; flex-direction: column; gap: 8px; margin-bottom: 16px; }
        .form-group label { font-size: 13px; font-weight: 700; color: var(--slate-700); }
        .form-control { padding: 12px 14px; border: 1px solid var(--slate-200); border-radius: 8px; font-size: 14px; outline: none; transition: 0.2s; font-family: inherit; width: 100%; background: var(--white); }
        .form-control:focus { border-color: var(--primary); box-shadow: 0 0 0 3px var(--primary-light); }

        .modal-footer { padding: 24px; border-top: 1px solid var(--slate-200); display: flex; justify-content: flex-end; gap: 12px; background: var(--slate-50); border-radius: 0 0 var(--radius-lg) var(--radius-lg); }
        .btn { padding: 10px 20px; border-radius: 8px; font-weight: 700; cursor: pointer; border: none; transition: 0.2s; font-size: 14px; }
        .btn-cancel { background: var(--slate-200); color: var(--slate-700); }
        .btn-cancel:hover { background: var(--slate-300); }
        .btn-submit { background: var(--primary); color: white; }
        .btn-submit:hover { background: #4338ca; }

        .loader { text-align: center; padding: 40px; color: var(--slate-700); font-weight: 600; font-size: 16px; }

        @media (max-width: 768px) { body { flex-direction: column; } .header { padding: 20px; } .content-body { padding: 20px; } .form-row { grid-template-columns: 1fr; gap: 0; } }
    </style>
</head>
<body>

<div class="main-content">
    <div class="header">
        <div class="header-title">
            <h1>TopUP Orders</h1>
        </div>
        <div class="header-actions">
            <?php if ($canEdit): ?>
            <button class="btn-primary" onclick="openModal('add')">
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M12 4.5v15m7.5-7.5h-15" /></svg>
                Create Manual Order
            </button>
            <?php endif; ?>
        </div>
    </div>
    
    <div class="content-body">
        <!-- Tabs Section -->
        <div class="tabs-container">
            <button class="tab-btn active" data-tab="pending" onclick="setTab('pending')">
                <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M12 6v6h4.5m4.5 0a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z" /></svg>
                Pending
                <span class="tab-badge" id="count-pending">0</span>
            </button>
            <button class="tab-btn" data-tab="success" onclick="setTab('success')">
                <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12.75 11.25 15 15 9.75M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z" /></svg>
                Success
                <span class="tab-badge" id="count-success">0</span>
            </button>
            <button class="tab-btn" data-tab="failed" onclick="setTab('failed')">
                <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="m9.75 9.75 4.5 4.5m0-4.5-4.5 4.5M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z" /></svg>
                Failed
                <span class="tab-badge" id="count-failed">0</span>
            </button>
        </div>

        <div class="table-container">
            <table>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>User (Live / Saved)</th>
                        <th>Product Title</th>
                        <th>Price & Deductions</th>
                        <th>TopUP UID</th>
                        <th>Order Date</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody id="dataTable">
                    <tr><td colspan="8" class="loader">Loading orders...</td></tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="modal-overlay" id="formModal">
    <div class="modal">
        <div class="modal-header">
            <h3 id="modalTitle">Add Order</h3>
            <button class="close-btn" onclick="closeModal()">
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18 18 6M6 6l12 12" /></svg>
            </button>
        </div>
        <div class="modal-body">
            <form id="dataForm">
                <input type="hidden" id="f_id" name="id">
                
                <div class="form-row">
                    <div class="form-group">
                        <label>Product ID</label>
                        <input type="number" class="form-control" name="product_id" id="f_product_id" required>
                    </div>
                    <div class="form-group">
                        <label>TopUP UID</label>
                        <input type="text" class="form-control" name="topup_uid" id="f_topup_uid" required>
                    </div>
                </div>

                <div class="form-group">
                    <label>User Token</label>
                    <input type="text" class="form-control" name="user_token" id="f_user_token" required>
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label>Backup Username</label>
                        <input type="text" class="form-control" name="username" id="f_username">
                    </div>
                    <div class="form-group">
                        <label>Backup Email</label>
                        <input type="email" class="form-control" name="email" id="f_email">
                    </div>
                </div>

                <div class="form-group">
                    <label>Product Title</label>
                    <input type="text" class="form-control" name="product_title" id="f_product_title" required>
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label>Product Price (৳)</label>
                        <input type="number" step="0.01" class="form-control" name="product_price" id="f_product_price" required>
                    </div>
                    <div class="form-group">
                        <label>Discount Price (৳)</label>
                        <input type="number" step="0.01" class="form-control" name="discount_price" id="f_discount_price" required>
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label>Balance Deducted (৳)</label>
                        <input type="number" step="0.01" class="form-control" name="balance_deducted" id="f_balance_deducted" required>
                    </div>
                    <div class="form-group">
                        <label>Winning Deducted (৳)</label>
                        <input type="number" step="0.01" class="form-control" name="winning_deducted" id="f_winning_deducted" required>
                    </div>
                </div>

                <div class="form-group">
                    <label>Order Status</label>
                    <select class="form-control" name="status" id="f_status">
                        <option value="pending">Pending</option>
                        <option value="success">Success</option>
                        <option value="failed">Failed</option>
                    </select>
                </div>
            </form>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-cancel" onclick="closeModal()">Cancel</button>
            <button type="button" class="btn btn-submit" id="btnSubmit" onclick="saveData()">Save Order</button>
        </div>
    </div>
</div>

<script>
    let currentMode = 'add';
    const canEdit = <?= $canEdit ? 'true' : 'false' ?>;
    const canDelete = <?= $canDelete ? 'true' : 'false' ?>;
    
    // Global array to store all fetched data and current tab tracker
    let allOrders = [];
    let currentTab = 'pending';

    // Update UI tabs
    function setTab(tabName) {
        currentTab = tabName;
        document.querySelectorAll('.tab-btn').forEach(btn => {
            btn.classList.remove('active');
            if (btn.getAttribute('data-tab') === tabName) {
                btn.classList.add('active');
            }
        });
        renderTable();
    }

    // Update Counts
    function updateTabCounts(data) {
        let pending = 0, success = 0, failed = 0;
        data.forEach(item => {
            if (item.status === 'pending') pending++;
            else if (item.status === 'success') success++;
            else if (item.status === 'failed') failed++;
        });
        document.getElementById('count-pending').innerText = pending;
        document.getElementById('count-success').innerText = success;
        document.getElementById('count-failed').innerText = failed;
    }

    function loadData() {
        const tbody = document.getElementById('dataTable');
        fetch('?api=fetch')
            .then(async res => {
                const text = await res.text();
                try { return JSON.parse(text); } 
                catch (e) { throw new Error("Invalid response"); }
            })
            .then(res => {
                if (res.status === 'success') {
                    allOrders = res.data || [];
                    updateTabCounts(allOrders);
                    renderTable();
                } else {
                    tbody.innerHTML = `<tr><td colspan="8" class="loader" style="color:var(--rose-500)">${res.message}</td></tr>`;
                }
            })
            .catch(err => {
                console.error(err);
                tbody.innerHTML = `<tr><td colspan="8" class="loader" style="color:var(--rose-500)">Failed to load data.</td></tr>`;
            });
    }

    function renderTable() {
        const tbody = document.getElementById('dataTable');
        tbody.innerHTML = '';

        // Filter data based on active tab
        const filteredData = allOrders.filter(item => item.status === currentTab);

        if (filteredData.length === 0) {
            tbody.innerHTML = `<tr><td colspan="8" class="loader">No ${currentTab} orders found.</td></tr>`;
            return;
        }

        filteredData.forEach(item => {
            let actionsHtml = '';
            if (canEdit || canDelete) {
                actionsHtml += `<div class="action-btns">`;
                
                if (canEdit) {
                    if (item.status === 'pending' || item.status === 'failed') {
                        actionsHtml += `
                            <button class="icon-btn quick-success" onclick="updateQuickStatus(${item.id}, 'success')" title="Mark Success">
                                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="m4.5 12.75 6 6 9-13.5" /></svg>
                            </button>`;
                    }
                    
                    if (item.status === 'pending') {
                        actionsHtml += `
                            <button class="icon-btn quick-failed" onclick="updateQuickStatus(${item.id}, 'failed')" title="Mark Failed">
                                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18 18 6M6 6l12 12" /></svg>
                            </button>`;
                    }

                    actionsHtml += `
                        <button class="icon-btn edit" onclick='openModal("edit", ${JSON.stringify(item).replace(/'/g, "&apos;")})' title="Edit Full Order">
                            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="m16.862 4.487 1.687-1.688a1.875 1.875 0 1 1 2.652 2.652L10.582 16.07a4.5 4.5 0 0 1-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 0 1 1.13-1.897l8.932-8.931Zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0 1 15.75 21H5.25A2.25 2.25 0 0 1 3 18.75V8.25A2.25 2.25 0 0 1 5.25 6H10" /></svg>
                        </button>`;
                }
                
                if (canDelete) {
                    actionsHtml += `
                        <button class="icon-btn delete" onclick="deleteData(${item.id})" title="Delete">
                            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 0 1-2.244 2.077H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 0 0-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 0 0-7.5 0" /></svg>
                        </button>`;
                }
                actionsHtml += `</div>`;
            }

            let displayUser = item.live_username ? item.live_username : (item.username || 'N/A');

            let tr = document.createElement('tr');
            tr.innerHTML = `
                <td>#${item.id}</td>
                <td>
                    <div style="font-weight:700; color:var(--slate-900);">${displayUser}</div>
                    <div style="font-size:11px; color:var(--slate-700); max-width:160px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;" title="${item.user_token}">${item.user_token || 'No Token'}</div>
                </td>
                <td style="font-weight:600;">${item.product_title}</td>
                <td>
                    <div class="amount-badge" style="font-size:11px; padding:2px 6px;">Reg: ৳${item.product_price}</div>
                    <div class="bonus-badge" style="font-size:11px; padding:2px 6px; margin-top:2px; display:inline-block;">Disc: ৳${item.discount_price}</div>
                    <div style="font-size:11px; margin-top:4px; color:var(--slate-700);">
                        Deducted: Bal: ৳${item.balance_deducted || 0} | Win: ৳${item.winning_deducted || 0}
                    </div>
                </td>
                <td><span style="font-family:monospace; background:var(--slate-100); padding:4px 8px; border-radius:4px; font-weight:700;">${item.topup_uid}</span></td>
                <td style="color:var(--slate-700); font-size:12px;">${item.order_date || 'N/A'}</td>
                <td><span class="status-badge ${item.status}">${item.status}</span></td>
                <td>${actionsHtml}</td>
            `;
            tbody.appendChild(tr);
        });
    }

    function updateQuickStatus(id, newStatus) {
        if (!confirm(`Are you sure you want to mark this order as ${newStatus.toUpperCase()}?`)) return;

        const formData = new FormData();
        formData.append('id', id);
        formData.append('status', newStatus);

        fetch('?api=quick_status', {
            method: 'POST',
            body: formData
        })
        .then(async res => {
            const text = await res.text();
            try { return JSON.parse(text); } 
            catch (e) { throw new Error("Invalid response from server."); }
        })
        .then(res => {
            if (res.status === 'success') {
                loadData();
            } else {
                alert(res.message || "An error occurred.");
            }
        })
        .catch(err => {
            console.error(err);
            alert("Connection error or action blocked.");
        });
    }

    function openModal(mode, data = null) {
        currentMode = mode;
        const form = document.getElementById('dataForm');
        form.reset();

        const statusSelect = document.getElementById('f_status');
        for (let option of statusSelect.options) {
            option.disabled = false;
        }

        if (mode === 'edit' && data) {
            document.getElementById('modalTitle').innerText = 'Edit / Process Order';
            document.getElementById('f_id').value = data.id;
            document.getElementById('f_product_id').value = data.product_id || '';
            document.getElementById('f_user_token').value = data.user_token || '';
            document.getElementById('f_username').value = data.username || '';
            document.getElementById('f_email').value = data.email || '';
            document.getElementById('f_product_title').value = data.product_title || '';
            document.getElementById('f_product_price').value = data.product_price || '';
            document.getElementById('f_discount_price').value = data.discount_price || '';
            document.getElementById('f_balance_deducted').value = data.balance_deducted || '0';
            document.getElementById('f_winning_deducted').value = data.winning_deducted || '0';
            document.getElementById('f_topup_uid').value = data.topup_uid || '';
            document.getElementById('f_status').value = data.status || 'pending';

            if (data.status === 'success') {
                for (let option of statusSelect.options) {
                    if (option.value === 'failed') {
                        option.disabled = true;
                    }
                }
            }
        } else {
            document.getElementById('modalTitle').innerText = 'Create Manual Order';
            document.getElementById('f_id').value = '';
            document.getElementById('f_balance_deducted').value = '0';
            document.getElementById('f_winning_deducted').value = '0';
        }
        
        document.getElementById('formModal').style.display = 'flex';
    }

    function closeModal() {
        document.getElementById('formModal').style.display = 'none';
    }

    function saveData() {
        const form = document.getElementById('dataForm');
        if (!form.reportValidity()) return;

        const formData = new FormData(form);
        const btn = document.getElementById('btnSubmit');
        const originalText = btn.innerText;
        
        btn.innerText = 'Processing...';
        btn.disabled = true;

        const apiEndpoint = currentMode === 'add' ? '?api=add' : '?api=update';

        fetch(apiEndpoint, {
            method: 'POST',
            body: formData
        })
        .then(async res => {
            const text = await res.text();
            try { return JSON.parse(text); } 
            catch (e) { throw new Error("Invalid response from server."); }
        })
        .then(res => {
            if (res.status === 'success') {
                closeModal();
                loadData();
            } else {
                alert(res.message || "An error occurred.");
            }
        })
        .catch(err => {
            console.error(err);
            alert("Connection error or action blocked.");
        })
        .finally(() => {
            btn.innerText = originalText;
            btn.disabled = false;
        });
    }

    function deleteData(id) {
        if (!confirm('Are you sure you want to permanently delete this order?')) return;

        const formData = new FormData();
        formData.append('id', id);

        fetch('?api=delete', {
            method: 'POST',
            body: formData
        })
        .then(res => res.json())
        .then(res => {
            if (res.status === 'success') {
                loadData();
            } else {
                alert(res.message || "Failed to delete.");
            }
        })
        .catch(err => console.error(err));
    }

    window.onload = loadData;
</script>
</body>
</html>