<?php
require_once "config.php";

session_start();
date_default_timezone_set("Asia/Dhaka");

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

if (empty($_SESSION['auth_logged_in'])) {
    header("Location: login.php");
    exit;
}

$role = $_SESSION['auth_role'];
$username = $_SESSION['auth_username'];
$is_super = ($role === 'admin');

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

if (!function_exists('getAccessToken')) {
    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;
    }
}

if (!function_exists('sendFCMNotification')) {
    function sendFCMNotification($title, $body, $matchId) {
        $serviceAccountFile = 'noti.json';
        if (file_exists($serviceAccountFile)) {
            $accessToken = getAccessToken($serviceAccountFile);
            if ($accessToken) {
                $credentials = json_decode(file_get_contents($serviceAccountFile), true);
                $projectId = $credentials['project_id'];
                $url = "https://fcm.googleapis.com/v1/projects/" . $projectId . "/messages:send";

                $postData = json_encode([
                    "message" => [
                        "topic" => "match_" . $matchId, 
                        "data" => [
                            "title" => (string)$title,
                            "body"  => (string)$body,
                            "id"    => (string)$matchId
                        ]
                    ]
                ], JSON_UNESCAPED_UNICODE);

                $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);
                $result = curl_exec($ch);
                $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                curl_close($ch);

                return $httpCode == 200;
            }
        }
        return false;
    }
}

$categories = [];
$catRes = $conn->query("SELECT * FROM category ORDER BY id ASC");
if ($catRes) {
    while ($c = $catRes->fetch_assoc()) {
        $img = isset($c['image_link']) ? $c['image_link'] : (isset($c['image']) ? $c['image'] : '');
        $categories[$c['id']] = [
            'title' => $c['title'],
            'img' => $img
        ];
    }
}

$cat_permissions = [];
if ($is_super) {
    foreach ($categories as $id => $data) {
        $cat_permissions[$id] = [
            'title' => $data['title'],
            'img' => $data['img'],
            'add_match' => 'Yes',
            'edit_match' => 'Yes',
            'delete_match' => 'Yes',
            'add_rules' => 'Yes'
        ];
    }
} else {
    $stmt = $conn->prepare("SELECT match_data FROM Zabbar_Admin_Permission WHERE username = ? LIMIT 1");
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $res = $stmt->get_result();
    if ($row = $res->fetch_assoc()) {
        $match_data = json_decode($row['match_data'] ?? '{}', true) ?: [];
        foreach ($match_data as $cid => $perms) {
            if (isset($categories[$cid])) {
                if (($perms['add_match'] ?? 'No') === 'Yes' || ($perms['edit_match'] ?? 'No') === 'Yes' || ($perms['delete_match'] ?? 'No') === 'Yes' || ($perms['add_rules'] ?? 'No') === 'Yes') {
                    $cat_permissions[$cid] = [
                        'title' => $categories[$cid]['title'],
                        'img' => $categories[$cid]['img'],
                        'add_match' => $perms['add_match'] ?? 'No',
                        'edit_match' => $perms['edit_match'] ?? 'No',
                        'delete_match' => $perms['delete_match'] ?? 'No',
                        'add_rules' => $perms['add_rules'] ?? 'No'
                    ];
                }
            }
        }
    }
    $stmt->close();
}

if (empty($cat_permissions)) {
    die("<!DOCTYPE html><html><head><title>Access Denied</title></head><body style='font-family:system-ui;text-align:center;padding:50px;color:#991b1b;background:#fef2f2;'><h2>Access Denied</h2><p>Permission Error.</p></body></html>");
}

$active_cat_id = isset($_GET['cat_id']) && isset($cat_permissions[$_GET['cat_id']]) ? (int)$_GET['cat_id'] : array_key_first($cat_permissions);
$active_cat = $cat_permissions[$active_cat_id];
$active_match_type = $active_cat['title'];
$active_cat_image = $active_cat['img'];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'save_rules' && $active_cat['add_rules'] === 'Yes') {
        $rules_text = trim($_POST['rules_text'] ?? '');
        $chk = $conn->prepare("SELECT id FROM match_rules WHERE match_type = ?");
        $chk->bind_param("s", $active_match_type);
        $chk->execute();
        $chk_res = $chk->get_result();
        
        if ($chk_res->num_rows > 0) {
            $upd = $conn->prepare("UPDATE match_rules SET rules = ? WHERE match_type = ?");
            $upd->bind_param("ss", $rules_text, $active_match_type);
            $upd->execute();
            $upd->close();
        } else {
            $ins = $conn->prepare("INSERT INTO match_rules (match_type, rules) VALUES (?, ?)");
            $ins->bind_param("ss", $active_match_type, $rules_text);
            $ins->execute();
            $ins->close();
        }
        $chk->close();
        $_SESSION['msg'] = "Rules saved successfully!";
        header("Location: ?cat_id=" . $active_cat_id);
        exit;
    }

    if ($_POST['action'] === 'save_template' && $active_cat['add_match'] === 'Yes') {
        $t_title = trim($_POST['t_title'] ?? '');
        $t_entry_fee = trim($_POST['t_entry_fee'] ?? '0');
        $t_win_amt = trim($_POST['t_win_amt'] ?? '0');
        $t_kill_reward = trim($_POST['t_kill_reward'] ?? '0');
        $t_slots = trim($_POST['t_slots'] ?? '0');
        $t_prize_details = trim($_POST['t_prize_details'] ?? '');
        
        $ins = $conn->prepare("INSERT INTO matches (type, title, entry_fee, win_amt, kill_reward, slots, prize_details) VALUES (?, ?, ?, ?, ?, ?, ?)");
        $ins->bind_param("sssssss", $active_match_type, $t_title, $t_entry_fee, $t_win_amt, $t_kill_reward, $t_slots, $t_prize_details);
        $ins->execute();
        $ins->close();
        $_SESSION['msg'] = "Template saved successfully!";
        header("Location: ?cat_id=" . $active_cat_id);
        exit;
    }
}

