<?php
require_once "config.php";

date_default_timezone_set("Asia/Dhaka");

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (!isset($conn) || !($conn instanceof mysqli)) {
    die("Database connection error.");
}
$conn->set_charset("utf8mb4");

function e($value): string {
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

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;
}

function parseDeliveryAmount($raw): float {
    $raw = trim((string)$raw);
    if ($raw === '' || strtolower($raw) === 'free' || strtolower($raw) === 'tk') return 0.0;
    if (preg_match('/\d+\.?\d*/', $raw, $m)) return (float)$m[0];
    return 0.0;
}

function sendFCM_v1($fcm_key, $title, $body) {
    if (empty($fcm_key)) return false;

    $serviceAccountFile = 'noti.json';
    if (!file_exists($serviceAccountFile)) return false;

    $credentials = json_decode(file_get_contents($serviceAccountFile), true);
    if (
        !$credentials ||
        empty($credentials['private_key']) ||
        empty($credentials['client_email']) ||
        empty($credentials['project_id'])
    ) {
        return false;
    }

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

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

    $header = json_encode(['alg' => 'RS256', 'typ' => 'JWT'], JSON_UNESCAPED_SLASHES);
    $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
    ], JSON_UNESCAPED_SLASHES);

    $unsignedJwt = $base64url($header) . "." . $base64url($payload);
    $signature = '';
    openssl_sign($unsignedJwt, $signature, $privateKey, OPENSSL_ALGO_SHA256);
    $jwt = $unsignedJwt . "." . $base64url($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);
    $tokenResponse = curl_exec($ch);
    curl_close($ch);

    $tokenData = json_decode($tokenResponse, true);
    $accessToken = $tokenData['access_token'] ?? null;
    if (!$accessToken) return false;

    $url = "https://fcm.googleapis.com/v1/projects/{$projectId}/messages:send";

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

    $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; charset=UTF-8'
    ]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    $result = curl_exec($ch);
    curl_close($ch);

    return $result;
}

$sessionTimeout = 1200;

if (!session_alive($sessionTimeout)) {
    if (isset($_GET['api'])) {
        header('Content-Type: application/json; charset=UTF-8');
        echo json_encode(["status" => "unauthorized"], JSON_UNESCAPED_UNICODE);
        exit;
    }
    header("Location: admin_login.php");
    exit;
}

$role = (string)($_SESSION['auth_role'] ?? '');
$sess_username = (string)($_SESSION['auth_username'] ?? '');
$sess_password = (string)($_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_Product_Read, Shop_Product_Edit, Shop_Product_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_Product_Read'] ?? '')) === 'yes' || $row['Shop_Product_Read'] == 1);
            $canEdit = (strtolower(trim($row['Shop_Product_Edit'] ?? '')) === 'yes' || $row['Shop_Product_Edit'] == 1);
            $canDelete = (strtolower(trim($row['Shop_Product_Delete'] ?? '')) === 'yes' || $row['Shop_Product_Delete'] == 1);
        }
        $stmt->close();
    }
}

