<?php
session_start();

if (!isset($_SESSION['admin_logged_in']) || !isset($_SESSION['admin_user']) || !isset($_SESSION['admin_pass'])) {
    header("Location: admin_login.php");
    exit;
}

$config_paths = ['Config.php', 'config.php', '../Config.php', '../config.php'];
$config_loaded = false;
foreach ($config_paths as $path) {
    if (file_exists($path)) {
        require_once $path;
        $config_loaded = true;
        break;
    }
}
if (!$config_loaded) die("Config file missing!");
if (!isset($conn) && isset($con)) $conn = $con;

$admin_user = $_SESSION['admin_user'];
$admin_pass = $_SESSION['admin_pass'];
$row = null;

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

$can_match_editing = strtolower(trim((string)($row['match_editing'] ?? 'no'))) === 'yes';

if (!$can_match_editing) {
    die('<!DOCTYPE html><html lang="bn"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>অ্যাক্সেস বাতিল</title></head><body style="margin:0;display:flex;flex-direction:column;align-items:center;justify-content:center;height:100vh;background:#f4f6f9;font-family:sans-serif;"><h2 style="color:#ff3b30;margin:20px 0 10px;">অ্যাক্সেস বাতিল!</h2><p style="color:#71717a;margin-bottom:20px;">আপনার এই পেজটি ব্যবহারের পারমিশন নেই।</p></body></html>');
}

$extra_json_str = $row['extra_json'] ?? '{}';
$extra_perms = json_decode($extra_json_str, true);
if (!is_array($extra_perms)) $extra_perms = [];