if (isset($_GET['api']) && $_GET['api'] == 'save_match') {
    header('Content-Type: application/json');
    $action = $_POST['action'] ?? '';
    
    if ($action === 'save_match') {
        $id = (int)($_POST['id'] ?? 0);
        
        $match_title = trim($_POST['match_title'] ?? '');
        $match_time = trim($_POST['match_time'] ?? '');
        $timer = $match_time; 
        
        $total_prize = trim($_POST['total_prize'] ?? ''); if ($total_prize === '') $total_prize = '0';
        $per_kill = trim($_POST['per_kill'] ?? ''); if ($per_kill === '') $per_kill = '0';
        $entry_fee = trim($_POST['entry_fee'] ?? ''); if ($entry_fee === '') $entry_fee = '0';
        $total_player = trim($_POST['total_player'] ?? ''); if ($total_player === '') $total_player = '0';

        $format_input = trim($_POST['format_input'] ?? 'Solo');
        $entry_type = $format_input;
        $join_type = $format_input;
        $locked_type = $format_input;
        $version = trim($_POST['version'] ?? 'Mobile');
        $play_map = trim($_POST['play_map'] ?? 'Bermuda');
        $registration = trim($_POST['registration'] ?? 'Open');
        $prize_details = trim($_POST['prize_details'] ?? '');
        $image_link = trim($_POST['image_link'] ?? '');
        $locked = trim($_POST['locked'] ?? 'true');
        $player_name_change = trim($_POST['player_name_change'] ?? 'true');
        
        $room_id = trim($_POST['room_id'] ?? ''); if ($room_id === '') $room_id = 'No';
        $room_pass = trim($_POST['room_pass'] ?? ''); if ($room_pass === '') $room_pass = 'No';
        $total_joiner = trim($_POST['total_joiner'] ?? ''); if ($total_joiner === '') $total_joiner = '0';
        $match_result = trim($_POST['match_result'] ?? 'No');
        
        $send_noti = trim($_POST['send_notification'] ?? 'No');

        if ($id > 0) {
            if ($active_cat['edit_match'] !== 'Yes') {
                echo json_encode(["status" => "error", "message" => "Edit permission denied."]);
                exit;
            }
            
            $sql = "UPDATE freefire SET 
                    match_title=?, match_time=?, total_prize=?, per_kill=?, entry_fee=?, entry_type=?, version=?, 
                    play_map=?, registration=?, prize_details=?, room_id=?, room_pass=?, total_player=?, total_joiner=?, 
                    match_result=?, timer=?, join_type=?, image_link=?, locked=?, locked_type=?, player_name_change=? 
                    WHERE id=?";
                    
            $stmt = $conn->prepare($sql);
            if (!$stmt) {
                echo json_encode(["status" => "error", "message" => "DB Error: " . $conn->error]); 
                exit;
            }

            $stmt->bind_param("sssssssssssssssssssssi", 
                $match_title, $match_time, $total_prize, $per_kill, $entry_fee, $entry_type, $version, 
                $play_map, $registration, $prize_details, $room_id, $room_pass, $total_player, $total_joiner, 
                $match_result, $timer, $join_type, $image_link, $locked, $locked_type, $player_name_change, 
                $id
            );
            
            if (!$stmt->execute()) {
                echo json_encode(["status" => "error", "message" => "Update Failed: " . $stmt->error]); 
                exit;
            }
            $stmt->close();
            
            $msg = "Match updated successfully!";
            
            if ($send_noti === 'Yes' && $match_result === 'No') {
                if ($room_id !== 'No' && $room_pass !== 'No' && $room_id !== '' && $room_pass !== '') {
                    $noti_title = "Room ID & Password";
                    $noti_body  = "প্রিয় {Player Name}, আপনার জয়েনকৃত ম্যাচ ({$match_title})-এর Room ID & Password দেওয়া হয়েছে।\nRoom ID: {$room_id}\nPassword: {$room_pass}";
                    
                    if (sendFCMNotification($noti_title, $noti_body, $id)) {
                        $msg .= " Notification Sent!";
                    }
                }
            }
            
            echo json_encode(["status" => "success", "message" => $msg, "type" => "edit"]);
            exit;
        } else {
            if ($active_cat['add_match'] !== 'Yes') {
                echo json_encode(["status" => "error", "message" => "Add permission denied."]); 
                exit;
            }
            
            $sql = "INSERT INTO freefire (
                    match_title, match_time, total_prize, per_kill, entry_fee, entry_type, match_type, version, 
                    play_map, registration, prize_details, room_id, room_pass, total_player, total_joiner, 
                    match_result, timer, join_type, image_link, locked, locked_type, player_name_change
                ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
            $stmt = $conn->prepare($sql);
            if (!$stmt) {
                echo json_encode(["status" => "error", "message" => "DB Error: " . $conn->error]); 
                exit;
            }

            $stmt->bind_param("ssssssssssssssssssssss", 
                $match_title, $match_time, $total_prize, $per_kill, $entry_fee, $entry_type, $active_match_type, $version, 
                $play_map, $registration, $prize_details, $room_id, $room_pass, $total_player, $total_joiner, 
                $match_result, $timer, $join_type, $image_link, $locked, $locked_type, $player_name_change
            );
            
            if (!$stmt->execute()) {
                echo json_encode(["status" => "error", "message" => "Insert Failed: " . $stmt->error]); 
                exit;
            }
            $stmt->close();
            
            echo json_encode(["status" => "success", "message" => "Match added successfully!", "type" => "add"]);
            exit;
        }
    }
    exit;
}

if (isset($_GET['api']) && $_GET['api'] == 'delete_template') {
    header('Content-Type: application/json');
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && $active_cat['add_match'] === 'Yes') {
        $id = (int)($_POST['id'] ?? 0);
        if ($id > 0) {
            $stmt = $conn->prepare("DELETE FROM matches WHERE id = ?");
            $stmt->bind_param("i", $id);
            $stmt->execute();
            $stmt->close();
            echo json_encode(["status" => "success"]);
        } else {
            echo json_encode(["status" => "error", "message" => "Invalid template ID."]);
        }
    } else {
        echo json_encode(["status" => "error", "message" => "Permission denied."]);
    }
    exit;
}

if (isset($_GET['api']) && $_GET['api'] == 'delete_match') {
    header('Content-Type: application/json');
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && $active_cat['delete_match'] === 'Yes') {
        $id = (int)($_POST['id'] ?? 0);
        $stmt = $conn->prepare("DELETE FROM freefire WHERE id = ?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $stmt->close();
        echo json_encode(["status" => "success", "message" => "Match deleted successfully!"]);
    } else {
        echo json_encode(["status" => "error", "message" => "Permission denied or invalid request."]);
    }
    exit;
}