$modules = [
    ['file' => 'index.php', 'label' => 'Dashboard'],
    ['file' => 'addtnx.php', 'label' => 'Add Transaction', 'mode' => 'admin_only'],
    ['file' => 'product_orders.php', 'label' => 'Product Orders', 'mode' => 'admin_only'],
    ['file' => 'UserInfo.php', 'label' => 'User Info', 'permissions' => ['members_read', 'members_edit', 'members_delete']],
    ['file' => 'moneyhistory.php', 'label' => 'Addmoney History', 'permissions' => ['addmoney_history_read', 'addmoney_history_edit', 'addmoney_history_delete']],
    ['file' => 'withdrawal_history.php', 'label' => 'Withdrawal History', 'permissions' => ['withdrawal_history_read', 'withdrawal_history_edit', 'withdrawal_history_delete']],
    ['file' => 'refound_history.php', 'label' => 'Refund Management', 'permissions' => ['refund_history_read', 'refund_history_delete', 'refund_send']],
    ['file' => 'zabbarnotification.php', 'label' => 'Notification Panel', 'permissions' => ['notification_send']],
    ['file' => 'announcements.php', 'label' => 'Announcements', 'permissions' => ['app_settings_edit']],
    ['file' => 'Settings.php', 'label' => 'App Settings', 'permissions' => ['app_settings_read', 'app_settings_edit']],
    ['file' => 'image_slider.php', 'label' => 'Image Slider', 'permissions' => ['slider_read', 'slider_edit', 'slider_delete']],
    ['file' => 'DailogSlider.php', 'label' => 'Dialog Slider', 'permissions' => ['dialog_slider_read', 'dialog_slider_edit', 'dialog_slider_delete']],
    ['file' => 'deposit_bonus.php', 'label' => 'Deposit Bonus', 'permissions' => ['deposit_bonus_read', 'deposit_bonus_edit', 'deposit_bonus_delete']],
    ['file' => 'category.php', 'label' => 'Category', 'permissions' => ['category_add', 'category_edit', 'category_delete']],
    ['file' => 'shop_product.php', 'label' => 'Shop Product', 'permissions' => ['Shop_Product_Read', 'Shop_Product_Edit', 'Shop_Product_Delete']],
    ['file' => 'topup_list.php', 'label' => 'Topup List', 'permissions' => ['Shop_TopUP_Read', 'Shop_TopUP_Edit', 'Shop_TopUP_Delete']],
    ['file' => 'topup_order.php', 'label' => 'Topup Order', 'permissions' => ['Shop_TopUP_Read', 'Shop_TopUP_Edit', 'Shop_TopUP_Delete']],
    ['file' => 'gift_requests.php', 'label' => 'Gift Requests', 'permissions' => ['Geft_Read', 'Geft_Edit', 'Geft_Delete']],
    ['file' => 'create_match.php', 'label' => 'Create Match', 'check_match_data' => true],
    ['file' => 'schedule_match.php', 'label' => 'Schedule Match', 'check_match_data' => true]
];

$visibleModules = [];
foreach ($modules as $module) {
    if ($role === 'admin') {
        $visibleModules[] = $module;
    } elseif (($module['mode'] ?? '') !== 'admin_only') {
        if ($module['file'] === 'index.php') {
            $visibleModules[] = $module;
        } elseif (!empty($module['permissions']) && $role === 'permission') {
            $visibleModules[] = $module;
        } elseif (!empty($module['check_match_data'])) {
            $visibleModules[] = $module;
        }
    }
}

