<?php
require_once "config.php";

session_set_cookie_params(['lifetime' => 0, 'path' => '/', 'httponly' => true]);
session_start();
date_default_timezone_set("Asia/Dhaka");

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

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

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

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

$canRead = $canEdit = $canDelete = false;

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

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

    $action = $_GET['api'];

    if ($action === 'fetch') {
        $tab = $_GET['tab'] ?? 'all';
        $whereClause = ""; $params = []; $types = "";
        
        if (in_array($tab, ['upcoming', 'live', 'completed'])) {
            $whereClause = "WHERE tab_category = ?";
            $params[] = $tab; $types .= "s";
        }

        $sql = "SELECT * FROM ZabbarXLudoMatch $whereClause ORDER BY id DESC";
        $stmt = $conn->prepare($sql);
        if (!empty($params)) $stmt->bind_param($types, ...$params);
        $stmt->execute();
        $result = $stmt->get_result();
        $data = [];
        while ($row = $result->fetch_assoc()) $data[] = $row;
        $stmt->close();
        
        echo json_encode(["status" => "success", "data" => $data]);
        exit;
    }

    if ($action === 'process' && $_SERVER['REQUEST_METHOD'] === 'POST') {
        $type = strtolower(trim($_POST['type'] ?? ''));
        if (in_array($type, ['add', 'edit']) && !$canEdit) die(json_encode(["status" => "error", "message" => "Edit/Add permission denied."]));
        if ($type === 'delete' && !$canDelete) die(json_encode(["status" => "error", "message" => "Delete permission denied."]));

        try {
            if ($type === 'add' || $type === 'edit') {
                $id = (int)($_POST['id'] ?? 0);
                $title = trim($_POST['title'] ?? '');
                $match_type = trim($_POST['match_type'] ?? '2 Player');
                $badge_text = trim($_POST['badge_text'] ?? '');
                $match_category = trim($_POST['match_category'] ?? '1vs1');
                $prize_amount = trim($_POST['prize_amount'] ?? '');
                $entry_fee = trim($_POST['entry_fee'] ?? '');
                
                $total_join = (int)($_POST['total_join'] ?? 2);
                $total_joined = (int)($_POST['total_joined'] ?? 0);
                
                $time_label = trim($_POST['time_label'] ?? '');
                $time_value = trim($_POST['time_value'] ?? '');
                $button_text = trim($_POST['button_text'] ?? '');
                $theme_start_color = trim($_POST['theme_start_color'] ?? '');
                $theme_end_color = trim($_POST['theme_end_color'] ?? '');
                $icon_type = trim($_POST['icon_type'] ?? 'TROPHY');
                $tab_category = trim($_POST['tab_category'] ?? '');
                
                $player_1 = trim($_POST['player_1'] ?? '');
                $player_2 = trim($_POST['player_2'] ?? '');
                $player_3 = trim($_POST['player_3'] ?? '');
                $player_4 = trim($_POST['player_4'] ?? '');

                // যদি ম্যাচ 1vs1 হয় তবে এক্সট্রা প্লেয়ার ডেটা ক্লিয়ার করে দেওয়া হলো
                if ($match_category === '1vs1') {
                    $player_3 = '';
                    $player_4 = '';
                }

                if ($title === '') throw new Exception("Title cannot be empty.");

                if ($type === 'add') {
                    $stmt = $conn->prepare("INSERT INTO ZabbarXLudoMatch (title, match_type, badge_text, match_category, prize_amount, entry_fee, total_join, total_joined, time_label, time_value, button_text, theme_start_color, theme_end_color, icon_type, tab_category, player_1, player_2, player_3, player_4) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                    $stmt->bind_param("ssssssiisssssssssss", $title, $match_type, $badge_text, $match_category, $prize_amount, $entry_fee, $total_join, $total_joined, $time_label, $time_value, $button_text, $theme_start_color, $theme_end_color, $icon_type, $tab_category, $player_1, $player_2, $player_3, $player_4);
                    if (!$stmt->execute()) throw new Exception("Failed to add match.");
                    $stmt->close();
                    $msg = "Match added successfully.";
                } else {
                    $stmt = $conn->prepare("UPDATE ZabbarXLudoMatch SET title=?, match_type=?, badge_text=?, match_category=?, prize_amount=?, entry_fee=?, total_join=?, total_joined=?, time_label=?, time_value=?, button_text=?, theme_start_color=?, theme_end_color=?, icon_type=?, tab_category=?, player_1=?, player_2=?, player_3=?, player_4=? WHERE id=?");
                    $stmt->bind_param("ssssssiisssssssssssi", $title, $match_type, $badge_text, $match_category, $prize_amount, $entry_fee, $total_join, $total_joined, $time_label, $time_value, $button_text, $theme_start_color, $theme_end_color, $icon_type, $tab_category, $player_1, $player_2, $player_3, $player_4, $id);
                    if (!$stmt->execute()) throw new Exception("Failed to update match.");
                    $stmt->close();
                    $msg = "Match updated successfully.";
                }
                echo json_encode(["status" => "success", "message" => $msg]);

            } elseif ($type === 'delete') {
                $id = (int)($_POST['id'] ?? 0);
                $stmt = $conn->prepare("DELETE FROM ZabbarXLudoMatch WHERE id = ?");
                $stmt->bind_param("i", $id);
                if (!$stmt->execute()) throw new Exception("Failed to delete match.");
                $stmt->close();
                echo json_encode(["status" => "success", "message" => "Match deleted successfully."]);
            }
        } catch (Exception $e) {
            echo json_encode(["status" => "error", "message" => $e->getMessage()]);
        }
        exit;
    }
    exit;
}

