<?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');

function formatDatetime($dt) {
    if (!$dt) return '';
    return str_replace('T', ' ', $dt) . (strlen($dt) == 16 ? ':00' : '');
}

function bn_date($datetime) {
    if(!$datetime || $datetime === '0000-00-00 00:00:00') return '';
    $engDATE = array('1','2','3','4','5','6','7','8','9','0','January','February','March','April','May','June','July','August','September','October','November','December','Saturday','Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','am','pm','AM','PM');
    $bangDATE = array('১','২','৩','৪','৫','৬','৭','৮','৯','০','জানুয়ারি','ফেব্রুয়ারি','মার্চ','এপ্রিল','মে','জুন','জুলাই','আগস্ট','সেপ্টেম্বর','অক্টোবর','নভেম্বর','ডিসেম্বর','শনিবার','রবিবার','সোমবার','মঙ্গলবার','বুধবার','বৃহস্পতিবার','শুক্রবার','এএম','পিএম','এএম','পিএম');
    $format = date('d F Y, h:i A', strtotime($datetime));
    return str_replace($engDATE, $bangDATE, $format);
}

function generateUniqueMatchId($conn) {
    do {
        $newId = mt_rand(10000000, 99999999);
        $chk = $conn->query("SELECT id FROM match_schedule WHERE id = $newId");
        if ($chk && $chk->num_rows > 0) continue;
        $chk2 = $conn->query("SELECT match_id FROM joiners WHERE match_id = $newId LIMIT 1");
        if ($chk2 && $chk2->num_rows > 0) continue;
        break;
    } while (true);
    return $newId;
}

function getNextTitleNumber($conn, $baseTitle, $matchType) {
    $like = $baseTitle . '%';
    $stmt = $conn->prepare("SELECT match_title FROM match_schedule WHERE match_type = ? AND CONVERT(match_title USING utf8mb4) COLLATE utf8mb4_general_ci LIKE ? ORDER BY id DESC LIMIT 1");
    if (!$stmt) return 1;
    $stmt->bind_param("ss", $matchType, $like);
    $stmt->execute();
    $res = $stmt->get_result();
    if ($row = $res->fetch_assoc()) {
        $parts = explode(' ', $row['match_title']);
        $last = end($parts);
        if (is_numeric($last)) {
            return (int)$last + 1;
        }
    }
    return 1;
}

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 id, title, image_link FROM category ORDER BY id ASC");
if ($catRes) {
    while ($c = $catRes->fetch_assoc()) {
        $categories[$c['id']] = [
            'title' => $c['title'],
            'img' => $c['image_link']
        ];
    }
}

$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'];