if (isset($_GET['api'])) {
    header('Content-Type: application/json; charset=UTF-8');

    if (!$canRead) {
        echo json_encode(["status" => "error", "message" => "Permission denied."], JSON_UNESCAPED_UNICODE);
        exit;
    }

    $action = $_GET['api'];

    if ($action === 'fetch') {
        $limit = 50;
        $page = max(1, (int)($_GET['page'] ?? 1));
        $offset = ($page - 1) * $limit;
        
        $tab = isset($_GET['tab']) ? strtolower(trim($_GET['tab'])) : 'pending';
        $validTabs = ['pending', 'success', 'failed'];
        if (!in_array($tab, $validTabs)) $tab = 'pending';

        // Count queries for Tabs
        $counts = ['pending' => 0, 'success' => 0, 'failed' => 0];
        $countQuery = $conn->query("SELECT status, COUNT(id) as c FROM product_orders GROUP BY status");
        if ($countQuery) {
            while ($row = $countQuery->fetch_assoc()) {
                $s = strtolower(trim($row['status']));
                if (isset($counts[$s])) {
                    $counts[$s] = (int)$row['c'];
                }
            }
        }

        $totalRows = $counts[$tab];
        $totalPages = max(1, (int)ceil($totalRows / $limit));

        $sql = "
            SELECT 
                po.id, po.order_id, po.user_id, po.product_id, po.product_title, po.product_image,
                po.amount, po.address, po.extra_json, po.status, po.created_at,
                p.discount, p.DeliveryFree,
                u.username, u.uid
            FROM product_orders po
            LEFT JOIN products p ON LOWER(TRIM(p.title)) = LOWER(TRIM(po.product_title))
            LEFT JOIN users u ON po.user_id = u.token
            WHERE LOWER(TRIM(po.status)) = ?
            ORDER BY po.id DESC
            LIMIT ? OFFSET ?
        ";

        $stmt = $conn->prepare($sql);
        if ($stmt) {
            $stmt->bind_param("sii", $tab, $limit, $offset);
            $stmt->execute();
            $result = $stmt->get_result();

            $data = [];
            while ($row = $result->fetch_assoc()) {
                $data[] = $row;
            }
            $stmt->close();

            echo json_encode([
                "status" => "success",
                "data" => $data,
                "counts" => $counts,
                "totalPages" => $totalPages,
                "currentPage" => $page
            ], JSON_UNESCAPED_UNICODE);
        } else {
            echo json_encode(["status" => "error", "message" => "Failed to prepare database query."], JSON_UNESCAPED_UNICODE);
        }
        exit;
    }

    if ($action === 'process' && $_SERVER['REQUEST_METHOD'] === 'POST') {
        $id = (int)($_POST['id'] ?? 0);
        $type = strtolower(trim($_POST['type'] ?? ''));

        if (($type === 'success' || $type === 'failed') && !$canEdit) {
            echo json_encode(["status" => "error", "message" => "Edit permission denied."], JSON_UNESCAPED_UNICODE);
            exit;
        }

        if ($type === 'delete' && !$canDelete) {
            echo json_encode(["status" => "error", "message" => "Delete permission denied."], JSON_UNESCAPED_UNICODE);
            exit;
        }

        $conn->begin_transaction();

        try {
            $stmt = $conn->prepare("
                SELECT po.user_id, po.status, po.product_title, p.discount, p.DeliveryFree
                FROM product_orders po
                LEFT JOIN products p ON LOWER(TRIM(p.title)) = LOWER(TRIM(po.product_title))
                WHERE po.id = ? FOR UPDATE
            ");
            $stmt->bind_param("i", $id);
            $stmt->execute();
            $order = $stmt->get_result()->fetch_assoc();
            $stmt->close();

            if (!$order) {
                throw new Exception("Order not found in database.");
            }

            $current_status = strtolower(trim($order['status'] ?? 'pending'));
            $user_token = (string)$order['user_id'];
            $product_title = (string)($order['product_title'] ?? 'Unknown Product');
            $discount = (float)($order['discount'] ?? 0);
            $deliveryAmount = parseDeliveryAmount($order['DeliveryFree'] ?? '0');
            $amount = $discount + $deliveryAmount;

            if ($amount <= 0) {
                throw new Exception("Order amount is zero, cannot process.");
            }

            $stmtUser = $conn->prepare("SELECT fcm_key, username, ban_reason, balance FROM users WHERE token = ? FOR UPDATE");
            $stmtUser->bind_param("s", $user_token);
            $stmtUser->execute();
            $userData = $stmtUser->get_result()->fetch_assoc();
            $stmtUser->close();

            if (!$userData) {
                throw new Exception("User associated with this order does not exist.");
            }

            if (strtolower(trim($userData['ban_reason'] ?? '')) === 'ban') {
                throw new Exception("User account is banned.");
            }

            $fcmKey = $userData['fcm_key'] ?? '';

            if ($type === 'success') {
                if ($current_status === 'success') {
                    throw new Exception("This order is already marked as success.");
                }

                if ($current_status === 'failed') {
                    if ((float)$userData['balance'] < $amount) {
                        throw new Exception("User does not have enough balance to re-approve this order.");
                    }
                    $stmt = $conn->prepare("UPDATE users SET balance = balance - ? WHERE token = ?");
                    $stmt->bind_param("ds", $amount, $user_token);
                    $stmt->execute();
                    $stmt->close();
                }

                $stmt = $conn->prepare("UPDATE product_orders SET status = 'success' WHERE id = ?");
                $stmt->bind_param("i", $id);
                $stmt->execute();
                $stmt->close();

                if (!empty($fcmKey)) {
                    $notiTitle = "✅ পণ্য অর্ডার সফল";
                    $notiBody = "অভিনন্দন! আপনার {$product_title} অর্ডারটি সফলভাবে সম্পন্ন হয়েছে। অর্ডারটি প্রক্রিয়াকরণ করা হয়েছে। আমাদের সাথে থাকার জন্য ধন্যবাদ। ❤️";
                    sendFCM_v1($fcmKey, $notiTitle, $notiBody);
                }

                $msg = "Order successfully marked as Success.";
            } elseif ($type === 'failed') {
                if ($current_status === 'success') {
                    throw new Exception("Cannot fail an already successful order directly.");
                }
                if ($current_status === 'failed') {
                    throw new Exception("This order is already failed.");
                }

                if ($current_status === 'pending') {
                    $stmt = $conn->prepare("UPDATE users SET balance = balance + ? WHERE token = ?");
                    $stmt->bind_param("ds", $amount, $user_token);
                    $stmt->execute();
                    $stmt->close();
                }

                $stmt = $conn->prepare("UPDATE product_orders SET status = 'failed' WHERE id = ?");
                $stmt->bind_param("i", $id);
                $stmt->execute();
                $stmt->close();

                if (!empty($fcmKey)) {
                    $notiTitle = "❌ পণ্য অর্ডার ব্যর্থ";
                    $notiBody = "দুঃখিত! আপনার {$product_title} অর্ডারটি সম্পন্ন করা যায়নি। আপনার একাউন্টে ব্যালেন্স রিটার্ন করা হয়েছে। অনুগ্রহ করে আবার চেষ্টা করুন বা সাপোর্টে যোগাযোগ করুন।";
                    sendFCM_v1($fcmKey, $notiTitle, $notiBody);
                }

                $msg = "Order failed. ৳{$amount} has been refunded to the user.";
            } elseif ($type === 'delete') {
                $stmt = $conn->prepare("DELETE FROM product_orders WHERE id = ?");
                $stmt->bind_param("i", $id);
                $stmt->execute();
                $stmt->close();

                $msg = "Order deleted successfully.";
            } else {
                throw new Exception("Invalid action type.");
            }

            $conn->commit();
            echo json_encode(["status" => "success", "message" => $msg], JSON_UNESCAPED_UNICODE);
        } catch (Exception $e) {
            $conn->rollback();
            echo json_encode(["status" => "error", "message" => $e->getMessage()], JSON_UNESCAPED_UNICODE);
        }
        exit;
    }

    echo json_encode(["status" => "error", "message" => "Invalid request."], JSON_UNESCAPED_UNICODE);
    exit;
}

if (!$canRead) {
    die("<!DOCTYPE html><html><head><meta charset='UTF-8'><title>Access Denied</title><style>body{font-family:system-ui;background:#f8fafc;margin:0;display:grid;place-items:center;min-height:100vh}.box{background:#fff;padding:36px 28px;border-radius:18px;box-shadow:0 10px 20px rgba(0,0,0,.08);max-width:520px;text-align:center}h2{margin:0 0 10px;color:#be123c}p{color:#334155;line-height:1.7;margin:0 0 18px}a{display:inline-block;padding:10px 18px;background:#4f46e5;color:#fff;text-decoration:none;border-radius:10px;font-weight:700}</style></head><body><div class='box'><h2>Access Denied</h2><p>You do not have permission to view product orders.</p><a href='index.php'>Return Dashboard</a></div></body></html>");
}
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Product Orders Management</title>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <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:'Plus Jakarta Sans',sans-serif}
        body{
            background:var(--slate-50);
            color:var(--slate-900);
            min-height:100vh;
            overflow-x:hidden;
            display: flex;
        }
        ::-webkit-scrollbar{width:8px;height:8px}
        ::-webkit-scrollbar-thumb{background:#cbd5e1;border-radius:999px}

        .sidebar{
            width:260px;
            background:var(--white);
            position:fixed;
            left:0;
            top:0;
            height:100vh;
            z-index:100;
            border-right:1px solid var(--slate-200);
            display:flex;
            flex-direction:column;
        }
        .sidebar-header{
            padding:20px 18px 14px;
            border-bottom:1px solid var(--slate-100);
        }
        .sidebar-header h2{
            font-size:18px;
            font-weight:800;
            color:var(--slate-900);
            display:flex;
            align-items:center;
            gap:10px;
        }
        .sidebar-menu{
            padding:14px;
            overflow:auto;
            display:flex;
            flex-direction:column;
            gap:6px;
        }
        .menu-item{
            display:flex;
            align-items:center;
            gap:12px;
            padding:12px 14px;
            color:var(--slate-700);
            text-decoration:none;
            border-radius:12px;
            font-weight:600;
            font-size:14px;
            transition:.2s ease;
        }
        .menu-item i{width:18px;text-align:center}
        .menu-item:hover,.menu-item.active{
            background:var(--primary-light);
            color:var(--primary);
        }

        .main-content{
            margin-left:260px;
            min-height:100vh;
            padding:24px 32px;
            width: calc(100% - 260px);
            display: flex;
            flex-direction: column;
        }

        .header-section {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 24px;
        }
        
        .header-title h1 { font-size: 24px; font-weight: 800; color: var(--slate-900); }
        .header-title p { color: var(--slate-700); font-size: 14px; margin-top: 4px; }

        /* 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: #cbd5e1; }
        .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); }

        .wrap{
            background:var(--white);
            border:1px solid var(--slate-200);
            border-radius:var(--radius-lg);
            box-shadow:var(--shadow-sm);
            overflow:hidden;
            display: flex;
            flex-direction: column;
            flex: 1;
        }

        .table-scroll{
            width:100%;
            overflow-x:auto;
        }

        table{
            width:100%;
            min-width:1050px;
            border-collapse:collapse;
            text-align:left;
        }

        thead th{
            background:var(--slate-50);
            color:var(--slate-700);
            font-size:13px;
            font-weight: 700;
            padding:16px 20px;
            border-bottom:1px solid var(--slate-200);
            white-space: nowrap;
        }

        tbody td{
            padding:16px 20px;
            border-bottom:1px solid var(--slate-100);
            vertical-align:middle;
            font-size:14px;
        }
        tbody tr:last-child td { border-bottom: none; }
        tbody tr:hover{background:var(--slate-50)}

        .muted{color:var(--slate-700);font-size:12px}
        .idbox{
            font-family:ui-monospace,SFMono-Regular,Menlo,monospace;
            font-size:13px;
            color:var(--slate-900);
            font-weight: 600;
        }

        .user{
            display:flex;
            flex-direction:column;
            gap:6px;
        }
        .user .name{
            font-weight:700;
            font-size:14px;
            color: var(--slate-900);
        }
        .chip{
            display:inline-flex;
            width:fit-content;
            padding:4px 8px;
            border-radius:6px;
            font-size:11px;
            font-weight:700;
            border:1px solid var(--slate-200);
            background:var(--slate-50);
            color:var(--slate-700);
        }
        .addr{
            display:flex;
            gap:6px;
            font-size: 12px;
            color:var(--slate-700);
            margin-top: 4px;
        }

        .prod{
            display:flex;
            gap:12px;
            align-items:center;
        }
        .prod img{
            width:48px;
            height:48px;
            object-fit:cover;
            border-radius:10px;
            border:1px solid var(--slate-200);
            background:var(--slate-50);
            flex:0 0 auto;
        }
        .prod-title{
            font-weight:700;
            font-size: 14px;
            margin-bottom:4px;
            color:var(--slate-900);
            display:-webkit-box;
            -webkit-line-clamp:2;
            -webkit-box-orient:vertical;
            overflow:hidden;
        }
        .price{
            color:var(--emerald-500);
            font-weight:700;
            font-size: 13px;
        }

        .status-badge {
            display:inline-flex;
            padding:6px 12px;
            border-radius:50px;
            font-size:12px;
            font-weight:700;
            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)}

        .date{
            display:flex;
            align-items:center;
            gap:6px;
            margin-top:8px;
            color:var(--slate-700);
            font-size:12px;
            font-weight: 500;
        }

        .action-btns { display: flex; gap: 8px; justify-content: flex-end; align-items: center; }
        .icon-btn { 
            border: none; 
            background: none; 
            cursor: pointer; 
            border-radius: 8px; 
            padding: 8px 12px; 
            transition: 0.2s; 
            display: inline-flex; 
            align-items: center; 
            justify-content: center; 
            font-size: 13px;
            font-weight: 600;
            gap: 6px;
        }
        .icon-btn:disabled { opacity: 0.5; cursor: not-allowed; transform: none !important; }
        
        .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); }

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

        .pager{
            display:flex;
            justify-content:space-between;
            align-items:center;
            gap:12px;
            padding:16px 24px;
            border-top:1px solid var(--slate-200);
            background:var(--slate-50);
            border-radius: 0 0 var(--radius-lg) var(--radius-lg);
        }
        .pagebtn{
            border:1px solid var(--slate-200);
            background:var(--white);
            color: var(--slate-700);
            padding:8px 16px;
            border-radius:8px;
            cursor:pointer;
            font-weight:600;
            font-size: 13px;
            transition: 0.2s;
        }
        .pagebtn:hover:not(:disabled) { background: var(--slate-100); color: var(--slate-900); }
        .pagebtn:disabled{opacity:.5;cursor:not-allowed;}

        .toastbox{
            position:fixed;
            right:24px;
            bottom:24px;
            z-index:9999;
            display:flex;
            flex-direction:column;
            gap:10px;
        }
        .toast{
            padding:14px 20px;
            border-radius:12px;
            color:#fff;
            box-shadow:0 10px 25px rgba(0,0,0,.15);
            font-weight:600;
            max-width:360px;
            font-size: 14px;
            transition:.25s ease;
        }
        .toast.success{background:var(--emerald-500)}
        .toast.error{background:var(--rose-500)}

        .jsonbox{
            margin-top:12px;
            padding:12px;
            border:1px dashed var(--slate-200);
            border-radius:10px;
            background:var(--slate-50);
        }
        .json-grid{
            display:flex;
            flex-wrap:wrap;
            gap:8px;
        }
        .json-item{
            display:flex;
            gap:6px;
            align-items:center;
            padding:6px 10px;
            border-radius:6px;
            border:1px solid var(--slate-200);
            background:var(--white);
            font-size:12px;
        }
        .json-key{
            color:var(--slate-700);
            font-weight:700;
        }
        .json-val{
            color:var(--slate-900);
            font-weight:600;
        }
        .json-raw{
            font-family:ui-monospace,SFMono-Regular,Menlo,monospace;
            font-size:12px;
            color:var(--slate-700);
            white-space:pre-wrap;
            word-break:break-word;
        }

        @media (max-width:768px){
            body { flex-direction: column; }
            .sidebar{
                position:relative;
                width:100%;
                height:auto;
                border-right:none;
                border-bottom:1px solid var(--slate-200);
            }
            .sidebar-menu{
                flex-direction:row;
                overflow-x:auto;
                padding:12px;
                gap:8px;
            }
            .menu-item{
                white-space:nowrap;
                flex:0 0 auto;
            }
            .main-content{
                margin-left:0;
                padding:16px;
                width: 100%;
            }
            .header-section{
                flex-direction:column;
                align-items:flex-start;
                gap: 12px;
            }
            .pager{
                flex-direction:column;
                align-items:stretch;
                text-align: center;
            }
            .action-btns{
                justify-content:flex-start;
            }
            th, td { padding: 12px; }
        }
    </style>
</head>
<body>

<div class="sidebar">
    <div class="sidebar-header">
        <h2><i class="fa-solid fa-gamepad"></i> Admin Panel</h2>
    </div>
    <div class="sidebar-menu">
        <?php $currentPage = basename($_SERVER['PHP_SELF']); ?>
        <?php foreach ($visibleModules as $module): ?>
            <?php $isActive = ($currentPage === $module['file']) ? 'active' : ''; ?>
            <a href="<?= e($module['file']) ?>" class="menu-item <?= $isActive ?>">
                <?php
                    $label = strtolower((string)$module['label']);
                    if (strpos($label, 'dashboard') !== false) echo '<i class="fa-solid fa-house"></i>';
                    elseif (strpos($label, 'user') !== false || strpos($label, 'member') !== false) echo '<i class="fa-solid fa-users"></i>';
                    elseif (strpos($label, 'product') !== false || strpos($label, 'shop') !== false) echo '<i class="fa-solid fa-cart-shopping"></i>';
                    else echo '<i class="fa-solid fa-circle-dot"></i>';
                ?>
                <span><?= e($module['label']) ?></span>
            </a>
        <?php endforeach; ?>
    </div>
</div>

<div class="main-content">
    <div class="header-section">
        <div class="header-title">
            <h1>Product Orders</h1>
            <p>Manage and track physical product orders</p>
        </div>
    </div>

    <!-- Tabs UI -->
    <div class="tabs-container">
        <button class="tab-btn active" data-tab="pending" onclick="setTab('pending')">
            <i class="fa-regular fa-clock"></i> Pending 
            <span class="tab-badge" id="count-pending">0</span>
        </button>
        <button class="tab-btn" data-tab="success" onclick="setTab('success')">
            <i class="fa-solid fa-check"></i> Success 
            <span class="tab-badge" id="count-success">0</span>
        </button>
        <button class="tab-btn" data-tab="failed" onclick="setTab('failed')">
            <i class="fa-solid fa-xmark"></i> Failed 
            <span class="tab-badge" id="count-failed">0</span>
        </button>
    </div>

    <div class="wrap">
        <div id="loader" class="loader">Loading...</div>

        <div class="table-scroll">
            <table id="dataTable" style="display:none;">
                <colgroup>
                    <col style="width:12%">
                    <col style="width:23%">
                    <col style="width:35%">
                    <col style="width:15%">
                    <col style="width:15%">
                </colgroup>
                <thead>
                    <tr>
                        <th>Order ID</th>
                        <th>User Details</th>
                        <th>Product Details</th>
                        <th>Status & Date</th>
                        <th style="text-align:right;">Actions</th>
                    </tr>
                </thead>
                <tbody id="dataBody"></tbody>
            </table>
        </div>

        <div class="pager" id="pager" style="display:none;">
            <div class="muted" id="pageInfo" style="font-weight: 600;">Page 1</div>
            <div style="display:flex;gap:8px;flex-wrap:wrap;">
                <button class="pagebtn" id="prevBtn">Previous</button>
                <button class="pagebtn" id="nextBtn">Next</button>
            </div>
        </div>
    </div>
</div>

<div class="toastbox" id="toastBox"></div>

<script>
const canEdit = <?= $canEdit ? 'true' : 'false' ?>;
const canDelete = <?= $canDelete ? 'true' : 'false' ?>;
let currentPage = 1;
let totalPages = 1;
let currentTab = 'pending';

function escapeHtml(str) {
    return String(str ?? '')
        .replaceAll('&', '&amp;')
        .replaceAll('<', '&lt;')
        .replaceAll('>', '&gt;')
        .replaceAll('"', '&quot;')
        .replaceAll("'", '&#039;');
}

function parseDeliveryAmount(raw) {
    if (!raw) return 0;
    raw = String(raw).trim();
    if (raw.toLowerCase() === 'free' || raw.toLowerCase() === 'tk') return 0;
    const m = raw.match(/\d+\.?\d*/);
    return m ? parseFloat(m[0]) : 0;
}