if (isset($_GET['api']) && $_GET['api'] == 'delete_all_going') {
    header('Content-Type: application/json');
    if ($active_cat['delete_match'] === 'Yes') {
        $stmt = $conn->prepare("DELETE FROM freefire WHERE match_type = ? AND match_result = 'going'");
        $stmt->bind_param("s", $active_match_type);
        $stmt->execute();
        $stmt->close();
        echo json_encode(["status" => "success", "message" => "All Ongoing matches deleted successfully!"]);
    } else {
        echo json_encode(["status" => "error", "message" => "Permission denied."]);
    }
    exit;
}

if (isset($_GET['api']) && $_GET['api'] == 'delete_all_result') {
    header('Content-Type: application/json');
    if ($active_cat['delete_match'] === 'Yes') {
        $stmt = $conn->prepare("DELETE FROM freefire WHERE match_type = ? AND match_result = 'Yes'");
        $stmt->bind_param("s", $active_match_type);
        $stmt->execute();
        $stmt->close();
        echo json_encode(["status" => "success", "message" => "All Result matches deleted successfully!"]);
    } else {
        echo json_encode(["status" => "error", "message" => "Permission denied."]);
    }
    exit;
}

$filter = isset($_GET['filter']) ? $_GET['filter'] : 'pending';
$match_result_filter = ($filter === 'result') ? 'Yes' : (($filter === 'ongoing') ? 'going' : 'No');

$count_pending = 0;
$count_going = 0;
$count_result = 0;

$stmt_count = $conn->prepare("SELECT COUNT(id) FROM freefire WHERE match_type = ? AND match_result = ?");
$status = 'No';
$stmt_count->bind_param("ss", $active_match_type, $status);
$stmt_count->execute();
$count_pending = $stmt_count->get_result()->fetch_row()[0] ?? 0;

$status = 'going';
$stmt_count->bind_param("ss", $active_match_type, $status);
$stmt_count->execute();
$count_going = $stmt_count->get_result()->fetch_row()[0] ?? 0;

$status = 'Yes';
$stmt_count->bind_param("ss", $active_match_type, $status);
$stmt_count->execute();
$count_result = $stmt_count->get_result()->fetch_row()[0] ?? 0;
$stmt_count->close();

$page = isset($_GET['p']) ? max(1, (int)$_GET['p']) : 1;
$limit = 20;
$offset = ($page - 1) * $limit;
$total_matches = ($filter === 'pending') ? $count_pending : (($filter === 'ongoing') ? $count_going : $count_result);
$total_pages = ceil($total_matches / $limit);

$matches = [];
$stmt = $conn->prepare("SELECT * FROM freefire WHERE match_type = ? AND match_result = ? ORDER BY id ASC LIMIT ? OFFSET ?");
$stmt->bind_param("ssii", $active_match_type, $match_result_filter, $limit, $offset);
$stmt->execute();
$res = $stmt->get_result();
while ($r = $res->fetch_assoc()) {
    $matches[] = $r;
}
$stmt->close();

$current_rules = '';
$stmt = $conn->prepare("SELECT rules FROM match_rules WHERE match_type = ? LIMIT 1");
$stmt->bind_param("s", $active_match_type);
$stmt->execute();
$res = $stmt->get_result();
if ($r = $res->fetch_assoc()) {
    $current_rules = $r['rules'];
}
$stmt->close();

$dynamic_templates = [];
$stmt_tpl = $conn->prepare("SELECT * FROM matches WHERE type = ? ORDER BY id ASC");
if ($stmt_tpl) {
    $stmt_tpl->bind_param("s", $active_match_type);
    $stmt_tpl->execute();
    $res_tpl = $stmt_tpl->get_result();
    while ($r = $res_tpl->fetch_assoc()) {
        $dynamic_templates[] = $r;
    }
    $stmt_tpl->close();
}

