<?php
// Filename: admin_settings.php
require 'config.php';
requireLogin();

// Define update system constants
if (!defined('UPDATE_CHECK_URL')) {
    define('UPDATE_CHECK_URL', 'https://manage.apasaja.my/update_check_api.php');
}
if (!defined('UPDATE_DOWNLOAD_URL')) {
    define('UPDATE_DOWNLOAD_URL', 'https://manage.apasaja.my/update_download_api.php');
}
if (!defined('UPDATE_REPORT_URL')) {
    define('UPDATE_REPORT_URL', 'https://manage.apasaja.my/update_report_api.php');
}

// Include update notification system
if (file_exists(__DIR__ . '/includes/update_notification_optimized.php')) {
    include_once __DIR__ . '/includes/update_notification_optimized.php';
}

// --- 1. ENCODING & SECURITY HEADERS ---
header('Content-Type: text/html; charset=utf-8'); 
header("X-Frame-Options: DENY");
header("X-Content-Type-Options: nosniff");
header("Referrer-Policy: same-origin");
header("X-XSS-Protection: 1; mode=block");

$user_id = $_SESSION['user_id'];
$role = $_SESSION['role'];
$msg = ''; $msg_type = '';

if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// --- 2. HELPERS ---
function refreshGlobalSettings(PDO $pdo): array {
    $stmt = $pdo->query("SELECT setting_key, setting_value FROM system_settings");
    $rows = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
    return is_array($rows) ? $rows : [];
}

function getSafeSetting(string $key, string $default=''): string {
    global $GLOBAL_SETTINGS, $pdo;
    if (isset($GLOBAL_SETTINGS[$key])) return (string)$GLOBAL_SETTINGS[$key];
    $stmt = $pdo->prepare("SELECT setting_value FROM system_settings WHERE setting_key = ? LIMIT 1");
    $stmt->execute([$key]);
    $val = $stmt->fetchColumn();
    return ($val !== false && $val !== null && $val !== '') ? (string)$val : $default;
}

function safeUnlink(string $path, array $allowedDirs = ['uploads']): void {
    if ($path === '') return;
    $real = realpath($path);
    if ($real === false) return;
    foreach ($allowedDirs as $dir) {
        $base = realpath($dir);
        if ($base !== false && str_starts_with($real, $base . DIRECTORY_SEPARATOR)) {
            if (is_file($real)) @unlink($real);
            return;
        }
    }
}

function uploadImageFile(string $fileKey, string $prefix, string $oldPath = '', int $maxBytes = 3145728): string {
    if (!isset($_FILES[$fileKey]) || empty($_FILES[$fileKey]['tmp_name'])) return $oldPath;
    $err = $_FILES[$fileKey]['error'] ?? UPLOAD_ERR_NO_FILE;
    if ($err !== UPLOAD_ERR_OK) throw new Exception("Upload failed.");
    $size = (int)($_FILES[$fileKey]['size'] ?? 0);
    if ($size > $maxBytes) throw new Exception("File too large.");
    $target_dir = "uploads/";
    if (!is_dir($target_dir)) mkdir($target_dir, 0755, true);
    $ext = strtolower(pathinfo($_FILES[$fileKey]['name'] ?? '', PATHINFO_EXTENSION));
    if (!in_array($ext, ['jpg','jpeg','png','gif'], true)) throw new Exception("Invalid extension.");
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $mime  = $finfo->file($_FILES[$fileKey]['tmp_name']);
    if (!in_array($mime, ['image/jpeg','image/png','image/gif'], true)) throw new Exception("Invalid MIME.");
    $newName = $prefix . "_" . date('Ymd_His') . "_" . bin2hex(random_bytes(4)) . "." . $ext;
    $dest = $target_dir . $newName;
    if (!move_uploaded_file($_FILES[$fileKey]['tmp_name'], $dest)) throw new Exception("Upload error.");
    if ($oldPath && $oldPath !== $dest) safeUnlink($oldPath, ['uploads']);
    return $dest;
}

$GLOBAL_SETTINGS = refreshGlobalSettings($pdo);

// --- 3. SECURITY LAYER (UPGRADED FOR MOBILE OTP) ---
if (getSafeSetting('security_2fa_enabled', '0') === '1' && getSafeSetting('security_2fa_settings_page', '0') === '1') {
    if (empty($_SESSION['settings_2fa_verified'])) {
        $stmt = $pdo->prepare("SELECT telegram_chat_id FROM users WHERE id = ?");
        $stmt->execute([$user_id]);
        $chat_id = $stmt->fetchColumn();
        if (!empty($chat_id)) {
            $error = '';
            if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['verify_otp'])) {
                if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
                    $error = "Security error.";
                } else {
                    $user_otp = trim((string)($_POST['otp_code'] ?? ''));
                    if ($user_otp !== '' && hash_equals((string)($_SESSION['settings_2fa_code'] ?? ''), $user_otp) && (time() - (int)($_SESSION['settings_2fa_time'] ?? 0) < 300)) {
                        $_SESSION['settings_2fa_verified'] = true;
                        unset($_SESSION['settings_2fa_code'], $_SESSION['settings_2fa_time']);
                        header("Location: admin_settings.php"); exit;
                    } else { $error = "Invalid code."; }
                }
            }
            $lastSent = (int)($_SESSION['settings_2fa_time'] ?? 0);
            if ($lastSent === 0 || (time() - $lastSent > 60)) {
                $otp = random_int(100000, 999999);
                $_SESSION['settings_2fa_code'] = (string)$otp;
                $_SESSION['settings_2fa_time'] = time();
                if (function_exists('sendTelegram')) @sendTelegram("Code: $otp", $chat_id, 'otp');
            }
            ?>
            <!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, viewport-fit=cover">
                <title>Security Verification</title>
                <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
                <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
                <style>
                    :root { --primary-grad: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%); }
                    body { background-color: #f8f9fd; font-family: 'Plus Jakarta Sans', sans-serif; display: flex; align-items: center; justify-content: center; min-height: 100dvh; margin: 0; }
                    .otp-card { background: white; border-radius: 30px; padding: 40px 25px; box-shadow: 0 20px 40px rgba(0,0,0,0.06); width: 100%; max-width: 360px; }
                    .otp-container { display: flex; gap: 8px; justify-content: center; margin: 25px 0; }
                    .otp-digit { width: 45px; height: 55px; border: 2px solid #e2e8f0; border-radius: 12px; text-align: center; font-size: 1.5rem; font-weight: 700; background: #f8fafc; transition: all 0.2s; }
                    .otp-digit:focus { border-color: #8b5cf6; background: white; outline: none; box-shadow: 0 0 0 4px rgba(139, 92, 246, 0.1); }
                    .btn-verify { background: var(--primary-grad); border: none; padding: 14px; border-radius: 16px; color: white; font-weight: 700; width: 100%; box-shadow: 0 10px 20px rgba(139, 92, 246, 0.2); transition: transform 0.2s; }
                    .btn-verify:active { transform: scale(0.98); }
                </style>
            </head>
            <body>
                <div class="otp-card text-center mx-3">
                    <div class="mb-3"><i class="bi bi-shield-lock-fill text-primary fs-1"></i></div>
                    <h4 class="fw-bold text-dark">Verify Access</h4>
                    <p class="text-muted small">Enter the 6-digit code sent to your Telegram.</p>
                    <?php if($error): ?><div class="alert alert-danger py-2 small fw-bold mb-3"><?= htmlspecialchars($error) ?></div><?php endif; ?>
                    <form method="POST" id="otpForm">
                        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token']) ?>">
                        <input type="hidden" name="otp_code" id="final_otp">
                        <div class="otp-container">
                            <?php for($i=0; $i<6; $i++): ?>
                            <input type="tel" maxlength="1" class="otp-digit" inputmode="numeric" pattern="[0-9]*" <?= ($i===0)?'autofocus':'' ?>>
                            <?php endfor; ?>
                        </div>
                        <button type="submit" name="verify_otp" class="btn-verify">Verify Identity</button>
                    </form>
                    <div class="mt-4 small text-muted">Didn't get a code? <a href="admin_settings.php" class="text-primary fw-bold text-decoration-none">Resend</a></div>
                </div>
                <script>
                    const inputs = document.querySelectorAll('.otp-digit');
                    const finalInput = document.getElementById('final_otp');
                    inputs.forEach((input, index) => {
                        input.addEventListener('input', (e) => {
                            if (e.target.value.length > 1) e.target.value = e.target.value.slice(0, 1);
                            if (e.target.value !== "" && index < inputs.length - 1) inputs[index + 1].focus();
                            updateFinalValue();
                        });
                        input.addEventListener('keydown', (e) => {
                            if (e.key === 'Backspace' && e.target.value === "" && index > 0) inputs[index - 1].focus();
                        });
                        input.addEventListener('paste', (e) => {
                            e.preventDefault();
                            const pasteData = e.clipboardData.getData('text').slice(0, 6).split('');
                            pasteData.forEach((char, i) => { if (inputs[index + i]) inputs[index + i].value = char; });
                            updateFinalValue();
                        });
                    });
                    function updateFinalValue() {
                        let val = "";
                        inputs.forEach(input => val += input.value);
                        finalInput.value = val;
                    }
                </script>
            </body>
            </html>
            <?php exit;
        }
    }
}

