<?php
require_once "config.php";
require_once "header.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("Database connection not available.");
}
$conn->set_charset("utf8mb4");

$permissionTable = "Zabbar_Admin_Permission";
$adminTable = "admin";

$permissionFields = [
    'members_read' => 'MEMBERS Read', 'members_edit' => 'MEMBERS Edit', 'members_delete' => 'MEMBERS Delete',
    'addmoney_history_read' => 'AddMoney History Read', 'addmoney_history_edit' => 'AddMoney History Edit', 'addmoney_history_delete' => 'AddMoney History Delete',
    'withdrawal_history_read' => 'Withdrawal History Read', 'withdrawal_history_edit' => 'Withdrawal History Edit', 'withdrawal_history_delete' => 'Withdrawal History Delete',
    'refund_history_read' => 'Refund History Read', 'refund_history_delete' => 'Refund History Delete',
    'notification_send' => 'NOTIFICATION Send', 
    'app_settings_read' => 'APP SETTINGS Read', 'app_settings_edit' => 'APP SETTINGS Edit',
    'slider_read' => 'Slider Read', 'slider_edit' => 'Slider Edit', 'slider_delete' => 'Slider Delete',
    'matches_rules_read' => 'MATCHES RULES Read', 'matches_rules_edit' => 'MATCHES RULES Edit',
    'deposit_bonus_read' => 'Deposit Bonus Read', 'deposit_bonus_edit' => 'Deposit Bonus Edit', 'deposit_bonus_delete' => 'Deposit Bonus Delete',
    'dialog_slider_read' => 'Dialog Slider Read', 'dialog_slider_edit' => 'Dialog Slider Edit', 'dialog_slider_delete' => 'Dialog Slider Delete',
    'refund_send' => 'Refund Send', 
    'category_add' => 'Category Add', 'category_edit' => 'Category Edit', 'category_delete' => 'Category Delete',
    'Shop_TopUP_Read' => 'Shop TopUP Read', 'Shop_TopUP_Edit' => 'Shop TopUP Edit', 'Shop_TopUP_Delete' => 'Shop TopUP Delete',
    'Shop_Product_Read' => 'Shop Product Read', 'Shop_Product_Edit' => 'Shop Product Edit', 'Shop_Product_Delete' => 'Shop Product Delete',
    'Geft_Read' => 'Gift Read', 'Geft_Edit' => 'Gift Edit', 'Geft_Delete' => 'Gift Delete'
];

$groups = [
    'MEMBERS' => ['members_read', 'members_edit', 'members_delete'],
    'AddMoney History' => ['addmoney_history_read', 'addmoney_history_edit', 'addmoney_history_delete'],
    'Withdrawal History' => ['withdrawal_history_read', 'withdrawal_history_edit', 'withdrawal_history_delete'],
    'Refund History & Actions' => ['refund_history_read', 'refund_history_delete', 'refund_send'],
    'Shop & TopUP' => ['Shop_TopUP_Read', 'Shop_TopUP_Edit', 'Shop_TopUP_Delete', 'Shop_Product_Read', 'Shop_Product_Edit', 'Shop_Product_Delete'],
    'Gift / Geft' => ['Geft_Read', 'Geft_Edit', 'Geft_Delete'],
    'NOTIFICATION & APP SETTINGS' => ['notification_send', 'app_settings_read', 'app_settings_edit'],
    'Slider & Dialog Slider' => ['slider_read', 'slider_edit', 'slider_delete', 'dialog_slider_read', 'dialog_slider_edit', 'dialog_slider_delete'],
    'MATCHES RULES & Deposit Bonus' => ['matches_rules_read', 'matches_rules_edit', 'deposit_bonus_read', 'deposit_bonus_edit', 'deposit_bonus_delete'],
    'Category' => ['category_add', 'category_edit', 'category_delete']
];

$categories = [];
$catRes = $conn->query("SELECT id, title FROM category ORDER BY id ASC");
if ($catRes) {
    while ($c = $catRes->fetch_assoc()) $categories[] = $c;
}