$active_tab = $_GET['tab'] ?? 'upcoming';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'save_rules' && $active_cat['add_rules'] === 'Yes') {
        $rules_text = trim($_POST['rules_text'] ?? '');
        $date = date('Y-m-d H:i:s');
        $chk = $conn->prepare("SELECT id FROM match_rules WHERE match_type = ?");
        $chk->bind_param("s", $active_match_type);
        $chk->execute();
        $res = $chk->get_result();
        if ($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();
        } else {
            $ins = $conn->prepare("INSERT INTO match_rules (match_type, rules, created_at) VALUES (?, ?, ?)");
            $ins->bind_param("sss", $active_match_type, $rules_text, $date);
            $ins->execute();
        }
        $_SESSION['sys_msg'] = "Rules updated successfully!";
        header("Location: ?cat_id=" . $active_cat_id . "&tab=" . $active_tab);
        exit;
    }

    if ($_POST['action'] === 'save_template' && $active_cat['add_match'] === 'Yes') {
        $t_title = trim($_POST['t_title'] ?? '');
        $t_win_amt = trim($_POST['t_win_amt'] ?? '0');
        $t_kill_reward = trim($_POST['t_kill_reward'] ?? '0');
        $t_entry_fee = trim($_POST['t_entry_fee'] ?? '0');
        $t_slots = trim($_POST['t_slots'] ?? '0');
        $t_prize_details = trim($_POST['t_prize_details'] ?? '');
        $t_type = $active_match_type;
        $t_created_at = date('Y-m-d H:i:s');

        $ins = $conn->prepare("INSERT INTO matches (title, win_amt, kill_reward, entry_fee, slots, prize_details, type, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
        if ($ins) {
            $ins->bind_param("ssssssss", $t_title, $t_win_amt, $t_kill_reward, $t_entry_fee, $t_slots, $t_prize_details, $t_type, $t_created_at);
            $ins->execute();
            $ins->close();
            $_SESSION['sys_msg'] = "New Template saved successfully!";
        }
        header("Location: ?cat_id=" . $active_cat_id . "&tab=" . $active_tab);
        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);
        
        $base_match_title = trim($_POST['match_title'] ?? '');
        $total_match = (int)($_POST['total_match'] ?? 1);
        
        $start_time_raw = trim($_POST['start_time'] ?? '');
        $interval_minute = trim($_POST['interval_minute'] ?? '10');
        $timer_raw = trim($_POST['timer'] ?? '');
        
        $total_prize = trim($_POST['total_prize'] ?? '0'); if ($total_prize === '') $total_prize = '0';
        $per_kill = trim($_POST['per_kill'] ?? '0'); if ($per_kill === '') $per_kill = '0';
        $entry_fee = trim($_POST['entry_fee'] ?? '0'); if ($entry_fee === '') $entry_fee = '0';
        $total_player = trim($_POST['total_player'] ?? '0'); 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');
        $schedule_status = trim($_POST['schedule_status'] ?? 'Yes');
        
        $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'] ?? '0'); if ($total_joiner === '') $total_joiner = '0';
        
        $match_result = trim($_POST['match_result'] ?? 'No');
        $status = trim($_POST['status'] ?? '0');
        $created_count = trim($_POST['created_count'] ?? '0');
        
        $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;
            }
            
            $start_time = formatDatetime($start_time_raw);
            $timer = formatDatetime($timer_raw);
            $match_time = $timer ? date('d/m/Y \A\t h:i A', strtotime($timer)) : '';
            
            $sql = "UPDATE match_schedule SET 
                    match_title=?, total_match=?, start_time=?, interval_minute=?, match_time=?, total_prize=?, per_kill=?, entry_fee=?, entry_type=?, version=?, play_map=?, registration=?, total_player=?, prize_details=?, timer=?, join_type=?, status=?, created_count=?, room_id=?, room_pass=?, total_joiner=?, match_result=?, image_link=?, locked=?, locked_type=?, player_name_change=?, schedule_status=? 
                    WHERE id=? AND match_type=?";
                    
            $stmt = $conn->prepare($sql);
            if (!$stmt) {
                echo json_encode(["status" => "error", "message" => "DB Error: " . $conn->error]); 
                exit;
            }

            $stmt->bind_param("sssssssssssssssssssssssssssis", 
                $base_match_title, $total_match, $start_time, $interval_minute, $match_time, 
                $total_prize, $per_kill, $entry_fee, $entry_type, $version, 
                $play_map, $registration, $total_player, $prize_details, $timer, 
                $join_type, $status, $created_count, $room_id, $room_pass, 
                $total_joiner, $match_result, $image_link, $locked, $locked_type, 
                $player_name_change, $schedule_status, $id, $active_match_type
            );
            
            if (!$stmt->execute()) {
                echo json_encode(["status" => "error", "message" => "Update Failed: " . $stmt->error]); 
                exit;
            }
            $stmt->close();
            
            $msg = "Schedule 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}, আপনার জয়েনকৃত ম্যাচ ({$base_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;
            }
            
            $room_id = 'No';
            $room_pass = 'No';
            $total_joiner = '0';
            $match_result = 'No';
            $status = '0';
            $created_count = '0';
            
            $sql = "INSERT INTO match_schedule (
                    id, match_title, total_match, start_time, interval_minute, match_time, total_prize, per_kill, entry_fee, entry_type, match_type, version, play_map, registration, total_player, prize_details, timer, join_type, status, created_count, room_id, room_pass, total_joiner, match_result, image_link, locked, locked_type, player_name_change, schedule_status
                ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
            $stmt = $conn->prepare($sql);
            if (!$stmt) {
                echo json_encode(["status" => "error", "message" => "DB Error: " . $conn->error]); 
                exit;
            }

            $base_start_ts = $start_time_raw ? strtotime($start_time_raw) : time();
            $base_timer_ts = $timer_raw ? strtotime($timer_raw) : time();
            $startNumber = getNextTitleNumber($conn, $base_match_title, $active_match_type);
            
            for ($i = 0; $i < $total_match; $i++) {
                $add_seconds = $i * $interval_minute * 60;
                
                $curr_start = date('Y-m-d H:i:s', $base_start_ts + $add_seconds);
                $curr_timer = date('Y-m-d H:i:s', $base_timer_ts + $add_seconds);
                $curr_mtime = date('d/m/Y \A\t h:i A', $base_timer_ts + $add_seconds);
                
                $newMatchId = generateUniqueMatchId($conn);
                $numberedTitle = $base_match_title . ' ' . str_pad($startNumber + $i, 2, '0', STR_PAD_LEFT);
                
                $stmt->bind_param("issssssssssssssssssssssssssss", 
                    $newMatchId, $numberedTitle, $total_match, $curr_start, $interval_minute, $curr_mtime, 
                    $total_prize, $per_kill, $entry_fee, $entry_type, $active_match_type, 
                    $version, $play_map, $registration, $total_player, $prize_details, 
                    $curr_timer, $join_type, $status, $created_count, $room_id, 
                    $room_pass, $total_joiner, $match_result, $image_link, $locked, 
                    $locked_type, $player_name_change, $schedule_status
                );
                $stmt->execute();
            }
            $stmt->close();
            
            echo json_encode(["status" => "success", "message" => "$total_match Schedule(s) added successfully!", "type" => "add"]);
            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') {
    if ($active_cat['delete_match'] === 'Yes') {
        $id = (int)($_POST['id'] ?? 0);
        $stmt = $conn->prepare("DELETE FROM match_schedule WHERE id = ?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $stmt->close();
        echo json_encode(["status" => "success", "message" => "Schedule deleted successfully!"]);
    } else {
        echo json_encode(["status" => "error", "message" => "Permission denied."]);
    }
    exit;
}