// --- 4. HANDLE UPDATE ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) die("CSRF Error");
    try {
        $pdo->beginTransaction();
        $logo_path = getSafeSetting('school_logo', '');
        $off_logo_path = getSafeSetting('official_logo_path', '');
        if (isset($_POST['remove_logo']) && $_POST['remove_logo'] == '1') { safeUnlink($logo_path, ['uploads']); $logo_path = ''; }
        if (isset($_FILES['school_logo']) && !empty($_FILES['school_logo']['tmp_name'])) { $logo_path = uploadImageFile('school_logo', 'logo', $logo_path); }
        if (isset($_POST['remove_official_logo']) && $_POST['remove_official_logo'] == '1') { safeUnlink($off_logo_path, ['uploads']); $off_logo_path = ''; }
        if (isset($_FILES['official_logo']) && !empty($_FILES['official_logo']['tmp_name'])) { $off_logo_path = uploadImageFile('official_logo', 'official', $off_logo_path); }

        $settings = [
            'school_name' => $_POST['school_name'] ?? '',
            'school_phone' => $_POST['school_phone'] ?? '',
            'school_address' => $_POST['school_address'] ?? '',
            'principal_name' => $_POST['principal_name'] ?? '',
            'hem_name' => $_POST['hem_name'] ?? '',
            'school_info' => $_POST['school_info'] ?? '',
            'letter_reference' => $_POST['letter_reference'] ?? '',
            'school_logo' => $logo_path,
            'official_logo_path' => $off_logo_path,
            'religion_list' => $_POST['religion_list'] ?? '',
            'infraction_list' => $_POST['infraction_list'] ?? '',
            'student_absence_reasons' => $_POST['student_absence_reasons'] ?? '',
            'official_absence_reasons' => $_POST['official_absence_reasons'] ?? '',
            'leave_types' => $_POST['leave_types'] ?? '',
            'start_time' => $_POST['start_time'] ?? '07:30',
            'slot_duration' => $_POST['slot_duration'] ?? '30',
            'recess_slot' => $_POST['recess_slot'] ?? '5',
            'recess_slot_upper' => $_POST['recess_slot_upper'] ?? '6',
            'recess_duration' => $_POST['recess_duration'] ?? '20',
            'recess_keyword' => $_POST['recess_keyword'] ?? 'RECESS',
            'header_theme' => $_POST['header_theme'] ?? 'default',
            'max_relief_per_day' => $_POST['max_relief_per_day'] ?? '2',
            'sound_enabled' => isset($_POST['sound_enabled']) ? '1' : '0',
            'absence_cutoff_time' => $_POST['absence_cutoff_time'] ?? '07:30',
            'relief_mode' => $_POST['relief_mode'] ?? 'manual',
            'system_mode' => $_POST['system_mode'] ?? 'live',
            'maintenance_mode' => isset($_POST['maintenance_mode']) ? '1' : '0',
            'security_email' => $_POST['security_email'] ?? '',
            'gps_accuracy_threshold' => $_POST['gps_accuracy_threshold'] ?? '100',
            'teacher_registration' => isset($_POST['teacher_registration']) ? '1' : '0',
            'security_2fa_enabled' => isset($_POST['security_2fa_enabled']) ? '1' : '0',
            'security_2fa_settings_page' => isset($_POST['security_2fa_settings_page']) ? '1' : '0',
            'security_2fa_system_page' => isset($_POST['security_2fa_system_page']) ? '1' : '0',
            'auto_cache_clear' => isset($_POST['auto_cache_clear']) ? '1' : '0',
            'public_portal_enabled' => isset($_POST['public_portal_enabled']) ? '1' : '0',
            'parent_portal_enabled' => isset($_POST['parent_portal_enabled']) ? '1' : '0',
            'public_calendar_enabled' => isset($_POST['public_calendar_enabled']) ? '1' : '0',
            'telegram_bot_token' => $_POST['telegram_bot_token'] ?? '',
            'telegram_chat_id' => $_POST['telegram_chat_id'] ?? '',
            'school_lat' => $_POST['school_lat'] ?? '',
            'school_lon' => $_POST['school_lon'] ?? '',
            'school_radius' => $_POST['school_radius'] ?? '200',
            'allowed_ips' => trim($_POST['allowed_ips'] ?? ''),
            'ip_check_enabled' => isset($_POST['ip_check_enabled']) ? '1' : '0',
            'geolocation_enabled' => isset($_POST['geolocation_enabled']) ? '1' : '0',
            'week_start_day' => $_POST['week_start_day'] ?? '1',
            'school_days_count' => $_POST['school_days_count'] ?? '5'
        ];
        for ($i = 1; $i <= 7; $i++) { if (isset($_POST["end_time_$i"])) $settings["end_time_$i"] = $_POST["end_time_$i"]; }
        $stmt = $pdo->prepare("INSERT INTO system_settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)");
        foreach ($settings as $key => $val) { $stmt->execute([$key, (string)$val]); }
        $pdo->commit();
        $GLOBAL_SETTINGS = refreshGlobalSettings($pdo);
        $msg = "Settings updated successfully."; $msg_type = "success";
    } catch (Exception $e) { if ($pdo->inTransaction()) $pdo->rollBack(); $msg = "Error: " . $e->getMessage(); $msg_type = "danger"; }
}