function e($value): string { return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8'); }

function bind_dynamic(mysqli_stmt $stmt, string $types, array &$params): void {
    $refs = [$types];
    foreach ($params as $k => $v) $refs[] = &$params[$k];
    call_user_func_array([$stmt, 'bind_param'], $refs);
}

function empty_form(array $permissionFields, array $categories): array {
    $form = ['username' => $_GET['username'] ?? '', 'password' => $_GET['password'] ?? ''];
    foreach ($permissionFields as $key => $label) $form[$key] = 'No';
    $form['match_data'] = [];
    foreach ($categories as $cat) {
        $form['match_data'][$cat['id']] = ['add_match' => 'No', 'add_rules' => 'No', 'edit_match' => 'No', 'delete_match' => 'No'];
    }
    return $form;
}

function get_auth_row(mysqli $conn, string $table, string $username, string $password): ?array {
    $stmt = $conn->prepare("SELECT * FROM `$table` WHERE username = ? AND password = ? LIMIT 1");
    $stmt->bind_param("ss", $username, $password); 
    $stmt->execute();
    $res = $stmt->get_result(); 
    $row = $res->fetch_assoc() ?: null; 
    $stmt->close();
    return $row;
}

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;
}

function check_admin_auth(): bool {
    return session_alive(1200) && isset($_SESSION['auth_role']) && $_SESSION['auth_role'] === 'admin';
}

if (isset($_GET['action']) && $_GET['action'] === 'autofill') {
    header('Content-Type: application/json; charset=utf-8');
    if (!check_admin_auth()) { http_response_code(401); echo json_encode(['ok' => false, 'message' => 'Session expired']); exit; }
    $username = trim($_GET['username'] ?? ''); $password = trim($_GET['password'] ?? '');
    if ($username === '' || $password === '') { echo json_encode(['ok' => true, 'found' => false]); exit; }
    
    $row = get_auth_row($conn, $permissionTable, $username, $password);
    if (!$row) { echo json_encode(['ok' => true, 'found' => false, 'data' => empty_form($permissionFields, $categories)], JSON_UNESCAPED_UNICODE); exit; }
    
    $permissions = [];
    foreach ($permissionFields as $key => $label) $permissions[$key] = (($row[$key] ?? 'No') === 'Yes') ? 'Yes' : 'No';
    echo json_encode(['ok' => true, 'found' => true, 'data' => ['username' => $row['username'] ?? '', 'password' => $row['password'] ?? '', 'permissions' => $permissions, 'match_data' => json_decode($row['match_data'] ?? '{}', true) ?: []]], JSON_UNESCAPED_UNICODE); exit;
}

$error = $success = '';
$form = empty_form($permissionFields, $categories);

if (isset($_POST['do_login'])) {
    $loginUsername = trim($_POST['login_username'] ?? ''); 
    $loginPassword = trim($_POST['login_password'] ?? '');
    if ($loginUsername === '' || $loginPassword === '') {
        $error = "Username and password are required.";
    } else {
        $adminRow = get_auth_row($conn, $adminTable, $loginUsername, $loginPassword);
        if ($adminRow) {
            session_regenerate_id(true); 
            $_SESSION['auth_logged_in'] = true; 
            $_SESSION['auth_role'] = 'admin';
            $_SESSION['auth_username'] = $adminRow['username'];
            $_SESSION['auth_password'] = $adminRow['password'];
            $_SESSION['auth_source_table'] = $adminTable;
            $_SESSION['auth_last_activity'] = time();
            header("Location: " . $_SERVER['PHP_SELF'] . (!empty($_GET['username']) ? "?username=".urlencode($_GET['username'])."&password=".urlencode($_GET['password'] ?? '') : ""));
            exit;
        } else {
            $error = "Invalid username or password.";
        }
    }
}

$loggedIn = check_admin_auth();