if (isset($_GET['api']) && $_GET['api'] == 'delete_all_ongoing') {
    if ($active_cat['delete_match'] === 'Yes') {
        $now = date('Y-m-d H:i:s');
        $stmt = $conn->prepare("DELETE FROM match_schedule WHERE match_type = ? AND timer <= ? AND match_result != 'Yes'");
        $stmt->bind_param("ss", $active_match_type, $now);
        $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') {
    if ($active_cat['delete_match'] === 'Yes') {
        $stmt = $conn->prepare("DELETE FROM match_schedule 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;
}

$now = date('Y-m-d H:i:s');

$count_upcoming = 0;
$count_ongoing = 0;
$count_result = 0;

$stmt_up = $conn->prepare("SELECT COUNT(id) as c FROM match_schedule WHERE match_type = ? AND timer > ? AND match_result != 'Yes'");
$stmt_up->bind_param("ss", $active_match_type, $now);
$stmt_up->execute();
$count_upcoming = $stmt_up->get_result()->fetch_assoc()['c'] ?? 0;
$stmt_up->close();

$stmt_on = $conn->prepare("SELECT COUNT(id) as c FROM match_schedule WHERE match_type = ? AND timer <= ? AND match_result != 'Yes'");
$stmt_on->bind_param("ss", $active_match_type, $now);
$stmt_on->execute();
$count_ongoing = $stmt_on->get_result()->fetch_assoc()['c'] ?? 0;
$stmt_on->close();

$stmt_res = $conn->prepare("SELECT COUNT(id) as c FROM match_schedule WHERE match_type = ? AND match_result = 'Yes'");
$stmt_res->bind_param("s", $active_match_type);
$stmt_res->execute();
$count_result = $stmt_res->get_result()->fetch_assoc()['c'] ?? 0;
$stmt_res->close();


$page = isset($_GET['p']) ? max(1, (int)$_GET['p']) : 1;
$limit = 20;
$offset = ($page - 1) * $limit;

$condition = "";
if ($active_tab === 'upcoming') {
    $condition = " AND timer > '$now' AND match_result != 'Yes'";
} elseif ($active_tab === 'ongoing') {
    $condition = " AND timer <= '$now' AND match_result != 'Yes'";
} elseif ($active_tab === 'result') {
    $condition = " AND match_result = 'Yes'";
}

$total_matches = 0;
$c_stmt = $conn->prepare("SELECT COUNT(id) as c FROM match_schedule WHERE match_type = ? $condition");
$c_stmt->bind_param("s", $active_match_type);
$c_stmt->execute();
$c_res = $c_stmt->get_result();
if ($c_row = $c_res->fetch_assoc()) {
    $total_matches = $c_row['c'];
}
$c_stmt->close();

$total_pages = ceil($total_matches / $limit);

$matches = [];
$stmt = $conn->prepare("SELECT * FROM match_schedule WHERE match_type = ? $condition ORDER BY id DESC LIMIT ? OFFSET ?");
$stmt->bind_param("sii", $active_match_type, $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'); }
require_once "header.php";
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Match Schedule Management</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        :root {
            --bg: #f8fafc; --surface: #ffffff; --primary: #3b82f6; --primary-hover: #2563eb;
            --danger: #ef4444; --warning: #f59e0b; --success: #10b981;
            --text-main: #1e293b; --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: 12px; --radius-lg: 16px;
        }
        * { box-sizing: border-box; margin: 0; padding: 0; font-family: 'Inter', system-ui, sans-serif; }
        body { background: var(--bg); color: var(--text-main); -webkit-font-smoothing: antialiased; }
        
        .topbar { background: var(--surface); padding: 16px 24px; 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 var(--border); }
        .brand { font-size: 18px; font-weight: 800; color: var(--primary); display: flex; align-items: center; gap: 8px; letter-spacing: -0.5px; }
        .cat-select { padding: 10px 16px; border-radius: 8px; border: 1px solid var(--border); font-size: 14px; font-weight: 600; cursor: pointer; outline: none; background: var(--bg); color: var(--text-main); transition: 0.2s; appearance: none; }
        .cat-select:hover { border-color: var(--primary); }
        
        .container { max-width: 1280px; margin: 0 auto; padding: 24px; }
        
        .view-section { display: none; animation: fadeIn 0.2s ease; }
        .view-section.active { display: block; }
        @keyframes fadeIn { from { opacity: 0; transform: translateY(5px); } to { opacity: 1; transform: translateY(0); } }

        .btn { padding: 10px 18px; border: none; border-radius: 8px; font-weight: 600; 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: var(--primary); color: #fff; box-shadow: 0 4px 10px rgba(59,130,246,0.2); }
        .btn-primary:hover { background: var(--primary-hover); transform: translateY(-1px); }
        .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: transparent; border: 1px solid var(--border); color: var(--text-main); }
        .btn-outline:hover { background: var(--bg); }
        
        .header-actions { display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px; flex-wrap: wrap; gap: 16px; }
        .view-title { font-size: 20px; font-weight: 700; color: var(--text-main); letter-spacing: -0.5px; }
        
        .alert { padding: 14px 16px; border-radius: 10px; margin-bottom: 24px; font-weight: 500; background: #ecfdf5; color: #065f46; border: 1px solid #a7f3d0; display: flex; align-items: center; gap: 10px; font-size: 14px; }
        .alert.error { background: #fef2f2; color: #991b1b; border-color: #fca5a5; }
        
        .tabs { display: flex; gap: 10px; overflow-x: auto; scrollbar-width: none; }
        .tabs::-webkit-scrollbar { display: none; }
        .tab-btn { padding: 10px 18px; border-radius: 8px; font-weight: 600; font-size: 14px; text-decoration: none; color: var(--text-muted); background: var(--surface); border: 1px solid var(--border); transition: 0.2s; white-space: nowrap; display: inline-flex; align-items: center; gap: 8px; }
        .tab-btn:hover { background: var(--bg); color: var(--primary); }
        .tab-btn.active { background: var(--primary); color: #fff; border-color: var(--primary); }

        .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: #eff6ff; color: #1e40af; padding: 8px 16px; border-radius: 20px; font-size: 13px; font-weight: 600; border: 1px solid #bfdbfe; cursor: pointer; white-space: nowrap; transition: 0.2s; flex-shrink: 0; }
        .template-btn:hover { background: #dbeafe; }

        .form-card { background: var(--surface); padding: 32px; border-radius: var(--radius-lg); box-shadow: var(--shadow-md); border: 1px solid var(--border); }
        .grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px; }
        .field { display: flex; flex-direction: column; gap: 6px; }
        .field.full { grid-column: 1 / -1; }
        .field label { font-size: 13px; font-weight: 600; color: var(--text-muted); display: flex; align-items: center; gap: 6px; }
        .field input, .field select, .field textarea { padding: 12px 14px; border-radius: 10px; border: 1px solid var(--border); font-size: 14px; background: var(--bg); transition: 0.2s; color: var(--text-main); outline: none; width: 100%; }
        .field input:focus, .field select:focus, .field textarea:focus { background: #fff; border-color: var(--primary); box-shadow: 0 0 0 3px rgba(59,130,246,0.1); }
        
        .match-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 20px; }
        .match-card { background: var(--surface); border-radius: var(--radius-md); overflow: hidden; box-shadow: var(--shadow-sm); transition: 0.3s; display: flex; flex-direction: column; border: 1px solid var(--border); }
        .match-card:hover { transform: translateY(-4px); box-shadow: var(--shadow-md); }
        .mc-img { width: 100%; height: 150px; object-fit: cover; background: #e5e7eb; position: relative; }
        .mc-status { position: absolute; top: 12px; right: 12px; padding: 4px 10px; border-radius: 6px; font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; }
        .mc-status.open { background: var(--success); color: #fff; }
        .mc-status.closed { background: var(--danger); color: #fff; }
        .mc-id { position: absolute; top: 12px; left: 12px; padding: 4px 8px; border-radius: 6px; font-size: 12px; font-weight: 700; background: rgba(0,0,0,0.7); color: #fff; backdrop-filter: blur(4px); }
        .mc-body { padding: 16px; flex: 1; display: flex; flex-direction: column; }
        .mc-title { font-size: 16px; font-weight: 700; margin-bottom: 12px; 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; gap: 10px; margin-bottom: 16px; font-size: 13px; }
        .mc-info-item { display: flex; align-items: center; gap: 8px; color: var(--text-muted); font-weight: 500; }
        .mc-info-item i { color: var(--primary); width: 16px; text-align: center; }
        .mc-price { font-size: 15px; font-weight: 700; color: var(--success); margin-top: auto; display: flex; align-items: center; justify-content: space-between; padding-top: 16px; border-top: 1px solid var(--border); }
        .mc-price-fee { color: var(--text-main); display: flex; align-items: center; gap: 6px; }
        
        .mc-actions { display: flex; gap: 8px; margin-top: 16px; flex-wrap: wrap; }
        .mc-actions button, .mc-actions a.btn { flex: 1; padding: 8px; font-size: 13px; justify-content: center; }

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

        .hidden { display: none !important; }
        
        .time-picker-wrapper { display: flex; gap: 8px; align-items: center; }
        .time-picker-wrapper input[type="datetime-local"] { width: 100%; }

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

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

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

    <div class="header-actions" id="mainHeader">
        <div class="view-title" id="pageTitle">Scheduled Match List</div>
        <div style="display:flex; gap:10px; 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-file-alt"></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 Schedule</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; border-bottom: 1px solid var(--border); padding-bottom: 16px;">
            <div class="tabs">
                <a href="?cat_id=<?= $active_cat_id ?>&tab=upcoming" class="tab-btn <?= $active_tab === 'upcoming' ? 'active' : '' ?>">
                    <i class="fa-regular fa-clock"></i> Upcoming (<?= $count_upcoming ?>)
                </a>
                <a href="?cat_id=<?= $active_cat_id ?>&tab=ongoing" class="tab-btn <?= $active_tab === 'ongoing' ? 'active' : '' ?>">
                    <i class="fa-solid fa-play"></i> Ongoing (<?= $count_ongoing ?>)
                </a>
                <a href="?cat_id=<?= $active_cat_id ?>&tab=result" class="tab-btn <?= $active_tab === 'result' ? 'active' : '' ?>">
                    <i class="fa-solid fa-check-double"></i> Results (<?= $count_result ?>)
                </a>
            </div>

            <?php if ($active_cat['delete_match'] === 'Yes'): ?>
            <div style="display: flex; gap: 10px; flex-wrap: wrap;">
                <button onclick="deleteAll('delete_all_ongoing')" class="btn btn-danger"><i class="fa-solid fa-trash-can"></i> Delete All Ongoing</button>
                <button onclick="deleteAll('delete_all_result')" class="btn btn-danger"><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): 
                    $isOpen = (strtolower($m['registration']) !== 'close' && strtolower($m['schedule_status']) === 'yes');
                ?>
                <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 ? 'Active Schedule' : 'Inactive' ?></div>
                    </div>
                    <div class="mc-body">
                        <div class="mc-title"><?= e($m['match_title']) ?> (Total: <?= e($m['total_match']) ?>)</div>
                        <div class="mc-info">
                            <div class="mc-info-item"><i class="fa-solid fa-hourglass-start"></i> তৈরীর সময়: <?= bn_date($m['start_time']) ?></div>
                            <div class="mc-info-item"><i class="fa-regular fa-clock"></i> শুরুর সময়: <?= bn_date($m['timer']) ?></div>
                            <div class="mc-info-item" style="display:grid; grid-template-columns:1fr 1fr; gap:10px; width:100%;">
                                <div><i class="fa-solid fa-users"></i> <?= e($m['entry_type']) ?></div>
                                <div><i class="fa-solid fa-map-location-dot"></i> <?= e($m['play_map']) ?></div>
                                <div><i class="fa-solid fa-stopwatch"></i> Gap: <?= e($m['interval_minute']) ?> Min</div>
                                <div><i class="fa-solid fa-mobile-screen"></i> <?= e($m['version']) ?></div>
                            </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 ?>&tab=<?= $active_tab ?>&p=<?= $p ?>" class="page-link <?= $p === $page ? 'active' : '' ?>"><?= $p ?></a>
                    <?php endif;
                endforeach;
                ?>
            </div>
            <?php endif; ?>

        <?php else: ?>
            <div style="text-align:center; padding:60px 20px; background:var(--surface); border-radius:var(--radius-lg); color:var(--text-muted); border:1px solid var(--border);">
                <i class="fa-solid fa-calendar-xmark fa-3x" style="margin-bottom:16px; color:var(--border);"></i>
                <h3 style="font-weight:600; color:var(--text-main); margin-bottom:8px;">No Matches Found</h3>
                <p style="font-size:14px;">কোনো <?= ucfirst($active_tab) ?> ম্যাচ পাওয়া যায়নি।</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:24px;">
                <h3 id="formTitleText" style="font-size:18px; font-weight:700; color:var(--text-main);"><i class="fa-solid fa-plus"></i> Create Schedule</h3>
                <button class="btn btn-outline" onclick="closeForm()" style="padding:8px 12px;"><i class="fa-solid fa-xmark"></i> Close</button>
            </div>

            <div class="quick-templates" id="quickTemplates">
                <button class="template-btn" type="button" onclick="openTemplateModal()" style="background:var(--primary); color:#fff; border-color:var(--primary);"><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: #eff6ff; border-radius: 20px; overflow: hidden; box-shadow: var(--shadow-sm); border: 1px solid #bfdbfe;">
                        <button type="button" style="background: transparent; color: #1e40af; padding: 8px 16px; font-size: 13px; font-weight: 600; 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='#1e40af'" 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">
                <input type="hidden" name="status" id="f_status" value="0">
                <input type="hidden" name="created_count" id="f_ccount" 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">
                        <label>Total Matches (কয়টি ম্যাচ তৈরি হবে?)</label>
                        <input type="number" name="total_match" id="f_tmatch" value="1" min="1" required>
                    </div>
                    
                    <div class="field">
                        <label>Interval Minute (কত মিনিট পরপর এড হবে)</label>
                        <input type="number" name="interval_minute" id="f_intmin" value="10" min="1" max="60" required>
                    </div>
                    
                    <div class="field">
                        <label>Start Time (ম্যাচ কখন তৈরি হবে?)</label>
                        <div class="time-picker-wrapper">
                            <input type="datetime-local" name="start_time" id="f_stime" required>
                        </div>
                    </div>
                    
                    <div class="field">
                        <label>Match Timer (ম্যাচ কখন শুরু হবে?)</label>
                        <div class="time-picker-wrapper">
                            <input type="datetime-local" name="timer" id="f_timer" required>
                        </div>
                    </div>

                    <div class="field"><label>Entry Fee</label><input type="number" name="entry_fee" id="f_fee" required></div>
                    <div class="field"><label>Per Kill</label><input type="number" name="per_kill" id="f_kill" required></div>
                    <div class="field"><label>Total Prize</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:8px;" placeholder="Enter custom map name">
                    </div>
                    
                    <div class="field">
                        <label>Schedule Status</label>
                        <select name="schedule_status" id="f_sched_status">
                            <option value="Yes">Yes</option>
                            <option value="No">No</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" selected>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" selected>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="4" placeholder="🏆 Winner List..."></textarea>
                    </div>

                    <div class="field edit-only hidden"><label>Room ID</label><input type="text" name="room_id" id="f_rid"></div>
                    <div class="field edit-only hidden"><label>Room Password</label><input type="text" name="room_pass" id="f_rpass"></div>
                    <div class="field edit-only hidden"><label>Joined Players</label><input type="number" name="total_joiner" id="f_tjoiner"></div>
                    
                    <div class="field edit-only hidden">
                        <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 edit-only hidden">
                        <label>Publish Result?</label>
                        <select name="match_result" id="f_mres">
                            <option value="No">No</option>
                            <option value="Yes">Yes</option>
                        </select>
                    </div>
                </div>

                <div class="field full edit-only hidden" style="background:#f0fdf4; border:1px solid #bbf7d0; padding:16px; border-radius:10px; margin-top:20px;">
                    <label style="display:flex; justify-content:space-between; align-items:center; width:100%; margin:0;">
                        <span style="font-size:15px; color:#166534;"><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; color:#166534;">
                            <input type="checkbox" name="send_notification" value="Yes" checked style="width:18px; height:18px;"> Yes, Send
                        </label>
                    </label>
                </div>
                
                <div class="field full" style="margin-top:24px;">
                    <button type="submit" class="btn btn-primary" id="submitBtn" style="width:100%; padding:14px; font-size:15px;"><i class="fa-solid fa-floppy-disk"></i> Save Schedule</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:24px;">
                <h3 style="font-size:18px; font-weight:700; color:var(--text-main);"><i class="fa-solid fa-file-alt"></i> Match Rules</h3>
                <button class="btn btn-outline" onclick="toggleView('listView', 'Schedule List')" style="padding:8px 12px;"><i class="fa-solid fa-arrow-left"></i> Back</button>
            </div>
            <form method="post">
                <input type="hidden" name="action" value="save_rules">
                <div class="field full" style="margin-bottom:24px;">
                    <textarea name="rules_text" rows="12" placeholder="Enter match rules..."><?= e($current_rules) ?></textarea>
                </div>
                <button type="submit" class="btn btn-primary" style="width:100%; padding:14px;"><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:18px; font-weight:700;"><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">
            <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 Schedule';
    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_tmatch').value = '1';
    document.getElementById('f_intmin').value = '10';
    document.getElementById('f_stime').value = '';
    document.getElementById('f_timer').value = '';
    document.getElementById('f_sched_status').value = 'Yes';
    document.getElementById('f_reg').value = 'Open';
    
    document.getElementById('f_lock').value = 'true';
    document.getElementById('f_pnc').value = 'true';
    document.getElementById('f_tjoiner').value = '0';
    
    document.getElementById('f_map_select').value = 'Bermuda';
    handleMapChange();
    
    document.querySelectorAll('.edit-only').forEach(el => el.classList.add('hidden'));
    toggleView('formView', 'Create Schedule');
}

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

function formatForInput(dtStr) {
    if(!dtStr || dtStr === '0000-00-00 00:00:00') return '';
    return dtStr.replace(' ', 'T').substring(0, 16);
}

function editMatch(data) {
    document.getElementById('formTitleText').innerHTML = '<i class="fa-solid fa-pen"></i> Edit Schedule';
    document.getElementById('f_id').value = data.id;
    document.getElementById('f_status').value = data.status || '0';
    document.getElementById('f_ccount').value = data.created_count || '0';
    
    document.getElementById('quickTemplates').classList.add('hidden');
    
    document.getElementById('f_title').value = data.match_title || '';
    document.getElementById('f_tmatch').value = data.total_match || '1';
    document.getElementById('f_intmin').value = data.interval_minute || '10';
    document.getElementById('f_stime').value = formatForInput(data.start_time);
    document.getElementById('f_timer').value = formatForInput(data.timer);
    
    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_sched_status').value = data.schedule_status || 'Yes';
    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 || '<?= e($active_cat_image) ?>';
    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.querySelectorAll('.edit-only').forEach(el => el.classList.remove('hidden'));
    toggleView('formView', 'Edit Schedule');
}

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 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 {
            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 Schedule';
    });
});

function deleteMatch(id) {
    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(actionType) {
    fetch('?api=' + actionType + '&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>