function toast(msg, type='success') {
    const box = document.getElementById('toastBox');
    const el = document.createElement('div');
    el.className = `toast ${type}`;
    el.textContent = msg;
    box.appendChild(el);

    setTimeout(() => {
        el.style.opacity = '0';
        el.style.transform = 'translateX(20px)';
        setTimeout(() => el.remove(), 250);
    }, 2800);
}

function renderExtraJson(raw) {
    if (!raw) return '';

    try {
        const parsed = JSON.parse(raw);

        if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
            const items = Object.entries(parsed).map(([key, value]) => {
                const niceKey = key.replace(/_/g, ' ').replace(/\b\w/g, ch => ch.toUpperCase());
                let niceValue = value;
                if (typeof niceValue === 'object' && niceValue !== null) {
                    niceValue = JSON.stringify(niceValue);
                }
                return `
                    <div class="json-item">
                        <span class="json-key">${escapeHtml(niceKey)}:</span>
                        <span class="json-val">${escapeHtml(niceValue)}</span>
                    </div>
                `;
            }).join('');

            return `<div class="jsonbox"><div class="json-grid">${items}</div></div>`;
        }

        return `<div class="jsonbox"><div class="json-raw">${escapeHtml(raw)}</div></div>`;
    } catch (e) {
        return `<div class="jsonbox"><div class="json-raw">${escapeHtml(raw)}</div></div>`;
    }
}