// --- FETCH VARIABLES ---
$s_name = getSafeSetting('school_name', 'My School');
$s_info = getSafeSetting('school_info', '');
$s_phone = getSafeSetting('school_phone', '');
$s_addr = getSafeSetting('school_address', '');
$s_principal = getSafeSetting('principal_name', '');
$s_hem = getSafeSetting('hem_name', '');
$s_letter_ref = getSafeSetting('letter_reference', '');
$s_religion = getSafeSetting('religion_list', 'Islam,Kristian,Buddha,Hindu,Sikh,Taoisme,Konfusianisme,Agama Tradisi Cina,Kepercayaan Pribumi,Tiada Agama');
$s_infractions = getSafeSetting('infraction_list', 'Disruptive Behavior,Late,Truancy,Improper Uniform,Fighting,Vandalism,Other');
$s_absence_reasons = getSafeSetting('student_absence_reasons', 'PdPR,Aktiviti Sekolah,Pergi ke hospital/Klinik,Cuti Sakit,Penggiliran Kerana Peperiksaan,Lain-lain');
$s_official_reasons = getSafeSetting('official_absence_reasons', 'PdPR,Aktiviti Sekolah,Cuti Sakit,Penggiliran Kerana Peperiksaan,Pergi ke hospital/Klinik');
$s_leave_types = getSafeSetting('leave_types', 'MC,CRK,Cuti Rehat,Cuti Tanpa Gaji,Kecemasan,Other');
$s_start = getSafeSetting('start_time', '07:30');
$s_dur = getSafeSetting('slot_duration', '30');
$s_rec_slot = getSafeSetting('recess_slot', '5');
$s_rec_slot_up = getSafeSetting('recess_slot_upper', '6');
$s_rec_dur = getSafeSetting('recess_duration', '20');

$week_start = intval(getSafeSetting('week_start_day', '1'));
$school_days_count = intval(getSafeSetting('school_days_count', '5'));
$days_map = [1=>'Mon', 2=>'Tue', 3=>'Wed', 4=>'Thu', 5=>'Fri', 6=>'Sat', 7=>'Sun'];
$display_order = ($week_start === 7) ? [7, 1, 2, 3, 4, 5, 6] : [1, 2, 3, 4, 5, 6, 7];

$system_mode = getSafeSetting('system_mode', 'live');
$relief_mode = getSafeSetting('relief_mode', 'manual');
$max_rel = getSafeSetting('max_relief_per_day', '2');
$sound_enabled = getSafeSetting('sound_enabled', '1');
$header_theme = getSafeSetting('header_theme', 'default');
$g_lat = getSafeSetting('school_lat', '');
$g_lon = getSafeSetting('school_lon', '');
$g_rad = getSafeSetting('school_radius', '200');
$geo_enabled = getSafeSetting('geolocation_enabled', '1');
$allowed_ips = getSafeSetting('allowed_ips', '');
$ip_enabled = getSafeSetting('ip_check_enabled', '0');
$current_ip = $_SERVER['REMOTE_ADDR'] ?? '';

$my_personal_tg_stmt = $pdo->prepare("SELECT telegram_chat_id FROM users WHERE id = ?");
$my_personal_tg_stmt->execute([$user_id]);
$my_personal_tg = $my_personal_tg_stmt->fetchColumn();

// --- GET LICENSE & VERSION INFO ---
$licenseInfo = null;
$isTrial = false;
$isActive = false;
$daysRemaining = 0;
$licenseKey = 'Not Activated';
$licenseStatus = 'No License';
$expiryDate = 'N/A';

if (file_exists('license.key')) {
    try {
        $licenseContent = file_get_contents('license.key');
        $key = hash('sha256', $_SERVER['HTTP_HOST'] . $_SERVER['DOCUMENT_ROOT'], true);
        $decoded = base64_decode($licenseContent);
        if (strlen($decoded) > 16) {
            $iv = substr($decoded, 0, 16);
            $encrypted = substr($decoded, 16);
            $decrypted = @openssl_decrypt($encrypted, 'AES-256-CBC', $key, 0, $iv);
            if ($decrypted) {
                $licenseInfo = json_decode($decrypted, true);
                if ($licenseInfo) {
                    $licenseKey = $licenseInfo['license_key'] ?? 'Unknown';
                    $licenseStatus = ucfirst($licenseInfo['status'] ?? 'unknown');
                    $isTrial = ($licenseInfo['status'] ?? '') === 'trial';
                    $isActive = in_array($licenseInfo['status'] ?? '', ['active', 'trial']);
                    
                    if (!empty($licenseInfo['expires_at'])) {
                        $expiryDate = date('F j, Y', strtotime($licenseInfo['expires_at']));
                        $daysRemaining = max(0, floor((strtotime($licenseInfo['expires_at']) - time()) / 86400));
                    } else {
                        $expiryDate = 'Lifetime';
                        $daysRemaining = 999999;
                    }
                }
            }
        }
    } catch (Exception $e) {
        // Silent fail
    }
}