$allowed_categories = [];
foreach ($extra_perms as $category_name => $perms) {
    $add = (isset($perms['Add']) && $perms['Add'] === 'Yes');
    $edit = (isset($perms['Edit']) && $perms['Edit'] === 'Yes');
    $delete = (isset($perms['Delete']) && $perms['Delete'] === 'Yes');

    if ($add || $edit || $delete) {
        $allowed_categories[$category_name] = [
            'Add' => $add ? 'Yes' : 'No',
            'Edit' => $edit ? 'Yes' : 'No',
            'Delete' => $delete ? 'Yes' : 'No'
        ];
    }
}
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Match Rules Setup</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">

    <style>
        * { font-family: 'Inter', sans-serif; box-sizing: border-box; }
        body {
            background: linear-gradient(45deg, #a18cd1 0%, #fbc2eb 100%);
            background-attachment: fixed;
            min-height: 100vh;
            padding: 4vh 2vw;
            color: #1e293b;
            font-size: 14px;
        }
        .os-window {
            max-width: 900px;
            margin: 0 auto;
            background: rgba(255,255,255,0.95);
            backdrop-filter: blur(20px);
            border-radius: 16px;
            overflow: hidden;
            box-shadow: 0 25px 50px -12px rgba(0,0,0,0.25);
        }
        .window-header {
            background: rgba(255,255,255,0.6);
            padding: 12px 20px;
            border-bottom: 1px solid rgba(0,0,0,0.1);
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        .traffic-lights { display: flex; gap: 8px; }
        .dot { width: 12px; height: 12px; border-radius: 50%; }
        .red { background: #ff5f56; }
        .yellow { background: #ffbd2e; }
        .green { background: #27c93f; }
        .window-content { padding: 30px; }
        .login-box { max-width: 320px; margin: 50px auto; text-align: center; }
        .login-box input {
            width: 100%;
            padding: 12px;
            margin-bottom: 15px;
            border-radius: 8px;
            border: 1px solid #cbd5e1;
            outline: none;
        }
        .login-box button {
            width: 100%;
            background: #8b5cf6;
            color: white;
            border: none;
            padding: 12px;
            border-radius: 8px;
            font-weight: 600;
        }
        .form-label { font-weight: 600; color: #475569; margin-bottom: 8px; display: block; }
        .custom-select, .custom-textarea {
            width: 100%;
            border-radius: 10px;
            border: 1px solid #cbd5e1;
            font-size: 14px;
            outline: none;
        }
        .custom-select {
            padding: 12px;
            background: white;
            margin-bottom: 20px;
        }
        .custom-textarea {
            padding: 15px;
            background: #f8fafc;
            min-height: 250px;
            resize: vertical;
            line-height: 1.6;
        }
        .custom-textarea:focus {
            border-color: #8b5cf6;
            background: white;
            box-shadow: 0 0 0 3px rgba(139,92,246,0.1);
        }
        .btn-action {
            background: #8b5cf6;
            color: white;
            border: none;
            padding: 12px 25px;
            border-radius: 8px;
            font-weight: 600;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }
        .btn-action:hover { background: #7c3aed; }
        @media (max-width: 768px) {
            body { padding: 0; }
            .os-window { border-radius: 0; min-height: 100vh; }
            .window-content { padding: 20px; }
        }
    </style>
</head>
<body>

<div class="toast-container position-fixed bottom-0 end-0 p-3" style="z-index:9999;">
    <div id="liveToast" class="toast border-0 shadow-sm" role="alert">
        <div class="toast-body fw-bold rounded" id="toastMessage" style="font-size:14px; background:white;"></div>
    </div>
</div>

<div class="os-window">
    <div class="window-header">
        <div class="traffic-lights">
            <div class="dot red"></div>
            <div class="dot yellow"></div>
            <div class="dot green"></div>
        </div>
        <div class="window-title">Match Rules Setup Dashboard</div>
        <a href="?logout=1" class="text-danger fw-bold text-decoration-none"><i class="fas fa-power-off"></i></a>
    </div>

    <div class="window-content">
        <label class="form-label">Select Match Category</label>
        <select id="categorySelect" class="custom-select">
            <option value="">-- Loading Categories... --</option>
        </select>

        <div id="rulesArea" style="display:none;">
            <label class="form-label mt-2">Rules</label>
            <textarea id="rulesInput" class="custom-textarea" placeholder="Write rules here..."></textarea>

            <div class="mt-4 text-end">
                <button id="saveBtn" class="btn-action">
                    <i class="fas fa-save"></i> <span>Save Rules</span>
                </button>
            </div>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>

<script>
const API_URL = 'match_rules_api.php';

function showToast(message, type = 'success') {
    const toastEl = $('#liveToast');
    const body = $('#toastMessage');
    if (type === 'success') body.html(`✅ ${message}`).css('color', '#15803d');
    else body.html(`❌ ${message}`).css('color', '#b91c1c');
    new bootstrap.Toast(toastEl, { delay: 3000 }).show();
}

function loadCategories() {
    $.post(API_URL, { action: 'get_categories' }, function(res) {
        if (res.status === 'success') {
            let html = '<option value="">-- Select a Category --</option>';
            if (res.data && res.data.length) {
                res.data.forEach(function(item) {
                    html += `<option value="${item.id}">${item.match_type}</option>`;
                });
            } else {
                html = '<option value="">-- No accessible category found --</option>';
            }
            $('#categorySelect').html(html);
        } else {
            $('#categorySelect').html('<option value="">-- Failed to load --</option>');
            showToast(res.message, 'error');
        }
    }, 'json').fail(function() {
        $('#categorySelect').html('<option value="">-- Failed to load --</option>');
        showToast('Server API Error!', 'error');
    });
}

$(function() {
    loadCategories();

    $('#categorySelect').on('change', function() {
        const categoryId = $(this).val();

        if (!categoryId) {
            $('#rulesArea').hide();
            $('#rulesInput').val('');
            return;
        }

        $('#rulesArea').show();
        $('#rulesInput').val('Loading...');

        $.post(API_URL, {
            action: 'get_rule',
            category_id: categoryId
        }, function(res) {
            if (res.status === 'success') {
                $('#rulesInput').val(res.data.rules || '');
                $('#saveBtn').html(
                    res.data.exists
                    ? '<i class="fas fa-edit"></i> <span>Update Rules</span>'
                    : '<i class="fas fa-plus-circle"></i> <span>Add Rules</span>'
                );
            } else {
                $('#rulesInput').val('');
                showToast(res.message, 'error');
            }
        }, 'json').fail(function(xhr) {
            $('#rulesInput').val('');
            if (xhr.status === 403) showToast('Permission denied.', 'error');
            else showToast('Failed to load rule.', 'error');
        });
    });

    $('#saveBtn').on('click', function() {
        const categoryId = $('#categorySelect').val();
        const rules = $('#rulesInput').val();

        if (!categoryId) {
            showToast('Please select a category.', 'error');
            return;
        }

        if (!rules.trim()) {
            showToast('Rules cannot be empty.', 'error');
            return;
        }

        const btn = $(this);
        const old = btn.html();

        btn.html('<i class="fas fa-spinner fa-spin"></i> Saving...').prop('disabled', true);

        $.post(API_URL, {
            action: 'save_rule',
            category_id: categoryId,
            rules: rules
        }, function(res) {
            btn.html(old).prop('disabled', false);

            if (res.status === 'success') {
                showToast(res.message, 'success');
                btn.html('<i class="fas fa-edit"></i> <span>Update Rules</span>');
            } else {
                showToast(res.message, 'error');
            }
        }, 'json').fail(function(xhr) {
            btn.html(old).prop('disabled', false);
            if (xhr.status === 403) showToast('Permission denied.', 'error');
            else showToast('Save failed.', 'error');
        });
    });
});
</script>
</body>
</html>