function renderPagination() {
    document.getElementById('pageInfo').textContent = `Page ${currentPage} of ${totalPages}`;
    document.getElementById('prevBtn').disabled = currentPage <= 1;
    document.getElementById('nextBtn').disabled = currentPage >= totalPages;
    document.getElementById('pager').style.display = totalPages > 0 ? 'flex' : 'none';
}

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');
        }
    });
    loadData(1);
}

function updateTabCounts(counts) {
    document.getElementById('count-pending').innerText = counts.pending || 0;
    document.getElementById('count-success').innerText = counts.success || 0;
    document.getElementById('count-failed').innerText = counts.failed || 0;
}

function loadData(page=1) {
    currentPage = page;
    document.getElementById('loader').style.display = 'block';
    document.getElementById('loader').innerHTML = 'Loading...';
    document.getElementById('dataTable').style.display = 'none';

    fetch(`?api=fetch&tab=${currentTab}&page=${page}&t=${Date.now()}`)
        .then(r => r.json())
        .then(res => {
            document.getElementById('loader').style.display = 'none';

            if (res.status !== 'success') {
                document.getElementById('loader').style.display = 'block';
                document.getElementById('loader').innerHTML = `<span style="color:#e11d48;">${escapeHtml(res.message || 'Failed')}</span>`;
                return;
            }

            totalPages = res.totalPages || 1;
            updateTabCounts(res.counts || {});
            renderTable(res.data || []);
            renderPagination();
            document.getElementById('dataTable').style.display = 'table';
        })
        .catch(() => {
            document.getElementById('loader').style.display = 'block';
            document.getElementById('loader').innerHTML = `<span style="color:#e11d48;">Connection error.</span>`;
        });
}

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

    if (!data.length) {
        tbody.innerHTML = `<tr><td colspan="5" style="padding:48px 16px;text-align:center;color:#64748b;">No ${currentTab} orders found.</td></tr>`;
        return;
    }

    let html = '';
    data.forEach(item => {
        const status = String(item.status || 'pending').toLowerCase();
        const delivery = parseDeliveryAmount(item.DeliveryFree);
        const totalPrice = (parseFloat(item.discount) || 0) + delivery;

        const img = item.product_image
            ? `<img src="${escapeHtml(item.product_image)}" alt="product">`
            : `<div style="width:48px;height:48px;border-radius:10px;border:1px solid #e2e8f0;background:#f8fafc;display:grid;place-items:center;color:#94a3b8;font-size:11px;">No Img</div>`;

        const address = item.address ? `
            <div class="addr">
                <i class="fa-solid fa-location-dot" style="margin-top:2px;"></i>
                <span>${escapeHtml(item.address)}</span>
            </div>
        ` : `<div class="muted">No address</div>`;

        const extra = renderExtraJson(item.extra_json);

        let actions = `<div class="action-btns">`;
        if (canEdit) {
            if (status === 'pending') {
                actions += `
                    <button class="icon-btn quick-success" onclick="processAction(${item.id}, 'success', this)">
                        <i class="fa-solid fa-check"></i> Success
                    </button>
                    <button class="icon-btn quick-failed" onclick="processAction(${item.id}, 'failed', this)">
                        <i class="fa-solid fa-xmark"></i> Failed
                    </button>`;
            } else if (status === 'failed') {
                actions += `
                    <button class="icon-btn quick-success" onclick="processAction(${item.id}, 'success', this)">
                        <i class="fa-solid fa-check"></i> Success
                    </button>`;
            }
        }
        if (canDelete) {
            actions += `
                <button class="icon-btn delete" onclick="processAction(${item.id}, 'delete', this)">
                    <i class="fa-regular fa-trash-can"></i> Delete
                </button>`;
        }
        actions += `</div>`;

        html += `
            <tr>
                <td>
                    <div class="muted">DB ID</div>
                    <div class="idbox">#${escapeHtml(item.id)}</div>
                    <div style="height:8px"></div>
                    <div class="muted">Order ID</div>
                    <div class="idbox" style="font-family: monospace;">${escapeHtml(item.order_id || '-')}</div>
                </td>
                <td>
                    <div class="user">
                        <div class="name">${escapeHtml(item.username || 'Unknown User')}</div>
                        <div class="chip">UID: ${escapeHtml(item.uid || 'N/A')}</div>
                        ${address}
                    </div>
                </td>
                <td>
                    <div class="prod">
                        ${img}
                        <div style="min-width:0;">
                            <div class="prod-title">${escapeHtml(item.product_title || 'Unknown Product')}</div>
                            <div class="price">৳ ${totalPrice.toFixed(2)}</div>
                        </div>
                    </div>
                    ${extra}
                </td>
                <td>
                    <div class="status-badge ${status}">${escapeHtml(status)}</div>
                    <div class="date"><i class="fa-regular fa-clock"></i> ${escapeHtml(item.created_at || '-')}</div>
                </td>
                <td>${actions}</td>
            </tr>
        `;
    });

    tbody.innerHTML = html;
}

function processAction(id, type, btn) {
    const msg = type === 'delete'
        ? 'Are you sure you want to delete this order permanently?'
        : `Mark this order as ${type.toUpperCase()}?`;

    if (!confirm(msg)) return;
    if (btn) btn.disabled = true;

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

    fetch('?api=process', {
        method: 'POST',
        body: formData
    })
    .then(r => r.json())
    .then(res => {
        if (res.status === 'success') {
            toast(res.message || 'Done', 'success');
            loadData(currentPage);
        } else {
            toast(res.message || 'Error', 'error');
            if (btn) btn.disabled = false;
        }
    })
    .catch(() => {
        toast('Connection error.', 'error');
        if (btn) btn.disabled = false;
    });
}

document.getElementById('prevBtn').addEventListener('click', () => {
    if (currentPage > 1) loadData(currentPage - 1);
});
document.getElementById('nextBtn').addEventListener('click', () => {
    if (currentPage < totalPages) loadData(currentPage + 1);
});

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