if (!$canRead) {
    die("Access Denied");
}
require_once "header.php";
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ludo Match Management</title>
    <style>
        :root { --slate-50:#f8fafc; --slate-100:#f1f5f9; --slate-200:#e2e8f0; --slate-500:#64748b; --slate-700:#334155; --slate-900:#0f172a; --primary:#4f46e5; --white:#fff; }
        * { box-sizing: border-box; margin: 0; padding: 0; font-family: system-ui, sans-serif; }
        body { background: var(--slate-50); color: var(--slate-900); }
        .container { max-width: 1400px; margin: 0 auto; padding: 20px; }
        
        .header { background: var(--white); padding: 20px; border-radius: 12px; margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center; box-shadow: 0 1px 3px rgba(0,0,0,0.05); }
        .header h1 { font-size: 20px; }
        
        .btn { padding: 10px 20px; border-radius: 6px; font-weight: 600; border: none; cursor: pointer; transition: 0.2s; }
        .btn-primary { background: var(--primary); color: var(--white); }
        .btn-secondary { background: var(--slate-200); color: var(--slate-700); }
        .btn-danger { background: #e11d48; color: var(--white); }
        
        .tabs { display: flex; gap: 10px; margin-bottom: 20px; background: var(--white); padding: 10px; border-radius: 12px; }
        .tab-btn { padding: 8px 16px; border: none; background: transparent; font-weight: 600; cursor: pointer; border-radius: 6px; }
        .tab-btn.active { background: var(--primary); color: var(--white); }
        
        .grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(350px, 1fr)); gap: 16px; }
        .card { background: var(--white); padding: 20px; border-radius: 12px; box-shadow: 0 1px 3px rgba(0,0,0,0.05); border: 1px solid var(--slate-200); }
        .card-header { display: flex; justify-content: space-between; margin-bottom: 15px; }
        .badge { padding: 4px 10px; border-radius: 20px; font-size: 12px; font-weight: 700; background: var(--slate-100); }
        .info-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 15px; }
        .info-box { background: var(--slate-50); padding: 10px; border-radius: 6px; font-size: 14px; }
        .info-box small { display: block; color: var(--slate-500); font-size: 11px; margin-bottom: 4px; }
        .actions { display: flex; gap: 8px; margin-top: 15px; border-top: 1px solid var(--slate-200); padding-top: 15px; }

        .form-view { background: var(--white); padding: 30px; border-radius: 12px; display: none; }
        .form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 15px; }
        .form-group label { display: block; font-size: 13px; font-weight: 600; margin-bottom: 5px; color: var(--slate-700); }
        .form-control { width: 100%; padding: 10px; border: 1px solid var(--slate-200); border-radius: 6px; outline: none; }
        
        .toast-container { position: fixed; bottom: 20px; right: 20px; z-index: 1000; }
        .toast { padding: 12px 20px; margin-top: 10px; border-radius: 6px; color: #fff; font-weight: 600; background: var(--slate-900); }
        .toast.success { background: #10b981; }
        .toast.error { background: #e11d48; }

        @media (max-width: 768px) { .form-row { grid-template-columns: 1fr; } .tabs { overflow-x: auto; } }
    </style>
</head>
<body>

<div class="container">
    <!-- List View -->
    <div id="listView">
        <div class="header">
            <h1>Ludo Matches</h1>
            <?php if ($canEdit): ?>
            <button class="btn btn-primary" onclick="showForm('add')">Add New Match</button>
            <?php endif; ?>
        </div>

        <div class="tabs">
            <button class="tab-btn active" onclick="switchTab('all', this)">All</button>
            <button class="tab-btn" onclick="switchTab('upcoming', this)">Upcoming</button>
            <button class="tab-btn" onclick="switchTab('live', this)">Live</button>
            <button class="tab-btn" onclick="switchTab('completed', this)">Completed</button>
        </div>

        <div class="grid" id="matchGrid">Loading...</div>
    </div>

    <!-- Form View -->
    <div id="formView" class="form-view">
        <div class="header" style="box-shadow:none; padding:0; margin-bottom:20px;">
            <h2 id="formTitle">Add Match</h2>
            <button class="btn btn-secondary" onclick="hideForm()">Back to List</button>
        </div>

        <form id="matchForm" onsubmit="saveMatch(event)">
            <input type="hidden" id="m_id" name="id" value="0">
            <input type="hidden" id="m_type" name="type" value="add">
            
            <!-- Hidden Fields for Total Join -->
            <input type="hidden" id="m_total_join" name="total_join" value="2">
            <input type="hidden" id="m_total_joined" name="total_joined" value="0">

            <div class="form-row">
                <div class="form-group">
                    <label>Match Title *</label>
                    <input type="text" id="m_title" name="title" class="form-control" required>
                </div>
                <div class="form-group">
                    <label>Badge Text *</label>
                    <select id="m_badge_text" name="badge_text" class="form-control" required>
                        <option value="SOLO">SOLO</option>
                        <option value="TEAM">TEAM</option>
                        <option value="VIP">VIP</option>
                    </select>
                </div>
            </div>

            <div class="form-row">
                <div class="form-group">
                    <label>Match Category *</label>
                    <select id="m_match_category" name="match_category" class="form-control" onchange="handleCategoryChange()" required>
                        <option value="1vs1">1vs1</option>
                        <option value="2vs2">2vs2</option>
                        <option value="1vs3">1vs3</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Match Type *</label>
                    <input type="text" id="m_match_type" name="match_type" class="form-control" value="2 Player" readonly>
                </div>
            </div>

            <div class="form-row">
                <div class="form-group">
                    <label>Prize Amount *</label>
                    <input type="text" id="m_prize_amount" name="prize_amount" class="form-control">
                </div>
                <div class="form-group">
                    <label>Entry Fee *</label>
                    <input type="text" id="m_entry_fee" name="entry_fee" class="form-control">
                </div>
            </div>

            <div class="form-row">
                <div class="form-group">
                    <label>Time Label *</label>
                    <input type="text" id="m_time_label" name="time_label" class="form-control" placeholder="Match Time">
                </div>
                <div class="form-group">
                    <label>Time Value (Timer Picker) *</label>
                    <input type="datetime-local" id="m_time_value" name="time_value" class="form-control" required>
                </div>
            </div>

            <div class="form-row">
                <div class="form-group">
                    <label>Tab Category *</label>
                    <select id="m_tab_category" name="tab_category" class="form-control" required>
                        <option value="upcoming">Upcoming</option>
                        <option value="live">Live</option>
                        <option value="completed">Completed</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Button Text *</label>
                    <select id="m_button_text" name="button_text" class="form-control" required>
                        <option value="Join">Join</option>
                        <option value="Watch">Watch</option>
                        <option value="Results">Results</option>
                    </select>
                </div>
            </div>

            <div class="form-row">
                <div class="form-group">
                    <label>Icon Type</label>
                    <select id="m_icon_type" name="icon_type" class="form-control">
                        <option value="TROPHY">Trophy</option>
                        <option value="CROWN">Crown</option>
                        <option value="DIAMOND">Diamond</option>
                        <option value="USERS">Users</option>
                        <option value="CHECK">Check</option>
                        <option value="MEDAL">Medal</option>
                        <option value="STAR">Star</option>
                        <option value="SHIELD">Shield</option>
                    </select>
                </div>
                <div class="form-group" style="display:flex; gap:10px;">
                    <div style="flex:1;">
                        <label>Start Color</label>
                        <input type="color" id="m_theme_start_color" name="theme_start_color" class="form-control" style="height:40px; padding:2px;" value="#AF52DE">
                    </div>
                    <div style="flex:1;">
                        <label>End Color</label>
                        <input type="color" id="m_theme_end_color" name="theme_end_color" class="form-control" style="height:40px; padding:2px;" value="#5E5CE6">
                    </div>
                </div>
            </div>

            <!-- Players Section (Hidden in Add mode) -->
            <div id="playersSection" style="display:none; background: var(--slate-50); padding: 15px; border-radius: 8px; margin-bottom:15px;">
                <h4 style="margin-bottom: 10px;">Players</h4>
                
                <div class="form-row">
                    <div class="form-group">
                        <label>Player 1</label>
                        <input type="text" id="m_player_1" name="player_1" class="form-control">
                    </div>
                    <div class="form-group">
                        <label>Player 2</label>
                        <input type="text" id="m_player_2" name="player_2" class="form-control">
                    </div>
                </div>
                
                <!-- This row will be hidden if Match Category is 1vs1 -->
                <div class="form-row" id="extraPlayersRow">
                    <div class="form-group">
                        <label>Player 3</label>
                        <input type="text" id="m_player_3" name="player_3" class="form-control">
                    </div>
                    <div class="form-group">
                        <label>Player 4</label>
                        <input type="text" id="m_player_4" name="player_4" class="form-control">
                    </div>
                </div>

            </div>

            <div style="text-align: right;">
                <button type="submit" class="btn btn-primary" id="saveBtn">Save Match</button>
            </div>
        </form>
    </div>
</div>

<div class="toast-container" id="toastContainer"></div>

<script>
    const canEdit = <?= $canEdit ? 'true' : 'false' ?>;
    const canDelete = <?= $canDelete ? 'true' : 'false' ?>;
    let currentTab = 'all';
    let matchesData = [];

    function showToast(msg, type = 'success') {
        const c = document.getElementById('toastContainer');
        const t = document.createElement('div');
        t.className = `toast ${type}`;
        t.textContent = msg;
        c.appendChild(t);
        setTimeout(() => t.remove(), 3000);
    }

    function handleCategoryChange() {
        const cat = document.getElementById('m_match_category').value;
        const typeInput = document.getElementById('m_match_type');
        const joinInput = document.getElementById('m_total_join');
        const extraRow = document.getElementById('extraPlayersRow');

        if (cat === '2vs2' || cat === '1vs3') {
            typeInput.value = '4 Player';
            joinInput.value = 4;
            extraRow.style.display = 'grid';
        } else {
            typeInput.value = '2 Player';
            joinInput.value = 2;
            extraRow.style.display = 'none';
            // Clear inputs for extra players
            document.getElementById('m_player_3').value = '';
            document.getElementById('m_player_4').value = '';
        }
    }

    function showForm(type, id = 0) {
        document.getElementById('listView').style.display = 'none';
        document.getElementById('formView').style.display = 'block';
        document.getElementById('formTitle').textContent = type === 'add' ? 'Add Match' : 'Edit Match';
        
        const form = document.getElementById('matchForm');
        form.reset();
        
        document.getElementById('m_type').value = type;
        document.getElementById('m_id').value = id;
        document.getElementById('playersSection').style.display = (type === 'edit') ? 'block' : 'none';

        if (type === 'edit') {
            const m = matchesData.find(x => x.id == id);
            if (m) {
                document.getElementById('m_title').value = m.title || '';
                document.getElementById('m_badge_text').value = m.badge_text || 'SOLO';
                document.getElementById('m_match_category').value = m.match_category || '1vs1';
                document.getElementById('m_prize_amount').value = m.prize_amount || '';
                document.getElementById('m_entry_fee').value = m.entry_fee || '';
                document.getElementById('m_time_label').value = m.time_label || '';
                document.getElementById('m_time_value').value = m.time_value || '';
                document.getElementById('m_button_text').value = m.button_text || 'Join';
                document.getElementById('m_icon_type').value = m.icon_type || 'TROPHY';
                document.getElementById('m_theme_start_color').value = m.theme_start_color || '#AF52DE';
                document.getElementById('m_theme_end_color').value = m.theme_end_color || '#5E5CE6';
                document.getElementById('m_tab_category').value = m.tab_category || 'upcoming';
                
                document.getElementById('m_total_joined').value = m.total_joined || 0;

                document.getElementById('m_player_1').value = m.player_1 || '';
                document.getElementById('m_player_2').value = m.player_2 || '';
                document.getElementById('m_player_3').value = m.player_3 || '';
                document.getElementById('m_player_4').value = m.player_4 || '';
                
                // Update specific visibility based on category
                handleCategoryChange();
            }
        } else {
            handleCategoryChange(); 
        }
    }

    function hideForm() {
        document.getElementById('formView').style.display = 'none';
        document.getElementById('listView').style.display = 'block';
    }

    function switchTab(tab, btn) {
        currentTab = tab;
        document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
        btn.classList.add('active');
        loadMatches();
    }

    function loadMatches() {
        const grid = document.getElementById('matchGrid');
        grid.innerHTML = 'Loading...';
        fetch(`?api=fetch&tab=${currentTab}&t=${Date.now()}`)
            .then(r => r.json())
            .then(res => {
                if (res.status === 'success') {
                    matchesData = res.data;
                    grid.innerHTML = matchesData.length ? matchesData.map(m => `
                        <div class="card">
                            <div class="card-header">
                                <strong>${m.title}</strong>
                                <span class="badge">${m.badge_text}</span>
                            </div>
                            <div class="info-grid">
                                <div class="info-box"><small>Prize</small>${m.prize_amount}</div>
                                <div class="info-box"><small>Entry</small>${m.entry_fee}</div>
                                <div class="info-box"><small>Type / Players</small>${m.match_category} (${m.total_joined}/${m.total_join})</div>
                                <div class="info-box"><small>${m.time_label}</small>${m.time_value.replace('T', ' ')}</div>
                            </div>
                            <div class="actions">
                                ${canEdit ? `<button class="btn btn-secondary" style="padding:6px 12px; font-size:13px;" onclick="showForm('edit', ${m.id})">Edit</button>` : ''}
                                ${canDelete ? `<button class="btn btn-danger" style="padding:6px 12px; font-size:13px;" onclick="deleteMatch(${m.id})">Delete</button>` : ''}
                            </div>
                        </div>
                    `).join('') : '<div style="color:var(--slate-500);">No matches found.</div>';
                }
            });
    }

    function saveMatch(e) {
        e.preventDefault();
        const btn = document.getElementById('saveBtn');
        btn.disabled = true; btn.textContent = 'Saving...';
        
        fetch('?api=process', { method: 'POST', body: new FormData(e.target) })
        .then(r => r.json())
        .then(res => {
            btn.disabled = false; btn.textContent = 'Save Match';
            if (res.status === 'success') {
                showToast(res.message, 'success');
                hideForm();
                loadMatches();
            } else showToast(res.message, 'error');
        }).catch(() => { btn.disabled = false; btn.textContent = 'Save Match'; });
    }

    function deleteMatch(id) {
        if (!confirm('Delete this match?')) return;
        const fd = new FormData(); fd.append('id', id); fd.append('type', 'delete');
        fetch('?api=process', { method: 'POST', body: fd })
        .then(r => r.json())
        .then(res => {
            if (res.status === 'success') { showToast(res.message); loadMatches(); }
            else showToast(res.message, 'error');
        });
    }

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