if ($loggedIn && isset($_POST['save_permission'])) {
    $sessionAdmin = (string)($_SESSION['auth_username'] ?? '');
    $sessionAdminPass = (string)($_SESSION['auth_password'] ?? '');
    $username = trim($_POST['username'] ?? ''); 
    $password = trim($_POST['password'] ?? '');
    
    if ($sessionAdmin === '') { 
        $error = "Session invalid."; 
        $loggedIn = false; 
    } elseif ($username === '' || $password === '') { 
        $error = "Username and password are required."; 
    } else {
        if (!get_auth_row($conn, $adminTable, $sessionAdmin, $sessionAdminPass)) { 
            $error = "Admin access is invalid."; 
            $loggedIn = false; 
        } else {
            $values = [];
            foreach ($permissionFields as $key => $label) $values[$key] = (isset($_POST[$key]) && $_POST[$key] === 'Yes') ? 'Yes' : 'No';
            $match_data_input = $_POST['match_data'] ?? []; $clean_match_data = [];
            foreach ($categories as $cat) {
                $cid = $cat['id'];
                $clean_match_data[$cid] = ['add_match' => isset($match_data_input[$cid]['add_match']) ? 'Yes' : 'No', 'add_rules' => isset($match_data_input[$cid]['add_rules']) ? 'Yes' : 'No', 'edit_match' => isset($match_data_input[$cid]['edit_match']) ? 'Yes' : 'No', 'delete_match' => isset($match_data_input[$cid]['delete_match']) ? 'Yes' : 'No'];
            }
            $match_data_json = json_encode($clean_match_data);
            $existing = get_auth_row($conn, $permissionTable, $username, $password);
            $params = []; foreach (array_keys($permissionFields) as $kf) $params[] = $values[$kf]; $params[] = $match_data_json;
            
            if ($existing) {
                $setParts = []; foreach (array_keys($permissionFields) as $kf) $setParts[] = "`$kf` = ?"; $setParts[] = "`match_data` = ?";
                $stmt = $conn->prepare("UPDATE `$permissionTable` SET " . implode(", ", $setParts) . " WHERE username = ? AND password = ?");
                $params[] = $username; $params[] = $password; $types = str_repeat('s', count($params));
                bind_dynamic($stmt, $types, $params); $stmt->execute(); $stmt->close();
                $success = "Permission updated successfully.";
            } else {
                $colNames = array_keys($permissionFields); array_push($colNames, 'match_data', 'username', 'password');
                $stmt = $conn->prepare("INSERT INTO `$permissionTable` (" . implode(", ", array_map(fn($c) => "`$c`", $colNames)) . ") VALUES (" . str_repeat('?,', count($colNames) - 1) . "?)");
                $params[] = $username; $params[] = $password; $types = str_repeat('s', count($params));
                bind_dynamic($stmt, $types, $params); $stmt->execute(); $stmt->close();
                $success = "Permission saved successfully.";
            }
            $form['username'] = $username; $form['password'] = $password;
            foreach ($permissionFields as $key => $label) $form[$key] = $values[$key];
            $form['match_data'] = $clean_match_data;
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Permission</title>
    <style>
        :root{ --bg:#f4f7fb; --card:#ffffff; --text:#122033; --muted:#64748b; --line:#dbe5f0; --accent:#2563eb; --accent2:#16a34a; --shadow:0 18px 50px rgba(18,32,51,.08); --radius:22px; }
        *{box-sizing:border-box}
        body{ margin:0; font-family:system-ui,-apple-system,sans-serif; background:radial-gradient(circle at top left, rgba(37,99,235,.10), transparent 28%), radial-gradient(circle at top right, rgba(22,163,74,.08), transparent 24%), var(--bg); color:var(--text); min-height:100vh; }
        .wrap{ width:min(1180px, calc(100% - 20px)); margin:0 auto; padding:18px 0 30px; }
        .topbar{ display:flex; align-items:center; justify-content:space-between; gap:12px; padding:18px 20px; background:rgba(255,255,255,.92); border:1px solid var(--line); border-radius:var(--radius); box-shadow:var(--shadow); position:sticky; top:12px; z-index:10; backdrop-filter: blur(12px); }
        .brand{display:flex;align-items:center;gap:12px;}
        .logo{ width:46px; height:46px; border-radius:16px; display:grid; place-items:center; background:linear-gradient(135deg, var(--accent), #7c3aed); color:white; font-weight:800; box-shadow:0 10px 24px rgba(37,99,235,.20); }
        .titlebox h1{margin:0;font-size:20px;}
        .titlebox p{margin:4px 0 0;color:var(--muted);font-size:13px;}
        .badge{ display:inline-flex; align-items:center; gap:8px; padding:10px 14px; border-radius:999px; background:#eff6ff; border:1px solid #dbeafe; color:var(--text); font-size:13px; }
        .panel{ background:rgba(255,255,255,.96); border:1px solid var(--line); border-radius:var(--radius); box-shadow:var(--shadow); margin-top:16px; backdrop-filter: blur(12px); }
        .panel-head{ padding:18px 20px; border-bottom:1px solid var(--line); display:flex; justify-content:space-between; align-items:center; }
        .panel-head h2{margin:0;font-size:18px;}
        .sub{margin:4px 0 0;color:var(--muted);font-size:13px;}
        .panel-body{padding:20px;}
        .alert{ padding:14px 16px; border-radius:18px; margin-bottom:16px; font-size:14px; border:1px solid transparent; }
        .alert.error{ background:#fef2f2; border-color:#fecaca; color:#991b1b; }
        .alert.success{ background:#f0fdf4; border-color:#bbf7d0; color:#166534; }
        .form-grid{ display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:16px; }
        .field{display:flex;flex-direction:column;gap:8px;}
        .field.full{grid-column:1 / -1;}
        label{font-size:13px;color:#334155;font-weight:700;}
        input[type="text"], input[type="password"]{ width:100%; border:1px solid var(--line); border-radius:16px; padding:14px 15px; outline:none; font-size:15px; transition:.2s; }
        input:focus{ border-color:rgba(37,99,235,.65); box-shadow:0 0 0 4px rgba(37,99,235,.10); }
        .status-row{ display:flex; align-items:center; justify-content:space-between; margin-top:14px; padding:14px 16px; border:1px solid var(--line); border-radius:18px; background:#f8fbff; }
        .status-pill{ font-size:12px; color:#fff; padding:7px 10px; border-radius:999px; background:#94a3b8; min-width:70px; text-align:center; }
        .btns{ display:flex; gap:12px; margin-top:18px; }
        .btn{ border:none; cursor:pointer; padding:13px 18px; border-radius:16px; font-weight:800; color:#fff; font-size:14px; transition:.2s ease; text-decoration:none; display:inline-block; }
        .btn.primary{background:linear-gradient(135deg, var(--accent), #7c3aed);}
        .btn.primary:hover{transform:translateY(-1px);}
        .section{ margin-top:18px; border:1px solid var(--line); border-radius:22px; overflow:hidden; background:#f8fbff; }
        .section-head{ padding:14px 16px; border-bottom:1px solid var(--line); display:flex; align-items:center; justify-content:space-between; background:#f8fbff; }
        .section-head h3{margin:0;font-size:16px;}
        .section-head span{color:var(--muted);font-size:12px;}
        .perm-grid{ display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:12px; padding:16px; }
        .perm{ display:flex; align-items:center; justify-content:space-between; gap:14px; padding:14px; border-radius:18px; background:#fff; border:1px solid var(--line); box-shadow:0 8px 20px rgba(15,23,42,.03); }
        .perm .name{ font-weight:700; font-size:14px; }
        .perm .state{ font-size:12px; color:#fff; padding:7px 10px; border-radius:999px; background:#94a3b8; min-width:52px; text-align:center; }
        .switch{ position:relative; width:62px; height:34px; flex:0 0 auto; }
        .switch input{opacity:0;width:0;height:0;}
        .slider{ position:absolute; cursor:pointer; inset:0; background:#cbd5e1; transition:.2s; border-radius:999px; }
        .slider:before{ content:""; position:absolute; height:26px; width:26px; left:4px; top:3px; background:#fff; border-radius:50%; transition:.2s; box-shadow:0 8px 18px rgba(0,0,0,.12); }
        .switch input:checked + .slider{ background:linear-gradient(135deg, #22c55e, #16a34a); }
        .switch input:checked + .slider:before{ transform:translateX(28px); }
        .cat-box{ background:#fff; border:1px solid var(--line); border-radius:18px; padding:16px; margin-bottom:12px; }
        .cat-box h4{ margin:0 0 12px 0; font-size:15px; color:var(--accent); }
        .cat-grid{ display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:10px; }
        .allowed-badge{ background:#ecfdf5; color:#059669; border:1px solid #a7f3d0; padding:6px 12px; border-radius:999px; font-size:13px; font-weight:700; }
        @media (max-width: 880px){ .form-grid, .perm-grid, .cat-grid{grid-template-columns:1fr;} }
    </style>
</head>
<body>
<div class="wrap">
    <div class="topbar">
        <div class="brand">
            <div class="logo">A</div>
            <div class="titlebox">
                <h1>Admin Permission</h1>
                <p>Permission editor</p>
            </div>
        </div>
        <div class="badge">
            <?php if ($loggedIn): ?>
                Logged in: <strong><?= e($_SESSION['auth_username'] ?? '') ?></strong>
            <?php else: ?>
                Admin Login
            <?php endif; ?>
        </div>
    </div>

    <?php if ($error !== ''): ?><div class="alert error"><?= e($error) ?></div><?php endif; ?>
    <?php if ($success !== ''): ?><div class="alert success"><?= e($success) ?></div><?php endif; ?>

    <?php if (!$loggedIn): ?>
        <div class="panel">
            <div class="panel-head"><div><h2>Admin Login</h2><div class="sub">Login with the Admin table username and password</div></div></div>
            <div class="panel-body">
                <form method="post" autocomplete="off">
                    <div class="form-grid">
                        <div class="field full"><label>Username</label><input type="text" name="login_username" required></div>
                        <div class="field full"><label>Password</label><input type="password" name="login_password" required></div>
                    </div>
                    <div class="btns"><button class="btn primary" type="submit" name="do_login">Login</button></div>
                </form>
            </div>
        </div>
    <?php else: ?>
        <div class="panel">
            <div class="panel-head">
                <div><h2>Permission Form</h2><div class="sub">Type username and password to auto-load matching permissions</div></div>
            </div>
            <div class="panel-body">
                <form method="post" autocomplete="off" id="permissionForm">
                    <div class="form-grid">
                        <div class="field"><label>Username</label><input type="text" name="username" id="username" value="<?= e($form['username']) ?>" required></div>
                        <div class="field"><label>Password</label><input type="text" name="password" id="password" value="<?= e($form['password']) ?>" required></div>
                    </div>
                    <div class="status-row">
                        <div class="status-title">Auto load status</div>
                        <div class="status-pill" id="statusPill">Waiting</div>
                    </div>
                    <?php foreach ($groups as $groupTitle => $keys): ?>
                        <div class="section">
                            <div class="section-head"><h3><?= e($groupTitle) ?></h3><span><?= count($keys) ?> permission(s)</span></div>
                            <div class="perm-grid">
                                <?php foreach ($keys as $key): ?>
                                    <div class="perm">
                                        <div class="name"><?= e($permissionFields[$key]) ?></div>
                                        <div style="display:flex;align-items:center;gap:10px;">
                                            <span class="state" id="state_<?= e($key) ?>"><?= e($form[$key]) ?></span>
                                            <label class="switch">
                                                <input type="checkbox" name="<?= e($key) ?>" value="Yes" <?= $form[$key] === 'Yes' ? 'checked' : '' ?> onchange="updateState(this, 'state_<?= e($key) ?>')">
                                                <span class="slider"></span>
                                            </label>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                    <div class="section">
                        <div class="section-head"><h3>Match Data Permissions</h3><span class="allowed-badge" id="allowedCatCount">0 Categories Allowed</span></div>
                        <div style="padding:16px;">
                            <?php foreach ($categories as $cat): ?>
                                <div class="cat-box" data-catid="<?= $cat['id'] ?>">
                                    <h4><?= e($cat['title']) ?></h4>
                                    <div class="cat-grid">
                                        <?php 
                                        $actions = ['add_match' => 'Add Match', 'add_rules' => 'Add Rules', 'edit_match' => 'Edit Match', 'delete_match' => 'Delete Match'];
                                        foreach ($actions as $actKey => $actLabel): 
                                            $isChecked = ($form['match_data'][$cat['id']][$actKey] ?? 'No') === 'Yes';
                                            $stateId = "state_cat_{$cat['id']}_{$actKey}";
                                        ?>
                                        <div class="perm" style="box-shadow:none; padding:10px; border-radius:14px; background:#f8fbff;">
                                            <div class="name" style="font-size:13px;"><?= $actLabel ?></div>
                                            <div style="display:flex;align-items:center;gap:8px;">
                                                <span class="state" style="min-width:40px; font-size:11px;" id="<?= $stateId ?>"><?= $isChecked ? 'Yes' : 'No' ?></span>
                                                <label class="switch" style="width:48px; height:28px;">
                                                    <input type="checkbox" class="cat-chk" name="match_data[<?= $cat['id'] ?>][<?= $actKey ?>]" value="Yes" <?= $isChecked ? 'checked' : '' ?> onchange="updateState(this, '<?= $stateId ?>'); calculateCatCount();">
                                                    <span class="slider" style="height:28px;"></span>
                                                </label>
                                            </div>
                                        </div>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <div class="btns"><button class="btn primary" type="submit" name="save_permission">Save Permission</button><a href="UserInfo.php" class="btn" style="background:var(--muted);">Back to Users</a></div>
                </form>
            </div>
        </div>
    <?php endif; ?>
</div>

<script>
function updateState(checkbox, stateId) {
    const el = document.getElementById(stateId);
    if (el) el.textContent = checkbox.checked ? 'Yes' : 'No';
}
function calculateCatCount() {
    let count = 0;
    document.querySelectorAll('.cat-box').forEach(box => {
        if (Array.from(box.querySelectorAll('.cat-chk')).some(chk => chk.checked)) count++;
    });
    document.getElementById('allowedCatCount').textContent = count + ' Categories Allowed';
}
function setAllStatesToNo() {
    document.querySelectorAll('.state').forEach(el => el.textContent = 'No');
    document.querySelectorAll('input[type="checkbox"]').forEach(cb => cb.checked = false);
    calculateCatCount();
}
function applyPermissions(data) {
    if (!data) return;
    if (data.username) document.getElementById('username').value = data.username;
    if (data.password) document.getElementById('password').value = data.password;
    const perms = data.permissions || {};
    Object.keys(perms).forEach(key => {
        const cb = document.querySelector('input[name="' + key + '"]'), state = document.getElementById('state_' + key), val = perms[key] === 'Yes';
        if (cb) cb.checked = val; if (state) state.textContent = val ? 'Yes' : 'No';
    });
    const mData = data.match_data || {};
    document.querySelectorAll('.cat-box').forEach(box => {
        const cid = box.getAttribute('data-catid'), d = mData[cid] || {};
        ['add_match', 'add_rules', 'edit_match', 'delete_match'].forEach(act => {
            const cb = document.querySelector(`input[name="match_data[${cid}][${act}]"]`), state = document.getElementById(`state_cat_${cid}_${act}`), val = d[act] === 'Yes';
            if (cb) cb.checked = val; if (state) state.textContent = val ? 'Yes' : 'No';
        });
    });
    calculateCatCount();
}
let autofillTimer = null, autofillController = null;
function updateStatus(text, type) {
    const pill = document.getElementById('statusPill');
    if (!pill) return;
    pill.textContent = text;
    pill.style.background = type === 'ok' ? 'linear-gradient(135deg, #22c55e, #16a34a)' : type === 'warn' ? 'linear-gradient(135deg, #f59e0b, #d97706)' : type === 'bad' ? 'linear-gradient(135deg, #ef4444, #dc2626)' : '#94a3b8';
}
function scheduleAutofill() {
    const u = document.getElementById('username').value.trim(), p = document.getElementById('password').value.trim();
    if (u === '' || p === '') { updateStatus('Waiting', 'idle'); return; }
    clearTimeout(autofillTimer);
    autofillTimer = setTimeout(() => {
        if (autofillController) autofillController.abort();
        autofillController = new AbortController();
        updateStatus('Checking', 'idle');
        const url = new URL(window.location.href);
        url.searchParams.set('action', 'autofill'); url.searchParams.set('username', u); url.searchParams.set('password', p);
        fetch(url.toString(), { signal: autofillController.signal })
        .then(r => r.json().then(data => ({ ok: r.ok, data })))
        .then(({ ok, data }) => {
            if (!ok || !data || data.ok === false) { updateStatus('Error', 'bad'); return; }
            if (data.found) { applyPermissions(data.data); updateStatus('Loaded', 'ok'); }
            else { setAllStatesToNo(); updateStatus('Not Found', 'warn'); }
        }).catch(err => { if (err.name !== 'AbortError') updateStatus('Error', 'bad'); });
    }, 350);
}
document.addEventListener('DOMContentLoaded', () => {
    ['username', 'password'].forEach(id => {
        const el = document.getElementById(id);
        if (el) { el.addEventListener('input', scheduleAutofill); el.addEventListener('change', scheduleAutofill); }
    });
    document.querySelectorAll('.slider').forEach(s => {
        s.style.height = s.parentNode.style.height || '34px';
        const before = document.createElement('style');
        before.innerHTML = `.switch input:checked + .slider[style*="28px"]:before { transform: translateX(20px); height: 20px; width: 20px; top: 4px; left: 4px; } .slider[style*="28px"]:before { height: 20px; width: 20px; top: 4px; left: 4px; }`;
        document.head.appendChild(before);
    });
    calculateCatCount();
    if (document.getElementById('username')?.value.trim() !== '' && document.getElementById('password')?.value.trim() !== '') scheduleAutofill();
});
</script>
</body>
</html>