// Get current software version
$currentVersion = '1.0.0';
try {
    $stmt = $pdo->prepare("SELECT setting_value FROM system_settings WHERE setting_key = 'software_version'");
    $stmt->execute();
    $result = $stmt->fetch();
    if ($result) {
        $currentVersion = $result['setting_value'];
    }
} catch (Exception $e) {
    // Use default
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>System Settings</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    
    <!-- Update Notification System -->
    <?php 
    if (file_exists(__DIR__ . '/includes/update_notification_optimized.php')) {
        include_once __DIR__ . '/includes/update_notification_optimized.php';
    }
    ?>
    
    <style>
        :root { --primary-grad: <?= getHeaderTheme() ?>; --bg-color: #f8f9fd; }
        body { font-family: 'Plus Jakarta Sans', sans-serif; background-color: var(--bg-color); padding-bottom: 150px; }
        .app-header { background: var(--primary-grad); padding: 30px 20px 80px 20px; border-radius: 0 0 35px 35px; color: white; text-align: center; }
        .floating-card { background: white; margin: -60px 20px 20px 20px; border-radius: 24px; padding: 20px; box-shadow: 0 15px 35px rgba(0,0,0,0.08); position: relative; z-index: 10; }
        .accordion-button { border-radius: 16px !important; font-weight: 700; background: white; box-shadow: 0 2px 5px rgba(0,0,0,0.02); }
        .accordion-button:not(.collapsed) { background: #f5f3ff; color: #8B5CF6; }
        .accordion-body { background: white; border-radius: 0 0 16px 16px; padding: 15px; margin-top: -5px; }
        .form-control, .form-select { border-radius: 12px; padding: 12px; background: #f8fafc; font-size: 0.95rem; }
        
        /* Thumb-friendly mobile save bar */
        .save-bar { position: fixed; bottom: 100px; left: 50%; transform: translateX(-50%); background: #1e293b; color: white; padding: 12px 20px; border-radius: 50px; width: 90%; max-width: 340px; display: none; justify-content: space-between; align-items: center; z-index: 1050; box-shadow: 0 10px 30px rgba(0,0,0,0.3); }
        .save-bar.show { display: flex; }
        .day-hidden { display: none !important; }
    </style>
</head>
<body>
    <div class="app-header no-print">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <a href="admin_dashboard.php" class="text-white"><i class="bi bi-arrow-left fs-4"></i></a>
            <div class="fw-bold fs-5">Settings</div>
            <div style="width: 24px;"></div>
        </div>
        <div class="opacity-75 small">Full System Configuration</div>
    </div>

    <div class="floating-card">
        <?php if($msg): ?><div class="alert alert-<?= htmlspecialchars($msg_type) ?> border-0 shadow-sm rounded-3 text-center small mb-4"><?= $msg ?></div><?php endif; ?>

        <form method="POST" enctype="multipart/form-data" id="settingsForm">
            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token']) ?>">

            <div class="accordion" id="settingsAccordion">

                <div class="accordion-item"><h2 class="accordion-header"><button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapseOne"><i class="bi bi-building me-2 text-primary"></i> School Profile</button></h2><div id="collapseOne" class="accordion-collapse collapse" data-bs-parent="#settingsAccordion"><div class="accordion-body">
                    <div class="mb-3"><label class="form-label">School Name</label><input type="text" name="school_name" class="form-control" value="<?= htmlspecialchars($s_name) ?>"></div>
                    <div class="mb-3"><label class="form-label">Tagline (School Info)</label><input type="text" name="school_info" class="form-control" value="<?= htmlspecialchars($s_info) ?>"></div>
                    <div class="row g-2 mb-3">
                        <div class="col-6"><label class="form-label">Principal Name</label><input type="text" name="principal_name" class="form-control" value="<?= htmlspecialchars($s_principal) ?>"></div>
                        <div class="col-6"><label class="form-label">PK HEM Name</label><input type="text" name="hem_name" class="form-control" value="<?= htmlspecialchars($s_hem) ?>"></div>
                    </div>
                    <div class="row g-2 mb-3"><div class="col-6"><label class="form-label">Phone</label><input type="tel" name="school_phone" class="form-control" value="<?= htmlspecialchars($s_phone) ?>"></div><div class="col-6"><label class="form-label">Reference Code</label><input type="text" name="letter_reference" class="form-control" value="<?= htmlspecialchars($s_letter_ref) ?>"></div></div>
                    <div class="mb-3"><label class="form-label">Address</label><textarea name="school_address" class="form-control" rows="3"><?= htmlspecialchars($s_addr) ?></textarea></div>
                    <div class="row g-2 mb-3"><div class="col-6 text-center"><label class="form-label d-block">App Logo</label><input type="file" name="school_logo" class="form-control form-control-sm" accept="image/*"></div><div class="col-6 text-center"><label class="form-label d-block">Letter Logo</label><input type="file" name="official_logo" class="form-control form-control-sm" accept="image/*"></div></div>
                </div></div></div>

                <div class="accordion-item"><h2 class="accordion-header"><button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseTheme"><i class="bi bi-palette me-2 text-purple"></i> App Appearance</button></h2><div id="collapseTheme" class="accordion-collapse collapse" data-bs-parent="#settingsAccordion"><div class="accordion-body">
                    <div class="mb-3">
                        <label class="form-label text-dark fw-bold">Header Theme</label>
                        <select name="header_theme" class="form-select fw-bold">
                            <option value="default" <?= $header_theme=='default'?'selected':'' ?>>Default (Purple)</option>
                            <option value="auto" <?= $header_theme=='auto'?'selected':'' ?>>✨ Auto Seasonal (Festivals)</option>
                            <option value="rainy" <?= $header_theme=='rainy'?'selected':'' ?>>🌧️ Weather: Rainy (Grey)</option>
                            <option value="sunny" <?= $header_theme=='sunny'?'selected':'' ?>>☀️ Weather: Sunny (Orange)</option>
                            <option value="blue" <?= $header_theme=='blue'?'selected':'' ?>>Corporate Blue</option>
                            <option value="red" <?= $header_theme=='red'?'selected':'' ?>>Alert Red</option>
                            <option value="dark" <?= $header_theme=='dark'?'selected':'' ?>>Night Mode</option>
                        </select>
                        <div class="form-text small">"Auto Seasonal" changes colors automatically based on Malaysian festivals.</div>
                    </div>
                </div></div></div>

                <div class="accordion-item"><h2 class="accordion-header"><button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapsePortals"><i class="bi bi-globe me-2 text-info"></i> Public Portals & Access</button></h2><div id="collapsePortals" class="accordion-collapse collapse" data-bs-parent="#settingsAccordion"><div class="accordion-body">
                    <div class="form-check form-switch mb-3"><input class="form-check-input" type="checkbox" name="public_portal_enabled" id="pubPort" <?= getSafeSetting('public_portal_enabled')=='1'?'checked':'' ?>><label class="form-check-label fw-bold" for="pubPort">Enable Official Public Portal (public.php)</label></div>
                    <div class="form-check form-switch mb-3"><input class="form-check-input" type="checkbox" name="parent_portal_enabled" id="parPort" <?= getSafeSetting('parent_portal_enabled')=='1'?'checked':'' ?>><label class="form-check-label fw-bold" for="parPort">Enable Parent Portal (public_parent.php)</label></div>
                    <div class="form-check form-switch mb-3"><input class="form-check-input" type="checkbox" name="public_calendar_enabled" id="pubCal" <?= getSafeSetting('public_calendar_enabled')=='1'?'checked':'' ?>><label class="form-check-label fw-bold text-primary" for="pubCal">Enable Calendar (public_calendar.php)</label></div>
                    <div class="form-check form-switch mb-3"><input class="form-check-input" type="checkbox" name="teacher_registration" id="regTog" <?= getSafeSetting('teacher_registration')=='1'?'checked':'' ?>><label class="form-check-label fw-bold text-primary" for="regTog">Enable Teacher Registration (register.php)</label></div>
                </div></div></div>

                <div class="accordion-item"><h2 class="accordion-header"><button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseTwo"><i class="bi bi-clock-history me-2 text-info"></i> Timetable & Recess</button></h2><div id="collapseTwo" class="accordion-collapse collapse" data-bs-parent="#settingsAccordion"><div class="accordion-body">
                    <div class="row g-2 mb-3"><div class="col-6"><label class="form-label">Start Time</label><input type="time" name="start_time" class="form-control" value="<?= htmlspecialchars($s_start) ?>"></div><div class="col-6"><label class="form-label">Slot Duration (Min)</label><input type="number" name="slot_duration" class="form-control" value="<?= htmlspecialchars($s_dur) ?>"></div></div>
                    <div class="bg-light p-3 rounded mb-3 border"><label class="form-label text-primary fw-bold mb-2">Recess (Staggered)</label><div class="row g-2"><div class="col-4"><label class="small text-muted">F1-3 Slot</label><input type="number" name="recess_slot" class="form-control text-center fw-bold" value="<?= htmlspecialchars($s_rec_slot) ?>"></div><div class="col-4"><label class="small text-muted">F4-6 Slot</label><input type="number" name="recess_slot_upper" class="form-control text-center fw-bold" value="<?= htmlspecialchars($s_rec_slot_up) ?>"></div><div class="col-4"><label class="small text-muted">Dur (Min)</label><input type="number" name="recess_duration" class="form-control text-center fw-bold" value="<?= htmlspecialchars($s_rec_dur) ?>"></div></div></div>
                    <div class="mb-3"><label class="form-label">Week Settings</label><div class="input-group"><select name="week_start_day" class="form-select"><option value="1" <?= $week_start==1?'selected':''?>>Mon Start</option><option value="7" <?= $week_start==7?'selected':''?>>Sun Start</option></select><select name="school_days_count" id="dayCount" class="form-select" onchange="updateDayVisibility()"><option value="5" <?= $school_days_count==5?'selected':''?>>5 Days</option><option value="6" <?= $school_days_count==6?'selected':''?>>6 Days</option></select></div></div>
                    <div class="row g-2" id="endTimesContainer"><?php foreach($display_order as $i => $day_id): ?><div class="col-4 day-input-group" data-day-index="<?= (int)$i ?>"><div class="bg-light rounded p-2 text-center border"><div class="small fw-bold text-muted mb-1"><?= htmlspecialchars($days_map[$day_id]) ?></div><input type="time" name="end_time_<?= (int)$day_id ?>" class="form-control form-control-sm text-center border-0 p-0 bg-transparent fw-bold" value="<?= htmlspecialchars(getSafeSetting("end_time_$day_id", '14:30')) ?>"></div></div><?php endforeach; ?></div>
                </div></div></div>

                <div class="accordion-item"><h2 class="accordion-header"><button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseOps"><i class="bi bi-sliders me-2 text-warning"></i> Operations</button></h2><div id="collapseOps" class="accordion-collapse collapse" data-bs-parent="#settingsAccordion"><div class="accordion-body">
                    <div class="mb-3"><label class="form-label">Absence Cut-off Time</label><input type="time" name="absence_cutoff_time" class="form-control" value="<?= htmlspecialchars(getSafeSetting('absence_cutoff_time','07:30')) ?>"></div>
                    <div class="mb-3"><label class="form-label">Attendance Mode</label><div class="btn-group w-100" role="group"><input type="radio" class="btn-check" name="system_mode" id="sm_live" value="live" <?= $system_mode=='live'?'checked':'' ?>><label class="btn btn-outline-primary" for="sm_live">Scanner</label><input type="radio" class="btn-check" name="system_mode" id="sm_manual" value="manual" <?= $system_mode=='manual'?'checked':'' ?>><label class="btn btn-outline-primary" for="sm_manual">Manual</label></div></div>
                    <div class="mb-3"><label class="form-label">Relief Mode</label><div class="btn-group w-100" role="group"><input type="radio" class="btn-check" name="relief_mode" id="rm_manual" value="manual" <?= $relief_mode=='manual'?'checked':'' ?>><label class="btn btn-outline-secondary" for="rm_manual">Manual</label><input type="radio" class="btn-check" name="relief_mode" id="rm_auto" value="auto" <?= $relief_mode=='auto'?'checked':'' ?>><label class="btn btn-outline-secondary" for="rm_auto">Auto</label></div></div>
                    <div class="row g-2"><div class="col-6"><label class="form-label">Max Relief/Day</label><input type="number" name="max_relief_per_day" class="form-control" value="<?= htmlspecialchars($max_rel) ?>"></div><div class="col-6 pt-4"><div class="form-check form-switch ps-0"><label class="form-check-label ms-0 fw-bold text-dark" for="soundCheck"><i class="bi bi-volume-up-fill me-1"></i>Sound Alerts</label><input class="form-check-input ms-2" type="checkbox" name="sound_enabled" id="soundCheck" <?= $sound_enabled=='1'?'checked':'' ?>></div></div></div>
                </div></div></div>

                <div class="accordion-item"><h2 class="accordion-header"><button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseThree"><i class="bi bi-list-check me-2 text-success"></i> Data Lists</button></h2><div id="collapseThree" class="accordion-collapse collapse" data-bs-parent="#settingsAccordion"><div class="accordion-body">
                    <div class="mb-3"><label class="form-label fw-bold">Religions</label><textarea name="religion_list" class="form-control" rows="2" placeholder="Comma separated list"><?= htmlspecialchars($s_religion) ?></textarea></div>
                    <div class="mb-3"><label class="form-label fw-bold">Infractions</label><textarea name="infraction_list" class="form-control" rows="2"><?= htmlspecialchars($s_infractions) ?></textarea></div>
                    <div class="mb-3"><label class="form-label fw-bold">Absence Reasons</label><textarea name="student_absence_reasons" class="form-control" rows="2"><?= htmlspecialchars($s_absence_reasons) ?></textarea></div>
                    <div class="mb-3"><label class="form-label fw-bold text-success">Official Reasons</label><textarea name="official_absence_reasons" class="form-control" rows="2"><?= htmlspecialchars($s_official_reasons) ?></textarea></div>
                    <div class="mb-3"><label class="form-label fw-bold text-warning">Teacher Leave Types</label><textarea name="leave_types" class="form-control" rows="2" placeholder="MC, CRK, Other"><?= htmlspecialchars($s_leave_types) ?></textarea></div>
                </div></div></div>

                <!-- LICENSE, UPDATES & REGISTRATION SECTION -->
                <div class="accordion-item">
                    <h2 class="accordion-header">
                        <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseLicense">
                            <i class="bi bi-key-fill me-2 text-success"></i> License, Updates & Registration
                        </button>
                    </h2>
                    <div id="collapseLicense" class="accordion-collapse collapse" data-bs-parent="#settingsAccordion">
                        <div class="accordion-body">
                            
                            <!-- Software Version Card -->
                            <div class="card border-0 shadow-sm mb-3" style="background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);">
                                <div class="card-body text-white">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <div>
                                            <h6 class="mb-1 opacity-75">Current Version</h6>
                                            <h3 class="mb-0 fw-bold">v<?= htmlspecialchars($currentVersion) ?></h3>
                                        </div>
                                        <button type="button" class="btn btn-light btn-sm" onclick="checkForUpdates()">
                                            <i class="bi bi-arrow-clockwise me-1"></i>
                                            Check Updates
                                        </button>
                                    </div>
                                    <div id="updateCheckResult" class="mt-3" style="display: none;"></div>
                                </div>
                            </div>
                            
                            <!-- License Status Card -->
                            <div class="card border-0 shadow-sm mb-3" style="background: linear-gradient(135deg, <?= $isActive ? ($isTrial ? '#f59e0b' : '#10b981') : '#ef4444' ?> 0%, <?= $isActive ? ($isTrial ? '#d97706' : '#059669') : '#dc2626' ?> 100%);">
                                <div class="card-body text-white">
                                    <div class="d-flex justify-content-between align-items-start mb-3">
                                        <div>
                                            <h5 class="mb-1">
                                                <i class="bi bi-<?= $isActive ? ($isTrial ? 'gift' : 'check-circle-fill') : 'exclamation-triangle-fill' ?> me-2"></i>
                                                <?= $isActive ? ($isTrial ? 'Trial License' : 'Licensed') : 'Not Activated' ?>
                                            </h5>
                                            <p class="mb-0 opacity-90 small">
                                                <?= $isActive ? ($isTrial ? 'Evaluation Mode' : 'Full Version') : 'Activation Required' ?>
                                            </p>
                                        </div>
                                        <span class="badge bg-white text-dark px-3 py-2" style="font-size: 0.9rem;">
                                            <?= $licenseStatus ?>
                                        </span>
                                    </div>
                                    
                                    <div class="row g-3">
                                        <div class="col-md-6">
                                            <div class="bg-white bg-opacity-10 rounded p-2">
                                                <small class="opacity-75 d-block mb-1">License Key</small>
                                                <div class="font-monospace fw-bold" style="font-size: 0.85rem;">
                                                    <?php if ($licenseKey !== 'Not Activated'): ?>
                                                        <?= substr($licenseKey, 0, 4) ?>-****-****-<?= substr($licenseKey, -4) ?>
                                                    <?php else: ?>
                                                        Not Activated
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="bg-white bg-opacity-10 rounded p-2">
                                                <small class="opacity-75 d-block mb-1">
                                                    <?= $isTrial || !$isActive ? 'Expires' : 'Valid Until' ?>
                                                </small>
                                                <div class="fw-bold" style="font-size: 0.85rem;">
                                                    <?= $expiryDate ?>
                                                    <?php if ($daysRemaining < 999999): ?>
                                                        <small class="d-block opacity-90">(<?= $daysRemaining ?> days)</small>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <?php if ($isTrial && $daysRemaining <= 7): ?>
                                        <div class="alert alert-warning bg-white text-dark mt-3 mb-0 border-0">
                                            <i class="bi bi-clock-history me-2"></i>
                                            <strong>Trial Ending Soon!</strong> Only <?= $daysRemaining ?> days remaining. Activate a full license to continue using all features.
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                            
                            <!-- Quick Actions -->
                            <div class="row g-2 mb-3">
                                <?php if ($isTrial || !$isActive): ?>
                                    <div class="col-md-4">
                                        <a href="activate_license.php" class="btn btn-success w-100">
                                            <i class="bi bi-key-fill me-1"></i>
                                            <?= $isTrial ? 'Upgrade' : 'Activate' ?>
                                        </a>
                                    </div>
                                <?php endif; ?>
                                <div class="col-md-<?= ($isTrial || !$isActive) ? '4' : '6' ?>">
                                    <button type="button" class="btn btn-outline-primary w-100" onclick="checkLicenseStatus()">
                                        <i class="bi bi-arrow-clockwise me-1"></i>
                                        Verify License
                                    </button>
                                </div>
                                <div class="col-md-<?= ($isTrial || !$isActive) ? '4' : '6' ?>">
                                    <button type="button" class="btn btn-outline-info w-100" onclick="checkForUpdates()">
                                        <i class="bi bi-cloud-download me-1"></i>
                                        Check Updates
                                    </button>
                                </div>
                            </div>
                            
                            <!-- Registration Info -->
                            <div class="card border-0 bg-light">
                                <div class="card-body">
                                    <h6 class="mb-3"><i class="bi bi-info-circle me-2 text-primary"></i>Registration Information</h6>
                                    <div class="row g-2 small">
                                        <div class="col-6">
                                            <div class="text-muted mb-1">Installation ID</div>
                                            <div class="font-monospace text-truncate" title="<?= $licenseInfo['installation_id'] ?? 'Not registered' ?>">
                                                <?= isset($licenseInfo['installation_id']) ? substr($licenseInfo['installation_id'], 0, 16) . '...' : 'Not registered' ?>
                                            </div>
                                        </div>
                                        <div class="col-6">
                                            <div class="text-muted mb-1">Domain</div>
                                            <div class="fw-bold"><?= htmlspecialchars($_SERVER['HTTP_HOST']) ?></div>
                                        </div>
                                        <div class="col-6">
                                            <div class="text-muted mb-1">Activated</div>
                                            <div>
                                                <?= isset($licenseInfo['activated_at']) ? date('M j, Y', strtotime($licenseInfo['activated_at'])) : 'Not activated' ?>
                                            </div>
                                        </div>
                                        <div class="col-6">
                                            <div class="text-muted mb-1">Last Check</div>
                                            <div>
                                                <?= isset($licenseInfo['last_check']) ? date('M j, Y', strtotime($licenseInfo['last_check'])) : 'Never' ?>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- License Status Check Result -->
                            <div id="licenseCheckResult" class="mt-3" style="display: none;"></div>
                            
                        </div>
                    </div>
                </div>

                <div class="accordion-item"><h2 class="accordion-header"><button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseFour"><i class="bi bi-shield-lock me-2 text-danger"></i> System & Security</button></h2><div id="collapseFour" class="accordion-collapse collapse" data-bs-parent="#settingsAccordion"><div class="accordion-body">
                    <div class="card border-0 shadow-sm bg-light mb-3"><div class="card-body">
                        <div class="form-check form-switch d-flex justify-content-between align-items-center ps-0 mb-2"><label class="form-check-label fw-bold">Telegram 2FA Global</label><input class="form-check-input" type="checkbox" name="security_2fa_enabled" id="2faToggle" <?= getSafeSetting('security_2fa_enabled')=='1'?'checked':'' ?> <?= empty($my_personal_tg)?'disabled':'' ?>></div>
                        <div class="bg-white rounded p-2 border">
                            <small class="text-muted d-block mb-2 fw-bold">Select pages to protect:</small>
                            <div class="form-check form-switch mb-2"><input class="form-check-input" type="checkbox" name="security_2fa_settings_page" id="protSett" <?= getSafeSetting('security_2fa_settings_page')=='1'?'checked':'' ?>><label class="form-check-label small" for="protSett">Protect Settings Page</label></div>
                            <div class="form-check form-switch"><input class="form-check-input" type="checkbox" name="security_2fa_system_page" id="protSys" <?= getSafeSetting('security_2fa_system_page')=='1'?'checked':'' ?>><label class="form-check-label small" for="protSys">Protect System Page</label></div>
                        </div>
                    </div></div>
                    <div class="form-switch mb-2"><input class="form-check-input" type="checkbox" name="auto_cache_clear" id="cacheCheck" <?= getSafeSetting('auto_cache_clear')=='1'?'checked':'' ?>><label class="form-check-label fw-bold text-warning" for="cacheCheck"><i class="bi bi-stars me-1"></i>Auto Clear Cache</label></div>
                    <div class="form-switch mb-2"><input class="form-check-input" type="checkbox" name="maintenance_mode" id="maintCheck" <?= getSafeSetting('maintenance_mode')=='1'?'checked':'' ?>><label class="form-check-label text-danger fw-bold" for="maintCheck">Maintenance Mode</label></div>
                    <div class="mb-3">
                        <label class="form-label text-danger fw-bold">Security Contact Email</label>
                        <input type="email" name="security_email" class="form-control" 
                               value="<?= htmlspecialchars(getSafeSetting('security_email')) ?>" 
                               placeholder="e.g. security@yourschool.edu.my">
                        <div class="form-text small">Used in security.txt for vulnerability reporting.</div>
                    </div>
                    <div class="border-top pt-3 mt-3">
                        <div class="form-switch mb-2"><input class="form-check-input" type="checkbox" name="geolocation_enabled" id="geoCheck" <?= getSafeSetting('geolocation_enabled','1')=='1'?'checked':'' ?>><label class="form-check-label fw-bold text-primary" for="geoCheck">GPS Geofencing</label></div>
                        <div class="row g-2 mb-3 ps-4"><div class="col-4"><input type="text" name="school_lat" class="form-control form-control-sm" value="<?= htmlspecialchars(getSafeSetting('school_lat')) ?>" placeholder="Lat"></div><div class="col-4"><input type="text" name="school_lon" class="form-control form-control-sm" value="<?= htmlspecialchars(getSafeSetting('school_lon')) ?>" placeholder="Lon"></div><div class="col-4"><input type="text" name="school_radius" class="form-control form-control-sm" value="<?= htmlspecialchars(getSafeSetting('school_radius','200')) ?>" placeholder="Rad(m)"></div></div>
                        <div class="form-switch mb-2"><input class="form-check-input" type="checkbox" name="ip_check_enabled" id="ipCheck" <?= getSafeSetting('ip_check_enabled')=='1'?'checked':'' ?>><label class="form-check-label fw-bold text-dark" for="ipCheck">IP Restriction</label></div>
                        <div class="input-group input-group-sm mb-3 ps-4"><input type="text" name="allowed_ips" class="form-control" value="<?= htmlspecialchars($allowed_ips) ?>" placeholder="e.g. 192.168.1.1"><button type="button" class="btn btn-outline-secondary" onclick="useCurrentIp()">Use My IP</button></div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label fw-bold">GPS Accuracy Threshold (meters)</label>
                        <input type="number" name="gps_accuracy_threshold" class="form-control" 
                               value="<?= getSafeSetting('gps_accuracy_threshold', '100') ?>" min="10" max="500">
                        <small class="text-muted">Maximum acceptable GPS accuracy. Higher = less strict. Default: 100m</small>
                    </div>
                    <div class="bg-light p-3 rounded mt-3 mb-3"><label class="form-label text-primary">Telegram Bot</label><input type="text" name="telegram_bot_token" class="form-control form-control-sm mb-2" value="<?= htmlspecialchars(getSafeSetting('telegram_bot_token')) ?>" placeholder="Bot Token"><input type="text" name="telegram_chat_id" class="form-control form-control-sm" value="<?= htmlspecialchars(getSafeSetting('telegram_chat_id')) ?>" placeholder="Chat ID"></div>
                    <a href="reset_timetable.php" class="btn btn-outline-danger w-100 rounded-pill btn-sm fw-bold"><i class="bi bi-trash me-2"></i>Reset New Semester</a>
                </div></div></div>
            </div>

            <div class="save-bar" id="saveBar">
                <span class="small fw-bold"><i class="bi bi-pencil-square me-1"></i> Unsaved Changes</span>
                <button type="submit" class="btn btn-light text-dark fw-bold rounded-pill px-4 btn-sm">Save</button>
            </div>
        </form>
    </div>

    <?php include 'menu.php'; ?>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function updateDayVisibility() {
            const count = parseInt(document.getElementById('dayCount').value || "5", 10);
            document.querySelectorAll('.day-input-group').forEach((div, index) => {
                if (index < count) div.classList.remove('day-hidden');
                else div.classList.add('day-hidden');
            });
        }
        updateDayVisibility();

        function useCurrentIp() {
            const ip = "<?= htmlspecialchars($current_ip) ?>";
            const input = document.querySelector('input[name="allowed_ips"]');
            if (!input) return;
            const v = (input.value || '').trim();
            if (v === "") input.value = ip;
            else {
                const parts = v.split(',').map(s => s.trim()).filter(Boolean);
                if (!parts.includes(ip)) parts.push(ip);
                input.value = parts.join(", ");
            }
            triggerDirty();
        }

        let isDirty = false;
        const saveBar = document.getElementById('saveBar');
        function triggerDirty() {
            if (!isDirty) {
                isDirty = true;
                if (saveBar) saveBar.classList.add('show');
            }
        }
        document.addEventListener("DOMContentLoaded", function() {
            document.querySelectorAll('input, select, textarea').forEach(el => {
                el.addEventListener('input', triggerDirty, {passive:true});
                el.addEventListener('change', triggerDirty, {passive:true});
            });
            const form = document.getElementById('settingsForm');
            if (form) form.addEventListener('submit', () => { isDirty = false; });
        });

        // ============================================
        // UPDATE CHECK FUNCTION
        // ============================================
        function checkForUpdates() {
            const resultDiv = document.getElementById('updateCheckResult');
            resultDiv.style.display = 'block';
            resultDiv.innerHTML = `
                <div class="alert alert-info bg-white bg-opacity-25 border-0 text-white mb-0">
                    <div class="spinner-border spinner-border-sm me-2" role="status"></div>
                    Checking for updates...
                </div>
            `;

            fetch('check_updates.php', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success && data.update_available) {
                    resultDiv.innerHTML = `
                        <div class="alert alert-success bg-white border-0 mb-0">
                            <h6 class="mb-2">
                                <i class="bi bi-download me-2 text-success"></i>
                                Update Available: v${data.latest_version}
                            </h6>
                            <p class="small mb-2">${data.title}</p>
                            <span class="badge bg-${data.release_type === 'security' ? 'danger' : data.release_type === 'major' ? 'primary' : 'info'} me-2">
                                ${data.release_type.toUpperCase()}
                            </span>
                            ${data.is_forced ? '<span class="badge bg-danger">CRITICAL</span>' : ''}
                            <div class="mt-3">
                                <a href="#" onclick="showUpdateModal('${data.latest_version}', '${data.file_hash || ''}'); return false;" class="btn btn-success btn-sm me-2">
                                    <i class="bi bi-download me-1"></i>
                                    Install Now
                                </a>
                                <button type="button" class="btn btn-outline-secondary btn-sm" onclick="this.closest('.alert').style.display='none'">
                                    Later
                                </button>
                            </div>
                        </div>
                    `;
                    
                    // Also show floating notification
                    if (typeof showUpdateNotification === 'function') {
                        showUpdateNotification(data);
                    }
                } else if (data.success) {
                    resultDiv.innerHTML = `
                        <div class="alert alert-success bg-white bg-opacity-25 border-0 text-white mb-0">
                            <i class="bi bi-check-circle-fill me-2"></i>
                            You're running the latest version (v${data.current_version})
                        </div>
                    `;
                    setTimeout(() => {
                        resultDiv.style.display = 'none';
                    }, 3000);
                } else {
                    resultDiv.innerHTML = `
                        <div class="alert alert-warning bg-white bg-opacity-25 border-0 text-white mb-0">
                            <i class="bi bi-exclamation-triangle-fill me-2"></i>
                            ${data.message || 'Could not check for updates'}
                        </div>
                    `;
                }
            })
            .catch(error => {
                resultDiv.innerHTML = `
                    <div class="alert alert-danger bg-white bg-opacity-25 border-0 text-white mb-0">
                        <i class="bi bi-x-circle-fill me-2"></i>
                        Connection error. Please check your internet.
                    </div>
                `;
            });
        }

        // Show update installation modal
        function showUpdateModal(version, hash) {
            if (confirm(`Install update v${version}?\n\nThis will:\n✓ Create automatic backup\n✓ Download and install update\n✓ Run database migrations\n✓ Reload the page\n\nContinue?`)) {
                // Use the floating notification's install function if available
                if (typeof startUpdate === 'function') {
                    startUpdate(version, hash);
                } else {
                    // Fallback: direct call to perform_update.php
                    installUpdateDirect(version, hash);
                }
            }
        }
        
        // Fallback update installation function
        function installUpdateDirect(version, hash) {
            console.log('Installing update:', version, hash); // Debug log
            
            if (!version || !hash) {
                alert('❌ Update failed: Missing version or hash information');
                return;
            }
            
            // Show progress in result div
            const resultDiv = document.getElementById('updateCheckResult');
            if (resultDiv) {
                resultDiv.style.display = 'block';
                resultDiv.innerHTML = `
                    <div class="alert alert-info">
                        <div class="spinner-border spinner-border-sm me-2" role="status"></div>
                        Installing update v${version}... Please wait, this may take a few minutes.
                    </div>
                `;
            }
            
            fetch('perform_update.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `version=${encodeURIComponent(version)}&hash=${encodeURIComponent(hash)}`
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                console.log('Update response:', data); // Debug log
                
                if (data.success) {
                    if (resultDiv) {
                        resultDiv.innerHTML = `
                            <div class="alert alert-success">
                                <i class="bi bi-check-circle-fill me-2"></i>
                                Update installed successfully! Updated from ${data.from_version} to ${data.to_version}.
                                <br><small>Page will reload in 3 seconds...</small>
                            </div>
                        `;
                    }
                    
                    setTimeout(() => {
                        window.location.reload();
                    }, 3000);
                } else {
                    if (resultDiv) {
                        resultDiv.innerHTML = `
                            <div class="alert alert-danger">
                                <i class="bi bi-x-circle-fill me-2"></i>
                                Update failed: ${data.message || 'Unknown error'}
                            </div>
                        `;
                    } else {
                        alert(`❌ Update failed: ${data.message || 'Unknown error'}`);
                    }
                }
            })
            .catch(error => {
                console.error('Update error:', error); // Debug log
                
                if (resultDiv) {
                    resultDiv.innerHTML = `
                        <div class="alert alert-danger">
                            <i class="bi bi-x-circle-fill me-2"></i>
                            Update failed: ${error.message}
                        </div>
                    `;
                } else {
                    alert(`❌ Update failed: ${error.message}`);
                }
            });
        }

        // ============================================
        // LICENSE CHECK FUNCTION (Enhanced)
        // ============================================
        function checkLicenseStatus() {
            const resultDiv = document.getElementById('licenseCheckResult');
            resultDiv.style.display = 'block';
            resultDiv.innerHTML = `
                <div class="alert alert-info">
                    <div class="spinner-border spinner-border-sm me-2" role="status"></div>
                    Verifying license and checking for updates...
                </div>
            `;

            // Call the license server to verify
            fetch('check_license_api.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    action: 'check_status'
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    resultDiv.innerHTML = `
                        <div class="alert alert-success alert-dismissible fade show">
                            <button type="button" class="btn-close" onclick="this.parentElement.style.display='none'"></button>
                            <i class="bi bi-check-circle-fill me-2"></i>
                            <strong>License Valid!</strong><br>
                            <small>Status: ${data.status || 'Active'}</small><br>
                            <small>Last verified: Just now</small>
                            ${data.message ? '<br><small>' + data.message + '</small>' : ''}
                        </div>
                    `;
                    
                    // Also check for updates after license verification
                    setTimeout(() => {
                        checkForUpdates();
                    }, 1000);
                    
                    // Reload page after 3 seconds to show updated info
                    setTimeout(() => location.reload(), 3000);
                } else {
                    resultDiv.innerHTML = `
                        <div class="alert alert-warning alert-dismissible fade show">
                            <button type="button" class="btn-close" onclick="this.parentElement.style.display='none'"></button>
                            <i class="bi bi-exclamation-triangle-fill me-2"></i>
                            <strong>Verification Issue</strong><br>
                            <small>${data.message || 'Could not verify license'}</small>
                        </div>
                    `;
                }
            })
            .catch(error => {
                resultDiv.innerHTML = `
                    <div class="alert alert-danger alert-dismissible fade show">
                        <button type="button" class="btn-close" onclick="this.parentElement.style.display='none'"></button>
                        <i class="bi bi-x-circle-fill me-2"></i>
                        <strong>Connection Error</strong><br>
                        <small>Could not connect to license server. Please check your internet connection.</small>
                    </div>
                `;
            });
        }
    </script>
</body>
</html>