<?php
session_start();
header('Content-Type: text/html; charset=utf-8');

// ১. লগিন চেক
if (!isset($_SESSION['admin_logged_in']) || !isset($_SESSION['admin_user']) || !isset($_SESSION['admin_pass'])) {
    header("Location: admin_login.php");
    exit;
}

// ২. ডাটাবেজ কনফিগারেশন লোড
$config_paths = ['Config.php', 'config.php', '../Config.php', '../config.php'];
$config_loaded = false;
foreach ($config_paths as $path) {
    if (file_exists($path)) {
        require_once $path;
        $config_loaded = true;
        break;
    }
}
if (!$config_loaded) die("Config file missing!");
if (!isset($conn) && isset($con)) $conn = $con;

// ৩. লাইভ পারমিশন চেক 
$admin_user = $_SESSION['admin_user'];
$admin_pass = $_SESSION['admin_pass'];
$row = null;

$sql = "SELECT * FROM modarator_permissions WHERE username = ? AND password = ? LIMIT 1";
$stmt = @$conn->prepare($sql);
if ($stmt) {
    $stmt->bind_param("ss", $admin_user, $admin_pass);
    if (@$stmt->execute()) {
        $res = $stmt->get_result();
        if ($res && $res->num_rows > 0) {
            $row = $res->fetch_assoc();
        } else {
            session_unset(); session_destroy();
            header("Location: admin_login.php"); exit;
        }
    }
    $stmt->close();
}

$can_match_editing = strtolower(trim((string)($row['match_editing'] ?? 'no'))) === 'yes';
if (!$can_match_editing) {
    die('<div style="text-align:center; padding:50px; font-family:sans-serif; color:red;"><h2>Access Denied!</h2><p>আপনার এই পেজ ব্যবহারের পারমিশন নেই।</p></div>');
}

// ৪. ক্যাটাগরিভিত্তিক পারমিশন ডিকোড
$extra_json_str = $row['extra_json'] ?? '{}';
$extra_perms = json_decode($extra_json_str, true);
if (!is_array($extra_perms)) $extra_perms = [];

$allowed_categories = [];
$can_add_any = false;