function e($str) { return htmlspecialchars((string)$str, ENT_QUOTES, 'UTF-8'); }
include 'header.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Match Management</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        :root {
            --bg: #f1f5f9; --surface: #ffffff; --primary: #4f46e5; --primary-hover: #4338ca;
            --danger: #ef4444; --warning: #f59e0b; --success: #10b981;
            --text-main: #0f172a; --text-muted: #64748b; --border: #e2e8f0;
            --shadow-sm: 0 1px 2px rgba(0,0,0,0.05);
            --shadow-md: 0 4px 6px -1px rgba(0,0,0,0.05), 0 2px 4px -1px rgba(0,0,0,0.03);
            --shadow-lg: 0 10px 15px -3px rgba(0,0,0,0.05), 0 4px 6px -2px rgba(0,0,0,0.03);
            --radius-md: 14px; --radius-lg: 20px;
        }
        * { box-sizing: border-box; margin: 0; padding: 0; font-family: 'Plus Jakarta Sans', sans-serif; }
        body { background: var(--bg); color: var(--text-main); -webkit-font-smoothing: antialiased; }
        
        .topbar { background: var(--surface); padding: 18px 28px; display: flex; justify-content: space-between; align-items: center; box-shadow: var(--shadow-sm); position: sticky; top: 0; z-index: 100; flex-wrap: wrap; gap: 12px; border-bottom: 1px solid rgba(0,0,0,0.05); }
        .brand { font-size: 20px; font-weight: 800; color: var(--primary); display: flex; align-items: center; gap: 10px; letter-spacing: -0.5px; }
        .cat-select { padding: 10px 18px; border-radius: 10px; border: 2px solid var(--border); font-size: 14px; font-weight: 700; cursor: pointer; outline: none; background: #f8fafc; color: var(--text-main); transition: 0.2s; appearance: none; }
        .cat-select:focus, .cat-select:hover { border-color: var(--primary); background: #fff; }
        
        .container { max-width: 1300px; margin: 0 auto; padding: 32px 24px; }
        
        .view-section { display: none; animation: fadeIn 0.3s ease; }
        .view-section.active { display: block; }
        @keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }

        .btn { padding: 12px 20px; border: none; border-radius: 12px; font-weight: 700; cursor: pointer; transition: all 0.2s; display: inline-flex; align-items: center; justify-content: center; gap: 8px; font-size: 14px; text-decoration: none; }
        .btn-primary { background: linear-gradient(135deg, var(--primary), #6366f1); color: #fff; box-shadow: 0 4px 12px rgba(79, 70, 229, 0.25); }
        .btn-primary:hover { transform: translateY(-2px); box-shadow: 0 6px 16px rgba(79, 70, 229, 0.35); }
        .btn-danger { background: #fee2e2; color: #b91c1c; }
        .btn-danger:hover { background: #fca5a5; }
        .btn-warning { background: #fef3c7; color: #b45309; }
        .btn-warning:hover { background: #fde68a; }
        .btn-outline { background: #fff; border: 2px solid var(--border); color: var(--text-main); }
        .btn-outline:hover { border-color: var(--primary); color: var(--primary); }
        
        .header-actions { display: flex; justify-content: space-between; align-items: center; margin-bottom: 28px; flex-wrap: wrap; gap: 16px; }
        .view-title { font-size: 24px; font-weight: 800; color: var(--text-main); letter-spacing: -0.5px; }
        
        .alert { padding: 16px 20px; border-radius: 14px; margin-bottom: 28px; font-weight: 600; background: #ecfdf5; color: #065f46; border: 1px solid #a7f3d0; display: flex; align-items: center; gap: 12px; font-size: 15px; box-shadow: var(--shadow-sm); }
        .alert.error { background: #fef2f2; color: #991b1b; border-color: #fca5a5; }
        
        .quick-templates { display: flex; gap: 12px; margin-bottom: 28px; overflow-x: auto; padding-bottom: 8px; -webkit-overflow-scrolling: touch; }
        .quick-templates::-webkit-scrollbar { height: 6px; }
        .quick-templates::-webkit-scrollbar-track { background: transparent; }
        .quick-templates::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 10px; }
        .quick-templates::-webkit-scrollbar-thumb:hover { background: #94a3b8; }

        .template-btn { background: #e0e7ff; color: var(--primary); padding: 10px 20px; border-radius: 30px; font-size: 14px; font-weight: 700; border: none; cursor: pointer; white-space: nowrap; transition: 0.2s; box-shadow: var(--shadow-sm); flex-shrink: 0; }
        .template-btn:hover { background: var(--primary); color: #fff; transform: translateY(-1px); }

        .form-card { background: var(--surface); padding: 40px; border-radius: var(--radius-lg); box-shadow: var(--shadow-lg); border: 1px solid rgba(0,0,0,0.03); }
        .grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 24px; }
        .field { display: flex; flex-direction: column; gap: 8px; }
        .field.full { grid-column: 1 / -1; }
        .field label { font-size: 14px; font-weight: 700; color: var(--text-main); display: flex; align-items: center; gap: 6px; }
        .field input, .field select, .field textarea { padding: 14px 16px; border-radius: 12px; border: 2px solid var(--border); font-size: 15px; background: #f8fafc; transition: all 0.2s; color: var(--text-main); outline: none; width: 100%; font-weight: 500; }
        .field input:focus, .field select:focus, .field textarea:focus { background: #fff; border-color: var(--primary); box-shadow: 0 0 0 4px rgba(79, 70, 229, 0.1); }
        
        .match-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 24px; }
        .match-card { background: var(--surface); border-radius: var(--radius-lg); overflow: hidden; box-shadow: var(--shadow-md); transition: 0.3s; display: flex; flex-direction: column; border: 1px solid rgba(0,0,0,0.04); }
        .match-card:hover { transform: translateY(-6px); box-shadow: var(--shadow-lg); border-color: rgba(79, 70, 229, 0.2); }
        .mc-img { width: 100%; height: 160px; object-fit: cover; background: #e2e8f0; position: relative; }
        .mc-status { position: absolute; top: 16px; right: 16px; padding: 6px 12px; border-radius: 8px; font-size: 12px; font-weight: 800; text-transform: uppercase; letter-spacing: 0.5px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
        .mc-status.open { background: var(--success); color: #fff; }
        .mc-status.closed { background: var(--danger); color: #fff; }
        .mc-id { position: absolute; top: 16px; left: 16px; padding: 6px 10px; border-radius: 8px; font-size: 13px; font-weight: 800; background: rgba(15, 23, 42, 0.8); color: #fff; backdrop-filter: blur(4px); }
        .mc-body { padding: 20px; flex: 1; display: flex; flex-direction: column; }
        .mc-title { font-size: 18px; font-weight: 800; margin-bottom: 16px; line-height: 1.4; color: var(--text-main); display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
        .mc-info { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-bottom: 20px; font-size: 14px; }
        .mc-info-item { display: flex; align-items: center; gap: 8px; color: var(--text-muted); font-weight: 600; }
        .mc-info-item i { color: var(--primary); width: 16px; text-align: center; }
        .mc-price { font-size: 16px; font-weight: 800; color: var(--success); margin-top: auto; display: flex; align-items: center; justify-content: space-between; padding-top: 16px; border-top: 2px dashed var(--border); }
        .mc-price-fee { color: var(--text-main); display: flex; align-items: center; gap: 6px; }
        
        .mc-actions { display: flex; gap: 10px; margin-top: 20px; flex-wrap: wrap; }
        .mc-actions button, .mc-actions a.btn { flex: 1; padding: 10px; font-size: 14px; justify-content: center; text-align: center; border-radius: 10px; }

        .pagination { display: flex; justify-content: center; align-items: center; gap: 8px; margin-top: 40px; flex-wrap: wrap; }
        .page-link { padding: 10px 16px; border-radius: 10px; background: var(--surface); border: 2px solid var(--border); color: var(--text-muted); font-weight: 700; font-size: 14px; text-decoration: none; transition: 0.2s; }
        .page-link:hover { background: #f8fafc; border-color: var(--primary); color: var(--primary); }
        .page-link.active { background: var(--primary); color: #fff; border-color: var(--primary); }
        .page-ellipsis { padding: 10px; color: var(--text-muted); font-weight: 700; }

        .hidden { display: none !important; }

        .time-picker-wrapper { position: relative; display: flex; align-items: center; }
        .time-picker-btn { position: absolute; right: 8px; background: #e2e8f0; color: var(--text-main); border: none; border-radius: 8px; padding: 8px 12px; cursor: pointer; transition: 0.2s; }
        .time-picker-btn:hover { background: #cbd5e1; }
        .time-picker-native { position: absolute; right: 8px; width: 45px; height: 100%; opacity: 0; cursor: pointer; }
        
        .notification-box { background: #f0fdf4; border: 2px solid #bbf7d0; padding: 20px; border-radius: 14px; margin-top: 24px; }
        .notification-box span { color: #166534; }
        .notification-box label { color: #166534; }

        .filter-buttons { display: flex; gap: 12px; }
        .filter-buttons .btn { max-width: 180px; }

        @media (max-width: 768px) {
            .grid { grid-template-columns: 1fr; }
            .topbar { padding: 14px 20px; }
            .container { padding: 20px; }
            .form-card { padding: 24px; }
            .header-actions { flex-direction: column; align-items: stretch; }
            .header-actions > div { display: flex; flex-direction: column; gap: 12px; }
            .mc-actions { flex-direction: column; }
            .btn { width: 100%; }
            .filter-buttons { flex-direction: column; width: 100%; }
            .filter-buttons .btn { max-width: 100%; }
            .bulk-actions { flex-direction: column; width: 100%; }
        }
    </style>
</head>
<body>

<div class="topbar">
    <div class="brand"><i class="fa-solid fa-gamepad"></i> MatchHub Admin</div>
    <select class="cat-select" onchange="window.location.href='?cat_id='+this.value">
        <?php foreach ($cat_permissions as $id => $cat): ?>
            <option value="<?= $id ?>" <?= $id === $active_cat_id ? 'selected' : '' ?>>
                <?= e($cat['title']) ?>
            </option>
        <?php endforeach; ?>
    </select>
</div>

<div class="container">
    <?php if(isset($_SESSION['msg'])): ?>
        <script>alert("<?= e($_SESSION['msg']) ?>");</script>
        <?php unset($_SESSION['msg']); ?>
    <?php endif; ?>
    
    <div id="messageBox"></div>

    <div class="header-actions" id="mainHeader">
        <div class="view-title" id="pageTitle">Active Matches</div>
        <div style="display:flex; gap:12px; flex-direction: row;">
            <?php if ($active_cat['add_rules'] === 'Yes'): ?>
                <button class="btn btn-outline" onclick="toggleView('rulesView', 'Match Rules')"><i class="fa-solid fa-scroll"></i> Rules</button>
            <?php endif; ?>
            <?php if ($active_cat['add_match'] === 'Yes'): ?>
                <button class="btn btn-primary" onclick="openCreateForm()"><i class="fa-solid fa-plus"></i> Create Match</button>
            <?php endif; ?>
        </div>
    </div>

    <div id="listView" class="view-section active">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px; flex-wrap: wrap; gap: 16px;">
            <div class="filter-buttons">
                <a href="?cat_id=<?= $active_cat_id ?>&filter=pending" class="btn <?= $filter === 'pending' ? 'btn-primary' : 'btn-outline' ?>">
                    <i class="fa-solid fa-gamepad"></i> Match (<?= $count_pending ?>)
                </a>
                <a href="?cat_id=<?= $active_cat_id ?>&filter=ongoing" class="btn <?= $filter === 'ongoing' ? 'btn-primary' : 'btn-outline' ?>">
                    <i class="fa-solid fa-play"></i> Ongoing (<?= $count_going ?>)
                </a>
                <a href="?cat_id=<?= $active_cat_id ?>&filter=result" class="btn <?= $filter === 'result' ? 'btn-primary' : 'btn-outline' ?>">
                    <i class="fa-solid fa-trophy"></i> Results (<?= $count_result ?>)
                </a>
            </div>
            
            <?php if ($active_cat['delete_match'] === 'Yes'): ?>
            <div class="bulk-actions" style="display: flex; gap: 10px;">
                <button class="btn btn-danger" onclick="deleteAll('going')"><i class="fa-solid fa-trash-can"></i> Delete All Going</button>
                <button class="btn btn-danger" onclick="deleteAll('result')"><i class="fa-solid fa-trash-can"></i> Delete All Results</button>
            </div>
            <?php endif; ?>
        </div>

        <?php if(count($matches) > 0): ?>
            <div class="match-grid">
                <?php foreach($matches as $m): 
                    $regStatus = strtolower($m['registration']);
                    $isOpen = ($regStatus !== 'close');
                ?>
                <div class="match-card">
                    <div style="position: relative;">
                        <div class="mc-id">#<?= $m['id'] ?></div>
                        <img src="<?= e($m['image_link']) ?>" class="mc-img" alt="Banner" onerror="this.src='https://placehold.co/600x300/e2e8f0/64748b?text=No+Image'">
                        <div class="mc-status <?= $isOpen ? 'open' : 'closed' ?>"><?= $isOpen ? 'Open' : 'Closed' ?></div>
                    </div>
                    <div class="mc-body">
                        <div class="mc-title"><?= e($m['match_title']) ?></div>
                        <div class="mc-info">
                            <div class="mc-info-item"><i class="fa-solid fa-clock"></i> <?= e($m['match_time']) ?></div>
                            <div class="mc-info-item"><i class="fa-solid fa-users"></i> <?= e($m['entry_type']) ?></div>
                            <div class="mc-info-item"><i class="fa-solid fa-map-location-dot"></i> <?= e($m['play_map']) ?></div>
                            <div class="mc-info-item"><i class="fa-solid fa-mobile-screen"></i> <?= e($m['version']) ?></div>
                            <div class="mc-info-item" style="grid-column: 1 / -1;"><i class="fa-solid fa-user-plus"></i> Joined: <?= e($m['total_joiner']) ?> / <?= e($m['total_player']) ?></div>
                        </div>
                        <div class="mc-price">
                            <div class="mc-price-fee"><i class="fa-solid fa-coins" style="color:#f59e0b;"></i> <?= e($m['entry_fee']) ?> TK</div>
                            <div><i class="fa-solid fa-trophy" style="color:#f59e0b;"></i> <?= e($m['total_prize']) ?></div>
                        </div>
                        
                        <div class="mc-actions">
                            <a href="refund.php?match_id=<?= $m['id'] ?>&match_type=<?= urlencode($m['match_type']) ?>" class="btn" style="background:var(--success); color:#fff;"><i class="fa-solid fa-money-bill-transfer"></i> Refund</a>
                            
                            <?php if ($active_cat['edit_match'] === 'Yes'): ?>
                                <button class="btn btn-warning" onclick='editMatch(<?= json_encode($m, JSON_HEX_APOS | JSON_HEX_QUOT) ?>)'><i class="fa-solid fa-pen"></i> Edit</button>
                            <?php endif; ?>
                            
                            <?php if ($active_cat['delete_match'] === 'Yes'): ?>
                                <button class="btn btn-danger" onclick="deleteMatch(<?= $m['id'] ?>)"><i class="fa-solid fa-trash"></i> Delete</button>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>

            <?php if ($total_pages > 1): ?>
            <div class="pagination">
                <?php
                $pages = [];
                if ($total_pages <= 7) {
                    for ($i = 1; $i <= $total_pages; $i++) { $pages[] = $i; }
                } else {
                    if ($page <= 4) {
                        $pages = [1, 2, 3, 4, 5, '...', $total_pages];
                    } elseif ($page >= $total_pages - 3) {
                        $pages = [1, '...', $total_pages - 4, $total_pages - 3, $total_pages - 2, $total_pages - 1, $total_pages];
                    } else {
                        $pages = [1, '...', $page - 1, $page, $page + 1, '...', $total_pages];
                    }
                }
                foreach ($pages as $p):
                    if ($p === '...'): ?>
                        <span class="page-ellipsis">...</span>
                    <?php else: ?>
                        <a href="?cat_id=<?= $active_cat_id ?>&filter=<?= $filter ?>&p=<?= $p ?>" class="page-link <?= $p === $page ? 'active' : '' ?>"><?= $p ?></a>
                    <?php endif;
                endforeach;
                ?>
            </div>
            <?php endif; ?>

        <?php else: ?>
            <div style="text-align:center; padding:80px 20px; background:var(--surface); border-radius:var(--radius-lg); color:var(--text-muted); border:1px solid var(--border);">
                <i class="fa-solid fa-folder-open fa-4x" style="margin-bottom:20px; color:var(--border);"></i>
                <h3 style="font-size: 22px; font-weight:800; color:var(--text-main); margin-bottom:10px;">No Matches Found</h3>
                <p style="font-size:15px;">There are no matches available in this filter.</p>
            </div>
        <?php endif; ?>
    </div>

    <div id="formView" class="view-section">
        <div class="form-card">
            <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:30px;">
                <h3 id="formTitleText" style="font-size:22px; font-weight:800; color:var(--text-main);"><i class="fa-solid fa-plus"></i> Create Match</h3>
                <button class="btn btn-outline" onclick="closeForm()" style="padding:10px 16px;"><i class="fa-solid fa-arrow-left"></i> Back to Matches</button>
            </div>

            <div class="quick-templates" id="quickTemplates">
                <button class="template-btn" type="button" onclick="openTemplateModal()" style="background:var(--primary); color:#fff;"><i class="fa-solid fa-plus"></i> Add Template</button>
                <?php foreach ($dynamic_templates as $tpl): ?>
                    <div style="display: flex; flex-shrink: 0; align-items: stretch; background: #e0e7ff; border-radius: 30px; overflow: hidden; box-shadow: var(--shadow-sm);">
                        <button type="button" style="background: transparent; color: var(--primary); padding: 10px 15px; font-size: 14px; font-weight: 700; border: none; cursor: pointer; white-space: nowrap; transition: 0.2s; outline: none;" onmouseover="this.style.background='var(--primary)'; this.style.color='#fff'" onmouseout="this.style.background='transparent'; this.style.color='var(--primary)'" onclick='applyDynamicTemplate(<?= json_encode($tpl['title']) ?>, <?= json_encode($tpl['win_amt']) ?>, <?= json_encode($tpl['kill_reward']) ?>, <?= json_encode($tpl['entry_fee']) ?>, <?= json_encode($tpl['slots']) ?>, <?= json_encode($tpl['prize_details']) ?>)'>
                            <?= e($tpl['title']) ?>
                        </button>
                        <button type="button" onclick="deleteTemplate(<?= $tpl['id'] ?>)" style="background: #fee2e2; color: #b91c1c; border: none; padding: 0 15px; cursor: pointer; transition: 0.2s; outline: none;" onmouseover="this.style.background='#fca5a5'" onmouseout="this.style.background='#fee2e2'" title="Delete Template">
                            <i class="fa-solid fa-trash-can"></i>
                        </button>
                    </div>
                <?php endforeach; ?>
            </div>

            <form id="matchForm">
                <input type="hidden" name="action" value="save_match">
                <input type="hidden" name="id" id="f_id" value="0">
                
                <div class="grid">
                    <div class="field full">
                        <label>Match Title</label>
                        <input type="text" name="match_title" id="f_title" placeholder="🌟 SPECIAL MATCH..." required>
                    </div>
                    
                    <div class="field full">
                        <label>Match Time</label>
                        <div class="time-picker-wrapper">
                            <input type="text" name="match_time" id="f_time" placeholder="Time: 05/06/2026 At 10:00 PM" required>
                            <button type="button" class="time-picker-btn"><i class="fa-solid fa-clock"></i></button>
                            <input type="datetime-local" class="time-picker-native" onchange="updateTimeText(this)">
                        </div>
                    </div>

                    <div class="field"><label>Entry Fee (TK)</label><input type="number" name="entry_fee" id="f_fee" required></div>
                    <div class="field"><label>Per Kill (TK)</label><input type="number" name="per_kill" id="f_kill" required></div>
                    <div class="field"><label>Total Prize (TK)</label><input type="number" name="total_prize" id="f_prize" required></div>
                    <div class="field"><label>Total Players</label><input type="number" name="total_player" id="f_tplayer" required></div>
                    
                    <div class="field">
                        <label>Match Format</label>
                        <select name="format_input" id="f_format">
                            <option value="Solo">Solo</option>
                            <option value="Duo">Duo</option>
                            <option value="Squad">Squad</option>
                        </select>
                    </div>
                    
                    <div class="field">
                        <label>Device Version</label>
                        <select name="version" id="f_version">
                            <option value="Mobile">Mobile</option>
                            <option value="PC">PC</option>
                            <option value="TTP">TTP</option>
                            <option value="TTF">TTF</option>
                        </select>
                    </div>
                    
                    <div class="field">
                        <label>Play Map</label>
                        <input type="hidden" name="play_map" id="f_map_final" value="Bermuda">
                        <select id="f_map_select" onchange="handleMapChange()">
                            <option value="Bermuda">Bermuda</option>
                            <option value="Purgatory">Purgatory</option>
                            <option value="Kalahari">Kalahari</option>
                            <option value="Alpine">Alpine</option>
                            <option value="Nexterra">Nexterra</option>
                            <option value="Bermuda Remastered">Bermuda Remastered</option>
                            <option value="Custom">Custom...</option>
                        </select>
                        <input type="text" id="f_map_custom" oninput="handleMapChange()" style="display:none; margin-top:10px;" placeholder="Enter custom map name">
                    </div>
                    
                    <div class="field">
                        <label>Registration Status</label>
                        <select name="registration" id="f_reg">
                            <option value="Open">Open</option>
                            <option value="Close">Closed</option>
                        </select>
                    </div>
                    
                    <div class="field full">
                        <label>Banner Image URL</label>
                        <input type="url" name="image_link" id="f_img" placeholder="https://..." required>
                    </div>

                    <div class="field">
                        <label>Lock Match?</label>
                        <select name="locked" id="f_lock">
                            <option value="true">Yes</option>
                            <option value="false">No</option>
                        </select>
                    </div>

                    <div class="field">
                        <label>Allow Name Change?</label>
                        <select name="player_name_change" id="f_pnc">
                            <option value="true">Yes</option>
                            <option value="false">No</option>
                        </select>
                    </div>
                    
                    <div class="field full">
                        <label>Prize Details</label>
                        <textarea name="prize_details" id="f_pdet" rows="5" placeholder="🏆 Winner List..."></textarea>
                    </div>

                    <div class="field"><label>Room ID</label><input type="text" name="room_id" id="f_rid" placeholder="Leave empty for 'No'"></div>
                    <div class="field"><label>Room Password</label><input type="text" name="room_pass" id="f_rpass" placeholder="Leave empty for 'No'"></div>
                    <div class="field"><label>Joined Players</label><input type="number" name="total_joiner" id="f_tjoiner" value="0"></div>
                    
                    <div class="field">
                        <label>Match Status?</label>
                        <select name="match_result" id="f_mres">
                            <option value="No">Match (Pending)</option>
                            <option value="going">Ongoing</option>
                            <option value="Yes">Result Published</option>
                        </select>
                    </div>
                </div>

                <div class="field full notification-box" id="f_noti_box" style="display: none;">
                    <label style="display:flex; justify-content:space-between; align-items:center; width:100%;">
                        <span style="font-size:16px;"><i class="fa-solid fa-bell"></i> Send Room ID Notification</span>
                        <label style="display:flex; align-items:center; gap:8px; cursor:pointer; font-weight:700;">
                            <input type="checkbox" name="send_notification" value="Yes" checked style="width:20px; height:20px;"> Yes, Send
                        </label>
                    </label>
                </div>
                
                <div class="field full" style="margin-top:30px;">
                    <button type="submit" class="btn btn-primary" id="submitBtn" style="width:100%; padding:16px; font-size:16px; font-weight:800;"><i class="fa-solid fa-floppy-disk"></i> Save Match Details</button>
                </div>
            </form>
        </div>
    </div>

    <?php if ($active_cat['add_rules'] === 'Yes'): ?>
    <div id="rulesView" class="view-section">
        <div class="form-card">
            <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:30px;">
                <h3 style="font-size:22px; font-weight:800; color:var(--text-main);"><i class="fa-solid fa-scroll"></i> Match Rules</h3>
                <button class="btn btn-outline" onclick="toggleView('listView', 'Active Matches')" style="padding:10px 16px;"><i class="fa-solid fa-arrow-left"></i> Back</button>
            </div>
            <form method="post" action="?cat_id=<?= $active_cat_id ?>">
                <input type="hidden" name="action" value="save_rules">
                <div class="field full" style="margin-bottom:30px;">
                    <textarea name="rules_text" rows="14" placeholder="Enter detailed match rules here..."><?= e($current_rules) ?></textarea>
                </div>
                <button type="submit" class="btn btn-primary" style="width:100%; padding:16px; font-size:16px; font-weight:800;"><i class="fa-solid fa-floppy-disk"></i> Save Rules</button>
            </form>
        </div>
    </div>
    <?php endif; ?>

</div>

<div id="templateModal" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.5); z-index:1000; align-items:center; justify-content:center;">
    <div class="form-card" style="width:90%; max-width:600px; max-height:90vh; overflow-y:auto; position:relative;">
        <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:20px;">
            <h3 style="font-size:20px; font-weight:800;"><i class="fa-solid fa-plus"></i> Save New Match Template</h3>
            <button type="button" class="btn btn-outline" onclick="closeTemplateModal()" style="padding:6px 12px;"><i class="fa-solid fa-xmark"></i></button>
        </div>
        <form method="post" action="?cat_id=<?= $active_cat_id ?>">
            <input type="hidden" name="action" value="save_template">
            <div class="grid">
                <div class="field full"><label>Template Title</label><input type="text" name="t_title" required placeholder="e.g., 20TK Special"></div>
                <div class="field"><label>Entry Fee (TK)</label><input type="number" name="t_entry_fee" required></div>
                <div class="field"><label>Total Prize / Win Amt (TK)</label><input type="number" name="t_win_amt" required></div>
                <div class="field"><label>Per Kill Reward (TK)</label><input type="number" name="t_kill_reward" required></div>
                <div class="field"><label>Total Slots (Players)</label><input type="number" name="t_slots" required></div>
                <div class="field full"><label>Prize Details</label><textarea name="t_prize_details" rows="4" required placeholder="Enter prize distribution details..."></textarea></div>
                <div class="field full" style="margin-top:10px;">
                    <button type="submit" class="btn btn-primary" style="width:100%; padding:14px;"><i class="fa-solid fa-floppy-disk"></i> Save Template</button>
                </div>
            </div>
        </form>
    </div>
</div>

<script>
function toggleView(viewId, title) {
    document.querySelectorAll('.view-section').forEach(el => el.classList.remove('active'));
    document.getElementById(viewId).classList.add('active');
    document.getElementById('pageTitle').innerText = title;
    if(viewId === 'listView') {
        document.getElementById('mainHeader').classList.remove('hidden');
    } else {
        document.getElementById('mainHeader').classList.add('hidden');
    }
}

function openCreateForm() {
    document.getElementById('formTitleText').innerHTML = '<i class="fa-solid fa-plus"></i> Create Match';
    document.getElementById('f_id').value = '0';
    document.getElementById('quickTemplates').classList.remove('hidden');
    
    document.querySelectorAll('#formView input[type="text"], #formView input[type="number"], #formView input[type="url"], #formView textarea').forEach(el => {
        el.value = '';
    });
    
    document.getElementById('f_img').value = '<?= e($active_cat_image) ?>';
    document.getElementById('f_map_select').value = 'Bermuda';
    handleMapChange();
    document.getElementById('f_lock').value = 'true';
    document.getElementById('f_pnc').value = 'true';
    document.getElementById('f_mres').value = 'No';
    document.getElementById('f_tjoiner').value = '0';
    
    document.getElementById('f_noti_box').style.display = 'none';
    
    toggleView('formView', 'Create Match');
}

function closeForm() {
    window.location.reload();
}

function editMatch(data) {
    document.getElementById('formTitleText').innerHTML = '<i class="fa-solid fa-pen"></i> Edit Match';
    document.getElementById('f_id').value = data.id;
    document.getElementById('quickTemplates').classList.add('hidden');
    
    document.getElementById('f_title').value = data.match_title || '';
    document.getElementById('f_time').value = data.match_time || '';
    document.getElementById('f_prize').value = data.total_prize || '0';
    document.getElementById('f_kill').value = data.per_kill || '0';
    document.getElementById('f_fee').value = data.entry_fee || '0';
    document.getElementById('f_format').value = data.entry_type || 'Solo';
    document.getElementById('f_version').value = data.version || 'Mobile';
    
    const standardMaps = ['Bermuda', 'Purgatory', 'Kalahari', 'Alpine', 'Nexterra', 'Bermuda Remastered'];
    const mapVal = data.play_map || 'Bermuda';
    if(standardMaps.includes(mapVal)) {
        document.getElementById('f_map_select').value = mapVal;
        document.getElementById('f_map_custom').value = '';
    } else {
        document.getElementById('f_map_select').value = 'Custom';
        document.getElementById('f_map_custom').value = mapVal;
    }
    handleMapChange();
    
    document.getElementById('f_reg').value = data.registration || 'Open';
    document.getElementById('f_tplayer').value = data.total_player || '0';
    document.getElementById('f_img').value = data.image_link || '';
    document.getElementById('f_lock').value = data.locked || 'true';
    document.getElementById('f_pnc').value = data.player_name_change || 'true';
    document.getElementById('f_pdet').value = data.prize_details || '';
    
    document.getElementById('f_rid').value = (data.room_id && data.room_id !== 'No') ? data.room_id : '';
    document.getElementById('f_rpass').value = (data.room_pass && data.room_pass !== 'No') ? data.room_pass : '';
    document.getElementById('f_tjoiner').value = data.total_joiner || '0';
    document.getElementById('f_mres').value = data.match_result || 'No';
    
    document.getElementById('f_noti_box').style.display = 'block';
    
    toggleView('formView', 'Edit Match');
}

function applyDynamicTemplate(title, prize, kill, fee, slots, pdet) {
    document.getElementById('f_title').value = title || '';
    document.getElementById('f_prize').value = prize || '0';
    document.getElementById('f_kill').value = kill || '0';
    document.getElementById('f_fee').value = fee || '0';
    document.getElementById('f_tplayer').value = slots || '0';
    document.getElementById('f_pdet').value = pdet || '';
}

function deleteTemplate(id) {
    if(!confirm('Delete this template?')) return;
    const formData = new FormData();
    formData.append('id', id);
    fetch('?api=delete_template&cat_id=<?= $active_cat_id ?>', {
        method: 'POST',
        body: formData
    })
    .then(res => res.json())
    .then(data => {
        if(data.status === 'success') {
            window.location.reload();
        } else {
            alert(data.message || 'Failed to delete template');
        }
    })
    .catch(err => alert('Network error.'));
}

function openTemplateModal() {
    document.getElementById('templateModal').style.display = 'flex';
}

function closeTemplateModal() {
    document.getElementById('templateModal').style.display = 'none';
}

function updateTimeText(el) {
    if(!el.value) return;
    const d = new Date(el.value);
    const day = String(d.getDate()).padStart(2, '0');
    const month = String(d.getMonth() + 1).padStart(2, '0');
    const year = d.getFullYear();
    let hours = d.getHours();
    const minutes = String(d.getMinutes()).padStart(2, '0');
    const ampm = hours >= 12 ? 'PM' : 'AM';
    hours = hours % 12;
    hours = hours ? hours : 12; 
    const strTime = "Time: " + day + "/" + month + "/" + year + " At " + String(hours).padStart(2, '0') + ":" + minutes + " " + ampm;
    document.getElementById('f_time').value = strTime;
}

function handleMapChange() {
    const sel = document.getElementById('f_map_select').value;
    const customInput = document.getElementById('f_map_custom');
    const finalInput = document.getElementById('f_map_final');
    if(sel === 'Custom') {
        customInput.style.display = 'block';
        finalInput.value = customInput.value;
    } else {
        customInput.style.display = 'none';
        finalInput.value = sel;
    }
}

document.getElementById('matchForm').addEventListener('submit', function(e) {
    e.preventDefault();
    const formData = new FormData(this);
    const submitBtn = document.getElementById('submitBtn');
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Saving...';
    
    fetch('?api=save_match&cat_id=<?= $active_cat_id ?>', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        const msgBox = document.getElementById('messageBox');
        if(data.status === 'success') {
            msgBox.innerHTML = '<div class="alert"><i class="fa-solid fa-check-circle"></i> ' + data.message + '</div>';
            window.scrollTo({ top: 0, behavior: 'smooth' });
            
            if (data.type === 'edit') {
                setTimeout(() => { window.location.reload(); }, 1200);
            } else {
                document.getElementById('f_id').value = '0';
            }
        } else {
            msgBox.innerHTML = '<div class="alert error"><i class="fa-solid fa-circle-exclamation"></i> ' + data.message + '</div>';
            window.scrollTo({ top: 0, behavior: 'smooth' });
        }
    })
    .catch(error => {
        document.getElementById('messageBox').innerHTML = '<div class="alert error"><i class="fa-solid fa-circle-exclamation"></i> Network error</div>';
    })
    .finally(() => {
        submitBtn.disabled = false;
        submitBtn.innerHTML = '<i class="fa-solid fa-floppy-disk"></i> Save Match Details';
    });
});

function deleteMatch(id) {
    if(!confirm('Delete this match permanently?')) return;
    const formData = new FormData();
    formData.append('id', id);
    fetch('?api=delete_match&cat_id=<?= $active_cat_id ?>', {
        method: 'POST',
        body: formData
    })
    .then(res => res.json())
    .then(data => {
        if(data.status === 'success') {
            window.location.reload();
        } else {
            alert(data.message);
        }
    });
}

function deleteAll(type) {
    const confirmMsg = type === 'going' ? 'Delete ALL Ongoing Matches?' : 'Delete ALL Result Matches?';
    if(!confirm(confirmMsg)) return;
    const api = type === 'going' ? 'delete_all_going' : 'delete_all_result';
    fetch('?api=' + api + '&cat_id=<?= $active_cat_id ?>', { method: 'POST' })
    .then(res => res.json())
    .then(data => {
        if(data.status === 'success') window.location.reload();
        else alert(data.message);
    });
}
</script>
</body>
</html>