<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Moderator Permissions</title>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <style>
        :root {
            --bg: #f3f6fc;
            --surface: #ffffff;
            --text-primary: #0f172a;
            --text-muted: #64748b;
            --primary: linear-gradient(135deg, #4f46e5 0%, #3b82f6 100%);
            --primary-solid: #4f46e5;
            --card-border: #e8eef6;
            --radius-lg: 20px;
            --radius-md: 12px;
            --radius-sm: 8px;
            --transition: all 0.25s ease;
            --success: #10b981;
        }
        * { box-sizing: border-box; outline: none; margin: 0; padding: 0; }
        body { font-family: 'Plus Jakarta Sans', sans-serif; background-color: var(--bg); color: var(--text-primary); padding: 40px 20px; }
        .wrapper { max-width: 900px; margin: 0 auto; background: var(--surface); padding: 40px; border-radius: var(--radius-lg); border: 1px solid var(--card-border); box-shadow: 0 10px 30px rgba(0,0,0,0.03); }
        .header-flex { display: flex; justify-content: space-between; align-items: center; margin-bottom: 25px; flex-wrap: wrap; gap: 10px; }
        h2 { font-weight: 800; font-size: 24px; letter-spacing: -0.5px; display: flex; align-items: center; gap: 10px; margin: 0; }
        .back-btn { background: rgba(79, 70, 229, 0.1); color: var(--primary-solid); padding: 8px 16px; border-radius: var(--radius-sm); font-size: 14px; font-weight: 700; text-decoration: none; transition: var(--transition); }
        .back-btn:hover { background: var(--primary-solid); color: #fff; }
        .section-title { font-size: 14px; font-weight: 800; text-transform: uppercase; letter-spacing: 0.5px; color: var(--text-muted); margin: 30px 0 15px; border-bottom: 1px solid var(--card-border); padding-bottom: 8px; }
        .grid-inputs { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin-bottom: 20px; }
        .input-group { display: flex; flex-direction: column; gap: 8px; }
        .input-group label { font-size: 13px; font-weight: 700; color: var(--text-primary); }
        .input-group input { padding: 12px 16px; border: 1px solid var(--card-border); border-radius: var(--radius-sm); font-family: inherit; font-size: 14px; background: #f8fafc; transition: var(--transition); }
        .input-group input:focus { border-color: var(--primary-solid); background: #fff; box-shadow: 0 0 0 4px rgba(79, 70, 229, 0.1); }
        .permissions-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 12px; }
        .perm-card { display: flex; align-items: center; justify-content: space-between; padding: 14px 16px; background: #f8fafc; border: 1px solid var(--card-border); border-radius: var(--radius-md); transition: var(--transition); }
        .perm-card.cat-card { flex-direction: column; align-items: flex-start; gap: 12px; background: #fff; border-left: 4px solid var(--primary-solid); }
        .perm-card:hover { background: #f1f5f9; }
        .perm-name { font-size: 14px; font-weight: 700; text-transform: capitalize; }
        .switch { position: relative; display: inline-block; width: 44px; height: 24px; }
        .switch input { opacity: 0; width: 0; height: 0; }
        .slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #cbd5e1; transition: .3s; border-radius: 24px; }
        .slider:before { position: absolute; content: ""; height: 18px; width: 18px; left: 3px; bottom: 3px; background-color: white; transition: .3s; border-radius: 50%; }
        input:checked + .slider { background: var(--primary); }
        input:checked + .slider:before { transform: translateX(20px); }
        .btn-submit { width: 100%; padding: 16px; background: var(--primary); color: white; border: none; border-radius: var(--radius-md); font-size: 16px; font-weight: 700; cursor: pointer; margin-top: 40px; transition: var(--transition); box-shadow: 0 4px 12px rgba(79, 70, 229, 0.2); }
        .btn-submit:hover { transform: translateY(-2px); box-shadow: 0 6px 20px rgba(79, 70, 229, 0.3); }
        #message-box { padding: 16px; border-radius: var(--radius-md); margin-bottom: 20px; font-size: 14px; font-weight: 600; display: none; }
        .msg-success { background: rgba(16, 185, 129, 0.1); color: var(--success); border: 1px solid rgba(16, 185, 129, 0.2); }
        .msg-error { background: rgba(239, 68, 68, 0.1); color: #ef4444; border: 1px solid rgba(239, 68, 68, 0.2); }
        .cat-actions { display: flex; justify-content: space-between; width: 100%; background: #f8fafc; padding: 10px; border-radius: 8px; border: 1px solid #e2e8f0; }
        .action-toggle { display: flex; flex-direction: column; align-items: center; gap: 6px; }
        .action-toggle span { font-size: 11px; font-weight: 800; color: var(--text-muted); text-transform: uppercase; }
    </style>
</head>
<body>

<div class="wrapper">
    <div class="header-flex">
        <h2><i class="fa-solid fa-user-gear" style="color: var(--primary-solid);"></i> Moderator Permissions</h2>
        <a href="index.php" class="back-btn"><i class="fa-solid fa-arrow-left"></i> Dashboard</a>
    </div>
    
    <div id="message-box"></div>

    <form id="modForm" autocomplete="off">
        <div class="section-title">Admin Authentication</div>
        <div class="grid-inputs">
            <div class="input-group">
                <label>Admin Username</label>
                <input type="text" id="admin_user" name="admin_username" required autocomplete="off">
            </div>
            <div class="input-group">
                <label>Admin Password</label>
                <input type="password" id="admin_pass" name="admin_password" required autocomplete="new-password">
            </div>
        </div>

        <div class="section-title">Moderator Info</div>
        <div class="grid-inputs">
            <div class="input-group">
                <label>Moderator Username</label>
                <input type="text" id="mod_user" name="mod_username" required autocomplete="off">
            </div>
            <div class="input-group">
                <label>Moderator Password</label>
                <input type="password" id="mod_pass" name="mod_password" required autocomplete="new-password">
            </div>
        </div>

        <div class="section-title">Core Module Permissions</div>
        <div class="permissions-grid">
            <div class="perm-card"><div class="perm-info"><span class="perm-name">Users Control</span></div><label class="switch"><input type="checkbox" name="users_control" value="Yes"><span class="slider"></span></label></div>
            <div class="perm-card"><div class="perm-info"><span class="perm-name">Money History</span></div><label class="switch"><input type="checkbox" name="money_history" value="Yes"><span class="slider"></span></label></div>
            <div class="perm-card"><div class="perm-info"><span class="perm-name">Database Editing</span></div><label class="switch"><input type="checkbox" name="database_editing" value="Yes"><span class="slider"></span></label></div>
            <div class="perm-card"><div class="perm-info"><span class="perm-name">Notifications</span></div><label class="switch"><input type="checkbox" name="notifications" value="Yes"><span class="slider"></span></label></div>
            <div class="perm-card"><div class="perm-info"><span class="perm-name">Match Rules</span></div><label class="switch"><input type="checkbox" name="match_rules" value="Yes"><span class="slider"></span></label></div>
            <div class="perm-card"><div class="perm-info"><span class="perm-name">Add Winnings</span></div><label class="switch"><input type="checkbox" name="add_winnings" value="Yes"><span class="slider"></span></label></div>
            <div class="perm-card"><div class="perm-info"><span class="perm-name">Refund System</span></div><label class="switch"><input type="checkbox" name="refund" value="Yes"><span class="slider"></span></label></div>
            <div class="perm-card"><div class="perm-info"><span class="perm-name">Match Delete</span></div><label class="switch"><input type="checkbox" name="match_delete" value="Yes"><span class="slider"></span></label></div>
            <div class="perm-card"><div class="perm-info"><span class="perm-name">Match Editing</span></div><label class="switch"><input type="checkbox" name="match_editing" value="Yes"><span class="slider"></span></label></div>
            <div class="perm-card"><div class="perm-info"><span class="perm-name">Match Ongoing Results</span></div><label class="switch"><input type="checkbox" name="match_ongoing_results" value="Yes"><span class="slider"></span></label></div>
        </div>

        <div class="section-title">Match Category Permissions (Dynamic From DB)</div>
        <div class="permissions-grid" id="match-category-container">
            <p style="font-size:13px; color:var(--text-muted); grid-column: 1/-1;">Please enter Admin details above to load Match Categories.</p>
        </div>

        <div class="section-title">Extra Features Permissions (Saved in JSON)</div>
        <div class="permissions-grid">
            <div class="perm-card"><div class="perm-info"><span class="perm-name">Match Category Permissions</span></div><label class="switch"><input type="checkbox" name="extra_perms[match_category_permissions]" value="Yes"><span class="slider"></span></label></div>
            <div class="perm-card"><div class="perm-info"><span class="perm-name">Bonus Management</span></div><label class="switch"><input type="checkbox" name="extra_perms[bonus_management]" value="Yes"><span class="slider"></span></label></div>
            <div class="perm-card"><div class="perm-info"><span class="perm-name">Withdrawals</span></div><label class="switch"><input type="checkbox" name="extra_perms[withdrawals]" value="Yes"><span class="slider"></span></label></div>
            <div class="perm-card"><div class="perm-info"><span class="perm-name">Order Fulfillment</span></div><label class="switch"><input type="checkbox" name="extra_perms[order_fulfillment]" value="Yes"><span class="slider"></span></label></div>
            <div class="perm-card"><div class="perm-info"><span class="perm-name">Policy & Rules</span></div><label class="switch"><input type="checkbox" name="extra_perms[policy_rules]" value="Yes"><span class="slider"></span></label></div>
        </div>

        <button type="submit" id="submit-btn" class="btn-submit">Save Moderator Permissions</button>
    </form>
</div>

<script>
    const adminUserField = document.getElementById('admin_user');
    const adminPassField = document.getElementById('admin_pass');
    const modUserField = document.getElementById('mod_user');
    const modPassField = document.getElementById('mod_pass');
    const msgBox = document.getElementById('message-box');
    const container = document.getElementById('match-category-container');
    const submitBtn = document.getElementById('submit-btn');

    function showMessage(text, isSuccess) {
        msgBox.style.display = 'block';
        msgBox.className = isSuccess ? 'msg-success' : 'msg-error';
        msgBox.innerText = text;
        window.scrollTo({ top: 0, behavior: 'smooth' });
    }

    async function loadDynamicCategories() {
        const adminUser = adminUserField.value.trim();
        const adminPass = adminPassField.value.trim();
        if(!adminUser || !adminPass) return;

        const fd = new FormData();
        fd.append('admin_username', adminUser);
        fd.append('admin_password', adminPass);
        fd.append('action', 'get_categories');

        try {
            const response = await fetch('api_moderators.php', { method: 'POST', body: fd });
            if (response.ok) {
                const data = await response.json();
                if (data.status === 'success') {
                    container.innerHTML = '';
                    if(data.categories.length === 0) {
                        container.innerHTML = '<p style="font-size:13px;color:var(--text-muted);">No categories found in table</p>';
                        return;
                    }
                    data.categories.forEach(cat => {
                        const safeCat = cat.replace(/"/g, '&quot;');
                        const displayCat = cat.replace(/_/g, ' ');
                        
                        const div = document.createElement('div');
                        div.className = 'perm-card cat-card';
                        div.innerHTML = `
                            <div class="perm-name" style="width: 100%; font-weight:800; color:var(--text-primary);"><i class="fa-solid fa-gamepad" style="margin-right:5px; color:var(--primary-solid);"></i> ${displayCat}</div>
                            <div class="cat-actions">
                                <div class="action-toggle">
                                    <span>Add</span>
                                    <label class="switch">
                                        <input type="hidden" name="dynamic_permissions[${safeCat}][Add]" value="No">
                                        <input type="checkbox" name="dynamic_permissions[${safeCat}][Add]" value="Yes">
                                        <span class="slider"></span>
                                    </label>
                                </div>
                                <div class="action-toggle">
                                    <span>Edit</span>
                                    <label class="switch">
                                        <input type="hidden" name="dynamic_permissions[${safeCat}][Edit]" value="No">
                                        <input type="checkbox" name="dynamic_permissions[${safeCat}][Edit]" value="Yes">
                                        <span class="slider"></span>
                                    </label>
                                </div>
                                <div class="action-toggle">
                                    <span>Delete</span>
                                    <label class="switch">
                                        <input type="hidden" name="dynamic_permissions[${safeCat}][Delete]" value="No">
                                        <input type="checkbox" name="dynamic_permissions[${safeCat}][Delete]" value="Yes">
                                        <span class="slider"></span>
                                    </label>
                                </div>
                            </div>
                        `;
                        container.appendChild(div);
                    });
                    
                    checkAndPopulateModerator();
                } else {
                    container.innerHTML = `<p style="font-size:13px;color:#ef4444;">${data.message || 'Admin validation failed.'}</p>`;
                }
            }
        } catch (e) {
            container.innerHTML = '<p style="font-size:13px;color:#ef4444;">Error connection failed.</p>';
        }
    }

    async function checkAndPopulateModerator() {
        const adminUser = adminUserField.value.trim();
        const adminPass = adminPassField.value.trim();
        const modUser = modUserField.value.trim();
        const modPass = modPassField.value.trim();

        if(!adminUser || !adminPass || !modUser || !modPass) {
            resetPermissionsOnly();
            submitBtn.innerText = "Save Moderator Permissions";
            return;
        }

        const fd = new FormData();
        fd.append('admin_username', adminUser);
        fd.append('admin_password', adminPass);
        fd.append('mod_username', modUser);
        fd.append('action', 'get_moderator');

        try {
            const response = await fetch('api_moderators.php', { method: 'POST', body: fd });
            if(response.ok) {
                const resData = await response.json();
                resetPermissionsOnly();

                if(resData.status === 'success' && resData.exists) {
                    const mod = resData.data;
                    
                    const coreCols = ['users_control', 'money_history', 'database_editing', 'notifications', 'match_rules', 'add_winnings', 'refund', 'match_delete', 'match_editing', 'match_ongoing_results'];
                    coreCols.forEach(col => {
                        const cb = document.querySelector(`input[type="checkbox"][name="${col}"]`);
                        if(cb) cb.checked = (mod[col] === 'Yes');
                    });

                    if(mod.extra_json) {
                        try {
                            const extra = JSON.parse(mod.extra_json);
                            for(const key in extra) {
                                if (typeof extra[key] === 'object') {
                                    for(const act in extra[key]) {
                                        const safeCat = key.replace(/"/g, '\\"');
                                        const cb = document.querySelector(`input[type="checkbox"][name="dynamic_permissions[${safeCat}][${act}]"]`);
                                        if(cb) cb.checked = (extra[key][act] === 'Yes');
                                    }
                                } else if (typeof extra[key] === 'string') {
                                    const cb = document.querySelector(`input[type="checkbox"][name="extra_perms[${key}]"]`);
                                    if(cb) cb.checked = (extra[key] === 'Yes');
                                }
                            }
                        } catch(jsonErr){}
                    }

                    submitBtn.innerText = "Update Moderator Permissions";
                } else {
                    submitBtn.innerText = "Save Moderator Permissions";
                }
            }
        } catch(e){}
    }

    function resetPermissionsOnly() {
        document.querySelectorAll('#modForm input[type="checkbox"]').forEach(cb => cb.checked = false);
    }

    adminUserField.addEventListener('input', loadDynamicCategories);
    adminPassField.addEventListener('input', loadDynamicCategories);
    modUserField.addEventListener('input', checkAndPopulateModerator);
    modPassField.addEventListener('input', checkAndPopulateModerator);

    document.getElementById('modForm').addEventListener('submit', async function(e) {
        e.preventDefault();
        
        document.getElementById('admin_user').value = document.getElementById('admin_user').value.trim();
        document.getElementById('admin_pass').value = document.getElementById('admin_pass').value.trim();
        document.getElementById('mod_user').value = document.getElementById('mod_user').value.trim();
        
        const formData = new FormData(this);
        formData.append('action', 'save_moderator');

        try {
            const response = await fetch('api_moderators.php', { method: 'POST', body: formData });
            const data = await response.json();
            if (data.status === 'success') {
                showMessage(data.message, true);
                this.reset();
                container.innerHTML = '<p style="font-size:13px; color:var(--text-muted); grid-column: 1/-1;">Please enter Admin details above to load Match Categories.</p>';
                submitBtn.innerText = "Save Moderator Permissions";
            } else {
                showMessage(data.message, false);
            }
        } catch (error) {
            showMessage("An error occurred process failed", false);
        }
    });
</script>

</body>
</html>