foreach ($extra_perms as $category_name => $perms) {
    $add = (isset($perms['Add']) && $perms['Add'] === 'Yes');
    $edit = (isset($perms['Edit']) && $perms['Edit'] === 'Yes');
    $delete = (isset($perms['Delete']) && $perms['Delete'] === 'Yes');
    
    if ($add || $edit || $delete) {
        $allowed_categories[$category_name] = [
            'Add' => $add ? 'Yes' : 'No',
            'Edit' => $edit ? 'Yes' : 'No',
            'Delete' => $delete ? 'Yes' : 'No'
        ];
    }
    if ($add) $can_add_any = true; 
}
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
    <meta name="theme-color" content="#07070a">
    <title>MatchPro | VIP Premium</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        /* --- VIP Premium Variables --- */
        :root {
            --bg-dark: #07070a;
            --bg-card: rgba(20, 20, 30, 0.4);
            --bg-glass: rgba(25, 25, 35, 0.6);
            --border-glass: rgba(255, 255, 255, 0.08);
            --vip-gold: #FFD700;
            --vip-gold-glow: rgba(255, 215, 0, 0.3);
            --neon-cyan: #00F2FE;
            --neon-pink: #FE0979;
            --danger: #FF3B30;
            --success: #34C759;
            --text-main: #FFFFFF;
            --text-muted: #A0A0B0;
            --radius-md: 16px;
            --radius-lg: 24px;
            --transition: 0.3s cubic-bezier(0.25, 1, 0.5, 1);
        }

        * { margin: 0; padding: 0; box-sizing: border-box; -webkit-tap-highlight-color: transparent; font-family: 'Inter', sans-serif; }
        body { background-color: var(--bg-dark); color: var(--text-main); min-height: 100vh; overflow-x: hidden; position: relative; }

        .ambient-bg {
            position: fixed; inset: 0; z-index: -1; overflow: hidden; pointer-events: none;
            background: radial-gradient(circle at 15% 50%, rgba(0, 242, 254, 0.05), transparent 40%),
                        radial-gradient(circle at 85% 30%, rgba(254, 9, 121, 0.05), transparent 40%);
        }

        ::-webkit-scrollbar { width: 6px; }
        ::-webkit-scrollbar-track { background: var(--bg-dark); }
        ::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.15); border-radius: 10px; }

        .glass-panel { background: var(--bg-glass); backdrop-filter: blur(20px); -webkit-backdrop-filter: blur(20px); border: 1px solid var(--border-glass); }

        .navbar {
            position: sticky; top: 0; z-index: 100; padding: 16px 24px;
            display: flex; justify-content: space-between; align-items: center;
            border-bottom: 1px solid var(--border-glass);
            background: rgba(7, 7, 10, 0.8); backdrop-filter: blur(15px);
        }
        .nav-brand { font-size: 22px; font-weight: 800; display: flex; align-items: center; gap: 8px; text-transform: uppercase; letter-spacing: 1px; }
        .nav-brand span { background: linear-gradient(90deg, var(--vip-gold), #FFF8DC); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }

        .btn-premium {
            background: linear-gradient(135deg, var(--neon-pink), #FF5E3A);
            color: #fff; border: none; padding: 10px 24px; border-radius: 50px;
            font-weight: 700; font-size: 14px; cursor: pointer; display: flex; align-items: center; gap: 8px;
            box-shadow: 0 4px 20px rgba(254, 9, 121, 0.4); transition: var(--transition);
        }
        .btn-premium:hover { transform: translateY(-2px); box-shadow: 0 6px 25px rgba(254, 9, 121, 0.6); }

        .container { max-width: 1400px; margin: 0 auto; padding: 24px; }
        .toolbar { display: flex; gap: 16px; margin-bottom: 30px; padding: 16px; border-radius: var(--radius-md); }
        
        .form-control {
            width: 100%; padding: 12px 16px; background: rgba(255,255,255,0.03); 
            border: 1px solid rgba(255,255,255,0.1); border-radius: 12px; 
            color: #fff; font-size: 14px; transition: var(--transition); outline: none; appearance: none;
        }
        .form-control:focus { border-color: var(--neon-cyan); background: rgba(0, 242, 254, 0.05); box-shadow: 0 0 0 3px rgba(0, 242, 254, 0.15); }
        
        .input-wrap { position: relative; flex: 1; min-width: 250px; }
        .input-wrap svg { position: absolute; left: 16px; top: 50%; transform: translateY(-50%); color: var(--text-muted); width: 16px; }
        .input-wrap input { padding-left: 44px; }
        select.form-control { cursor: pointer; background-image: url('data:image/svg+xml;utf8,<svg fill="%23A0A0B0" height="20" viewBox="0 0 24 24" width="20" xmlns="http://www.w3.org/2000/svg"><path d="M7 10l5 5 5-5z"/></svg>'); background-repeat: no-repeat; background-position: right 12px center; padding-right: 40px; }
        select.form-control option { background: #14141e; color: #fff; }

        .grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(340px, 1fr)); gap: 24px; }
        .card {
            background: var(--bg-card); border-radius: var(--radius-md); border: 1px solid var(--border-glass);
            padding: 20px; display: flex; flex-direction: column; gap: 16px; position: relative; overflow: hidden;
            transition: var(--transition); backdrop-filter: blur(10px);
        }
        @media (hover: hover) { .card:hover { transform: translateY(-5px); border-color: rgba(255, 215, 0, 0.3); box-shadow: 0 10px 30px rgba(0,0,0,0.6), 0 0 20px var(--vip-gold-glow); } }
        
        .card-head { display: flex; justify-content: space-between; align-items: flex-start; gap: 12px; }
        .card-title { font-size: 18px; font-weight: 700; color: #fff; line-height: 1.3; }
        
        .badge { padding: 4px 10px; border-radius: 6px; font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; }
        .badge-lock { background: rgba(255, 59, 48, 0.15); color: var(--danger); border: 1px solid rgba(255, 59, 48, 0.3); }
        .badge-open { background: rgba(52, 199, 89, 0.15); color: var(--success); border: 1px solid rgba(52, 199, 89, 0.3); }
        .badge-completed { background: rgba(0, 242, 254, 0.15); color: var(--neon-cyan); border: 1px solid rgba(0, 242, 254, 0.3); }

        .vip-prize-box { background: linear-gradient(90deg, rgba(255,215,0,0.1), transparent); border-left: 3px solid var(--vip-gold); padding: 12px 16px; border-radius: 4px; display: flex; justify-content: space-between; align-items: center; }
        .prize-text { font-size: 12px; color: var(--text-muted); font-weight: 600; text-transform: uppercase; }
        .prize-amount { font-size: 20px; font-weight: 800; color: var(--vip-gold); text-shadow: 0 0 10px var(--vip-gold-glow); }

        .card-info { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
        .info-row { display: flex; align-items: center; gap: 8px; font-size: 13px; color: var(--text-muted); font-weight: 500; }
        .info-row svg { width: 16px; height: 16px; flex-shrink: 0; color: var(--neon-cyan); }
        .info-full { grid-column: 1 / -1; color: #fff; }

        .card-actions { display: flex; gap: 12px; margin-top: auto; padding-top: 16px; border-top: 1px solid rgba(255,255,255,0.05); }
        .btn-action { flex: 1; padding: 10px; border-radius: 10px; font-size: 13px; font-weight: 600; border: none; cursor: pointer; display: flex; justify-content: center; align-items: center; gap: 6px; transition: 0.2s; }
        .btn-action svg { width: 16px; height: 16px; flex-shrink: 0; }
        .btn-edit { background: rgba(255,255,255,0.05); color: #fff; border: 1px solid rgba(255,255,255,0.1); }
        .btn-edit:hover { background: var(--neon-cyan); color: #000; border-color: var(--neon-cyan); }
        .btn-del { background: rgba(255, 59, 48, 0.1); color: var(--danger); border: 1px solid rgba(255, 59, 48, 0.2); }
        .btn-del:hover { background: var(--danger); color: #fff; }

        .drawer-overlay { position: fixed; inset: 0; background: rgba(0,0,0,0.6); backdrop-filter: blur(5px); z-index: 999; opacity: 0; pointer-events: none; transition: opacity 0.4s ease; }
        .drawer-overlay.active { opacity: 1; pointer-events: all; }
        
        .drawer { position: fixed; top: 0; bottom: 0; right: 0; width: 450px; z-index: 1000; background: rgba(15, 15, 20, 0.95); backdrop-filter: blur(30px); -webkit-backdrop-filter: blur(30px); border-left: 1px solid var(--border-glass); box-shadow: -20px 0 50px rgba(0,0,0,0.8); display: flex; flex-direction: column; transform: translateX(100%); transition: transform 0.4s cubic-bezier(0.16, 1, 0.3, 1); }
        .drawer.active { transform: translateX(0); }
        .drawer-drag-handle { display: none; } 

        .drawer-head { padding: 20px 24px; border-bottom: 1px solid var(--border-glass); display: flex; justify-content: space-between; align-items: center; flex-shrink: 0; }
        .drawer-head h2 { font-size: 18px; font-weight: 700; color: #fff; }
        .btn-close { background: rgba(255,255,255,0.05); border: none; color: var(--text-muted); width: 32px; height: 32px; border-radius: 50%; cursor: pointer; display: flex; align-items: center; justify-content: center; transition: 0.2s; }
        .btn-close:hover { background: rgba(255,255,255,0.1); color: #fff; }

        .drawer-body { flex: 1; overflow-y: auto; padding: 24px; display: flex; flex-direction: column; gap: 16px; -webkit-overflow-scrolling: touch; }
        .form-group { display: flex; flex-direction: column; gap: 6px; }
        .form-group label { font-size: 12px; font-weight: 600; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.5px; }
        .grid-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }

        .drawer-foot { padding: 16px 24px; border-top: 1px solid var(--border-glass); background: rgba(0,0,0,0.3); display: flex; gap: 12px; flex-shrink: 0; padding-bottom: max(16px, env(safe-area-inset-bottom)); }
        .btn-save { flex: 1; background: var(--vip-gold); color: #000; border: none; padding: 14px; border-radius: 12px; font-size: 15px; font-weight: 700; cursor: pointer; box-shadow: 0 4px 15px var(--vip-gold-glow); transition: 0.2s; }
        .btn-save:hover { background: #FFEA00; transform: translateY(-2px); }
        .btn-cancel { flex: 1; background: rgba(255,255,255,0.05); color: #fff; border: none; padding: 14px; border-radius: 12px; font-size: 15px; font-weight: 600; cursor: pointer; transition: 0.2s; }

        .state-box { text-align: center; padding: 60px 20px; grid-column: 1/-1; color: var(--text-muted); }
        .spinner { width: 36px; height: 36px; border: 3px solid rgba(255,255,255,0.1); border-top-color: var(--vip-gold); border-radius: 50%; animation: spin 0.8s linear infinite; margin: 0 auto 16px; }
        @keyframes spin { 100% { transform: rotate(360deg); } }
        
        .pagination { display: flex; justify-content: center; gap: 8px; margin-top: 30px; padding-bottom: 20px; }
        .pagination button { width: 36px; height: 36px; border-radius: 10px; background: rgba(255,255,255,0.05); border: 1px solid var(--border-glass); color: #fff; font-weight: 600; cursor: pointer; transition: 0.2s; }
        .pagination button.active { background: var(--vip-gold); color: #000; border-color: var(--vip-gold); }

        .toast { position: fixed; top: 24px; right: 24px; transform: translateX(150%); background: #1a1a24; border-left: 4px solid var(--success); color: #fff; padding: 16px 20px; border-radius: 12px; font-weight: 600; font-size: 14px; z-index: 9999; box-shadow: 0 10px 30px rgba(0,0,0,0.5); display: flex; align-items: center; gap: 10px; transition: 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275); }
        .toast.show { transform: translateX(0); }
        .toast.error { border-color: var(--danger); }

        @media (max-width: 768px) {
            .navbar { padding: 12px 16px; }
            .nav-brand { font-size: 18px; }
            .container { padding: 16px; }
            .toolbar { flex-direction: column; gap: 12px; padding: 12px; }
            .input-wrap, .btn-premium { width: 100%; justify-content: center; }
            .grid { grid-template-columns: 1fr; }
            
            .drawer { top: auto; bottom: 0; left: 0; right: 0; width: 100%; height: max-content; max-height: 90dvh; border-radius: 24px 24px 0 0; border-left: none; border-top: 1px solid var(--border-glass); transform: translateY(100%); transition: transform 0.4s cubic-bezier(0.2, 0.9, 0.3, 1); }
            .drawer.active { transform: translateY(0); }
            .drawer-drag-handle { display: block; width: 40px; height: 5px; background: rgba(255,255,255,0.2); border-radius: 10px; margin: 12px auto 0; }
            .drawer-head { padding: 12px 20px; border-bottom: none; }
            .drawer-body { padding: 16px 20px; gap: 16px; }
            .toast { top: auto; bottom: 24px; right: 50%; transform: translate(50%, 150%); width: 90%; justify-content: center; }
            .toast.show { transform: translate(50%, 0); }
        }
    </style>
</head>
<body>

<div class="ambient-bg"></div>

<nav class="navbar">
    <div class="nav-brand"><span>Match</span>Pro</div>
    <?php if ($can_add_any): ?>
    <button class="btn-premium" onclick="openDrawer()">
        <svg style="width:18px; height:18px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
        New Match
    </button>
    <?php endif; ?>
</nav>

<div class="container">
    <div class="toolbar glass-panel">
        <div class="input-wrap">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
            <input type="text" class="form-control" id="searchInput" placeholder="Search tournaments..." autocomplete="off">
        </div>
        <div class="input-wrap" style="flex: 0.5;">
            <select id="categoryFilter" class="form-control" onchange="loadMatches(1)">
                <option value="">All Categories</option>
            </select>
        </div>
    </div>

    <div class="grid" id="matchList">
        <div class="state-box"><div class="spinner"></div><p>Loading Matches...</p></div>
    </div>
    
    <div class="pagination" id="pagination"></div>
</div>

<div class="drawer-overlay" id="drawerOverlay" onclick="closeDrawer()"></div>

<div class="drawer" id="sideDrawer">
    <div class="drawer-drag-handle"></div>
    <div class="drawer-head">
        <h2 id="drawerTitle">New Match</h2>
        <button class="btn-close" onclick="closeDrawer()">
            <svg style="width:18px; height:18px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
        </button>
    </div>
    
    <div class="drawer-body">
        <div class="form-group"><label>Match Title *</label><input type="text" class="form-control" id="f_match_title" placeholder="e.g. VIP Scrims"></div>
        
        <div class="grid-2">
            <div class="form-group"><label>Match Time (Display Text)</label><input type="text" class="form-control" id="f_match_time" placeholder="e.g. 10 Feb, 8:00 PM"></div>
            <div class="form-group"><label>Start Time (System/Countdown)</label><input type="datetime-local" class="form-control" id="f_start_time"></div>
        </div>

        <div class="grid-2">
            <div class="form-group">
                <label>Category</label>
                <select class="form-control" id="f_match_type"><option value="" disabled selected>Select Category</option></select>
            </div>
            <div class="form-group">
                <label>Match Status</label>
                <select class="form-control" id="f_status">
                    <option value="Pending">Pending</option>
                    <option value="Ongoing">Ongoing</option>
                    <option value="Completed">Completed</option>
                </select>
            </div>
        </div>

        <div class="grid-2">
            <div class="form-group"><label>Prize Pool (৳)</label><input type="number" class="form-control" id="f_total_prize" placeholder="0"></div>
            <div class="form-group"><label>Per Kill (৳)</label><input type="number" class="form-control" id="f_per_kill" placeholder="0"></div>
        </div>

        <div class="grid-2">
            <div class="form-group"><label>Entry Fee (৳)</label><input type="number" class="form-control" id="f_entry_fee" placeholder="0"></div>
            <div class="form-group"><label>Entry Type</label>
                <select class="form-control" id="f_entry_type"><option value="Solo">Solo</option><option value="Duo">Duo</option><option value="Squad">Squad</option></select>
            </div>
        </div>

        <div class="grid-2">
            <div class="form-group"><label>Map</label>
                <select class="form-control" id="f_play_map"><option value="Bermuda">Bermuda</option><option value="Kalahari">Kalahari</option><option value="Purgatory">Purgatory</option><option value="Alpine">Alpine</option><option value="Erangel">Erangel</option></select>
            </div>
            <div class="form-group"><label>Version</label>
                <select class="form-control" id="f_version"><option value="Mobile">Mobile</option><option value="PC">PC</option><option value="Emulator">Emulator</option></select>
            </div>
        </div>

        <div class="grid-2">
            <div class="form-group"><label>Room ID</label><input type="text" class="form-control" id="f_room_id" placeholder="Hidden"></div>
            <div class="form-group"><label>Password</label><input type="text" class="form-control" id="f_room_pass" placeholder="Hidden"></div>
        </div>

        <div class="form-group"><label>Prize Distribution</label><input type="text" class="form-control" id="f_prize_details" placeholder="1st: 500, 2nd: 300"></div>
        
        <div class="grid-2">
            <div class="form-group"><label>Total Spots</label><input type="number" class="form-control" id="f_total_player" placeholder="48"></div>
            <div class="form-group"><label>Joined</label><input type="number" class="form-control" id="f_total_joiner" placeholder="0"></div>
        </div>

        <div class="grid-2">
            <div class="form-group"><label>Lock Action</label><select class="form-control" id="f_locked"><option value="0">🔓 Open</option><option value="1">🔒 Locked</option></select></div>
            <div class="form-group"><label>Registration</label><select class="form-control" id="f_registration"><option value="Open">Open</option><option value="Closed">Closed</option></select></div>
        </div>

        <div class="form-group"><label>Banner Link (Optional)</label><input type="url" class="form-control" id="f_image_link" placeholder="https://..."></div>
        
        <input type="hidden" id="f_match_result" value="NO"><input type="hidden" id="f_player_name_change" value="0">
        <input type="hidden" id="f_timer" value="0"><input type="hidden" id="f_join_type" value="solo"><input type="hidden" id="f_locked_type" value="admin">
    </div>

    <div class="drawer-foot">
        <button class="btn-cancel" onclick="closeDrawer()">Cancel</button>
        <button class="btn-save" onclick="saveMatch()">Save Match</button>
    </div>
</div>

<div class="toast" id="toast"></div>

<script>
// JS এ PHP থেকে ডাইনামিক ক্রেডেনশিয়াল এবং পারমিশন ইনজেক্ট করা হলো
const API_URL = 'freefire_api.php';
const ADMIN_USER = '<?php echo addslashes($admin_user); ?>';
const ADMIN_PASS = '<?php echo addslashes($admin_pass); ?>';
const CATEGORY_PERMISSIONS = <?php echo json_encode($allowed_categories, JSON_UNESCAPED_UNICODE); ?>;

let allSystemCategories = [];
let editingId = null; let currentPage = 1; const currentShow = 20; let matchData = [];

const svg = {
    clock: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>`,
    map: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polygon points="3 6 9 3 15 6 21 3 21 18 15 21 9 18 3 21"/><line x1="9" y1="3" x2="9" y2="18"/><line x1="15" y1="6" x2="15" y2="21"/></svg>`,
    tag: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M20.59 13.41l-7.17 7.17a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82z"/><line x1="7" y1="7" x2="7.01" y2="7"/></svg>`,
    edit: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>`,
    del: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/><line x1="10" y1="11" x2="10" y2="17"/><line x1="14" y1="11" x2="14" y2="17"/></svg>`
};

const formatDate = (str) => {
    if(!str) return 'N/A';
    try { return new Date(str).toLocaleString('en-US', { day: '2-digit', month: 'short', hour: '2-digit', minute: '2-digit', hour12: true }); } 
    catch(e) { return str; }
};

async function fetchAPI(dataObj) {
    const fd = new URLSearchParams({ admin_username: ADMIN_USER, admin_password: ADMIN_PASS, ...dataObj });
    try { const res = await fetch(API_URL, { method: 'POST', body: fd }); return await res.json(); } 
    catch (e) { return { status: 'error', message: 'Network Error' }; }
}

async function loadCategories() {
    const data = await fetchAPI({ action: 'categories' });
    if (data.status === 'success') {
        allSystemCategories = data.categories || [];
        let opts = '<option value="">All Categories</option>';
        allSystemCategories.forEach(c => { 
            if(CATEGORY_PERMISSIONS[c.title]) {
                opts += `<option value="${c.title}">${c.title}</option>`; 
            }
        });
        document.getElementById('categoryFilter').innerHTML = opts;
    }
}

function populateCategoryDropdown(isEditMode) {
    let formOpts = '<option value="" disabled selected>Select Category</option>';
    allSystemCategories.forEach(c => {
        let catName = c.title;
        if (CATEGORY_PERMISSIONS[catName]) {
            let p = CATEGORY_PERMISSIONS[catName];
            if ((!isEditMode && p.Add === 'Yes') || (isEditMode && p.Edit === 'Yes')) {
                formOpts += `<option value="${catName}">${catName}</option>`;
            }
        }
    });
    document.getElementById('f_match_type').innerHTML = formOpts;
}

async function loadMatches(page = 1) {
    currentPage = page;
    const list = document.getElementById('matchList');
    list.innerHTML = `<div class="state-box"><div class="spinner"></div><p>Syncing Matches...</p></div>`;
    
    const data = await fetchAPI({ action: 'list', page: page, show: currentShow, search: document.getElementById('searchInput').value.trim(), category: document.getElementById('categoryFilter').value });
    if (data.status === 'success') {
        matchData = data.matches || [];
        if (!matchData.length) { list.innerHTML = `<div class="state-box"><p>No matches found.</p></div>`; document.getElementById('pagination').innerHTML=''; return; }
        
        let html = '';
        matchData.forEach(m => {
            // শুধুমাত্র যেসব ক্যাটাগরিতে তার পারমিশন আছে, সেগুলোই দেখাবে
            let catName = m.match_type;
            if(!CATEGORY_PERMISSIONS[catName]) return;
            
            let perms = CATEGORY_PERMISSIONS[catName];
            let canEdit = (perms.Edit === 'Yes');
            let canDelete = (perms.Delete === 'Yes');

            let statusBadge = m.status === 'Completed' ? `<span class="badge badge-completed">Completed</span>` : (m.locked == 1 ? `<span class="badge badge-lock">Locked</span>` : `<span class="badge badge-open">Open</span>`);
            
            let actionBtns = '';
            if(canEdit) actionBtns += `<button class="btn-action btn-edit" onclick="openDrawer(${m.id})">${svg.edit} Edit</button>`;
            if(canDelete) actionBtns += `<button class="btn-action btn-del" onclick="deleteMatch(${m.id})">${svg.del} Delete</button>`;
            if(!canEdit && !canDelete) actionBtns = `<span style="color:var(--text-muted); width:100%; text-align:center; font-size:12px; font-weight:bold;">No Edit/Delete Access</span>`;

            html += `
            <div class="card">
                <div class="card-head">
                    <div class="card-title">${m.match_title || 'Untitled'}</div>
                    ${statusBadge}
                </div>
                <div class="vip-prize-box">
                    <div class="prize-text">Prize Pool</div>
                    <div class="prize-amount">৳${m.total_prize || 0}</div>
                </div>
                <div class="card-info">
                    <div class="info-row info-full" style="color: #fff;">
                        ${svg.clock} Time: ${m.match_time || 'N/A'} <br> 
                        <small style="color:var(--text-muted); margin-left: 24px;">Start: ${formatDate(m.start_time)}</small>
                    </div>
                    <div class="info-row">${svg.map} ${m.play_map || '-'}</div>
                    <div class="info-row">${svg.tag} ${m.entry_type || '-'} (৳${m.entry_fee || 0})</div>
                </div>
                <div class="card-actions">${actionBtns}</div>
            </div>`;
        });
        
        list.innerHTML = html || `<div class="state-box"><p>No allowed matches found.</p></div>`;
        renderPagination(data.total_pages || 1, page);
    }
}

function renderPagination(total, current) {
    const pEl = document.getElementById('pagination'); if (total <= 1) { pEl.innerHTML = ''; return; }
    let html = `<button onclick="loadMatches(${current-1})" ${current<=1?'disabled':''}>&laquo;</button>`;
    let start = Math.max(1, current - 2); let end = Math.min(total, current + 2);
    for (let i = start; i <= end; i++) html += `<button onclick="loadMatches(${i})" class="${i===current ? 'active':''}">${i}</button>`;
    html += `<button onclick="loadMatches(${current+1})" ${current>=total?'disabled':''}>&raquo;</button>`;
    pEl.innerHTML = html;
}

function openDrawer(id = null) {
    editingId = id; document.getElementById('drawerTitle').textContent = id ? 'Edit Match' : 'New Match';
    document.querySelectorAll('.drawer-body input').forEach(el => el.value = '');
    document.getElementById('f_entry_type').value = 'Solo'; document.getElementById('f_play_map').value = 'Bermuda';
    document.getElementById('f_version').value = 'Mobile'; document.getElementById('f_locked').value = '0';
    document.getElementById('f_registration').value = 'Open'; 
    document.getElementById('f_status').value = 'Pending';

    if (id) {
        populateCategoryDropdown(true);
        const m = matchData.find(x => x.id == id);
        if (m) {
            setTimeout(() => {
                ['match_title', 'match_time', 'start_time', 'status', 'total_prize', 'per_kill', 'entry_type', 'entry_fee', 'match_type', 'version', 'play_map', 'registration', 'prize_details', 'room_id', 'room_pass', 'total_player', 'total_joiner', 'locked', 'image_link'].forEach(k => { 
                    let el = document.getElementById('f_' + k);
                    if (el) {
                        if (k === 'start_time' && m[k]) {
                            el.value = m[k].replace(' ', 'T').substring(0, 16);
                        } else {
                            el.value = m[k] || '';
                        }
                    } 
                });
                if(!m.status) document.getElementById('f_status').value = 'Pending';
            }, 50);
        }
    } else {
        populateCategoryDropdown(false);
    }
    
    document.getElementById('sideDrawer').classList.add('active'); document.getElementById('drawerOverlay').classList.add('active'); document.body.style.overflow = 'hidden';
}

function closeDrawer() { document.getElementById('sideDrawer').classList.remove('active'); document.getElementById('drawerOverlay').classList.remove('active'); document.body.style.overflow = ''; }

async function saveMatch() {
    const title = document.getElementById('f_match_title').value.trim(), mType = document.getElementById('f_match_type').value;
    if (!title || !mType) return showToast('Title and Category required!', 'error');
    
    // JS Security Check
    let perms = CATEGORY_PERMISSIONS[mType] || {Add: 'No', Edit: 'No'};
    if (!editingId && perms.Add !== 'Yes') return showToast("এই ক্যাটাগরিতে Add করার পারমিশন নেই!", "error");
    if (editingId && perms.Edit !== 'Yes') return showToast("এই ক্যাটাগরিতে Edit করার পারমিশন নেই!", "error");

    const payload = { action: editingId ? 'update' : 'add' }; if (editingId) payload.id = editingId;
    document.querySelectorAll('.drawer-body input, .drawer-body select').forEach(el => { 
        if(el.id.startsWith('f_')) {
            let val = el.value || (el.type === 'number' ? 0 : '');
            if(el.id === 'f_start_time' && val) val = val.replace('T', ' ');
            payload[el.id.replace('f_', '')] = val; 
        }
    });
    
    const data = await fetchAPI(payload);
    if (data.status === 'success') { showToast('Saved Successfully!', 'success'); closeDrawer(); loadMatches(currentPage); } 
    else showToast(data.message, 'error');
}

async function deleteMatch(id) {
    const m = matchData.find(x => x.id == id);
    if(m) {
        let perms = CATEGORY_PERMISSIONS[m.match_type];
        if(!perms || perms.Delete !== 'Yes') return showToast("এই ম্যাচটি Delete করার পারমিশন নেই!", "error");
    }
    
    if (!confirm('Delete this match?')) return;
    const data = await fetchAPI({ action: 'delete', id: id });
    if (data.status === 'success') { showToast('Deleted!', 'success'); loadMatches(currentPage); } else showToast(data.message, 'error');
}

function showToast(msg, type = 'success') {
    const el = document.getElementById('toast');
    const icon = type === 'success' ? `<svg width="18" height="18" stroke="var(--success)" fill="none" stroke-width="2" viewBox="0 0 24 24"><polyline points="20 6 9 17 4 12"/></svg>` : `<svg width="18" height="18" stroke="var(--danger)" fill="none" stroke-width="2" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>`;
    el.innerHTML = `${icon} <span>${msg}</span>`; el.className = `toast ${type} show`; setTimeout(() => el.classList.remove('show'), 3000);
}

let searchTimeout; document.getElementById('searchInput').addEventListener('input', () => { clearTimeout(searchTimeout); searchTimeout = setTimeout(() => loadMatches(1), 500); });
loadCategories().then(() => loadMatches(1));
</script>
</body>
</html>