<?php
// Filename: index.php

// ==========================================
// 1. SMART CONFIG CHECK & AUTO-HEAL
// ==========================================
$config_file = __DIR__ . '/config.php';
$setup_file  = __DIR__ . '/setup.php';

// Logic: If config is missing OR if it crashes (e.g., wrong paths), go to setup.
if (!file_exists($config_file)) {
    if (file_exists($setup_file)) {
        header("Location: setup.php");
        exit;
    } else {
        die('<h1>System Error</h1><p>Configuration file <b>config.php</b> is missing, and <b>setup.php</b> was not found.</p>');
    }
}

try {
    // Attempt to load config. If it has old paths (open_basedir error), it throws a Throwable.
    require_once $config_file;
} catch (Throwable $e) {
    // Catch the crash and redirect to installer to fix the bad config
    if (file_exists($setup_file)) {
        header("Location: setup.php");
        exit;
    }
    // If setup.php is missing, show the actual error
    die("<h1>Configuration Error</h1><p>Your config.php file is corrupt or contains invalid paths.</p><p>Error: " . htmlspecialchars($e->getMessage()) . "</p>");
}

// --- 0. FORCE NO CACHE ---
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");

// --- ENHANCED SECURITY HEADERS ---
header("X-Frame-Options: DENY");
header("X-XSS-Protection: 1; mode=block");
header("X-Content-Type-Options: nosniff");
header("Referrer-Policy: strict-origin-when-cross-origin");

// --- 2. SETTINGS ---
$s_name = getSetting('school_name', 'School Attendance');
$s_logo = getSetting('school_logo', '');
$s_info = getSetting('school_info', 'Secure Portal');
$maint_mode = getSetting('maintenance_mode', '0');
$maint_msg = getSetting('maintenance_message', 'System maintenance in progress.');
$reg_enabled = getSetting('teacher_registration', '0');
$public_enabled = getSetting('public_portal_enabled', '0'); 

$error = '';
$show_login = true;

// --- ENHANCED: Get visitor IP ---
function getClientIP() {
    $ip = $_SERVER['REMOTE_ADDR'];
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ips = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $ip = trim($ips[0]); 
    } elseif (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    }
    return filter_var($ip, FILTER_VALIDATE_IP) ? $ip : $_SERVER['REMOTE_ADDR'];
}
$visitor_ip = getClientIP();

// --- ENHANCED: Security Logging ---
function logSecurityEvent($pdo, $event_type, $username, $ip_address, $details = '') {
    try {
        $stmt = $pdo->prepare("INSERT INTO security_logs (event_type, username, ip_address, details, created_at) VALUES (?, ?, ?, ?, NOW())");
        $stmt->execute([$event_type, $username, $ip_address, $details]);
    } catch (PDOException $e) { 
        // Silent fail if table missing (during install)
    }
}

// --- ENHANCED: Rate Limiting ---
function checkIPRateLimit($pdo, $ip_address) {
    try {
        $stmt = $pdo->prepare("SELECT COUNT(*) as attempts FROM security_logs WHERE ip_address = ? AND event_type = 'failed_login' AND created_at > DATE_SUB(NOW(), INTERVAL 15 MINUTE)");
        $stmt->execute([$ip_address]);
        $result = $stmt->fetch();
        if ($result && $result['attempts'] >= 10) {
            return ['blocked' => true, 'message' => 'Too many failed attempts from your network. Please try again later.'];
        }
    } catch (Exception $e) { /* Ignore if table missing */ }
    return ['blocked' => false];
}

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

// --- UPDATED: MAINTENANCE MODE CHECK ---
if ($maint_mode == '1') {
    // Allow login if:
    // 1. User is already logged in as Admin
    // 2. User is submitting the login form (POST)
    // 3. User explicitly requests admin login via URL (?mode=login)
    $is_admin = isset($_SESSION['role']) && $_SESSION['role'] === 'admin';
    $is_posting = $_SERVER['REQUEST_METHOD'] === 'POST';
    $force_login = isset($_GET['mode']) && $_GET['mode'] === 'login';

    if (!$is_admin && !$is_posting && !$force_login) {
        $show_login = false;
    }
}

// --- 3. HANDLE LOGIN ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $post_token = $_POST['csrf_token'] ?? '';
    $sess_token = $_SESSION['csrf_token'] ?? '';

    if (empty($post_token) || !hash_equals($sess_token, $post_token)) {
        $error = "Security validation failed. Please refresh.";
        logSecurityEvent($pdo, 'csrf_failure', '', $visitor_ip, 'Invalid CSRF token');
    } else {
        $ipCheck = checkIPRateLimit($pdo, $visitor_ip);
        if ($ipCheck['blocked']) {
            $error = $ipCheck['message'];
            logSecurityEvent($pdo, 'ip_rate_limit', '', $visitor_ip, 'IP blocked');
        } else {
            $username = preg_replace('/[^0-9]/', '', trim($_POST['username']));
            $password = $_POST['password'];

            if (!empty($username) && !empty($password)) {
                $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
                $stmt->execute([$username]);
                $user = $stmt->fetch();

                if (!$user) {
                    password_verify($password, '$2y$10$dummyhashtopreventtimingattacksxxxxxxxxxxxxxxxxxxxxxxxxxx');
                    $error = "Invalid credentials. Please try again.";
                    logSecurityEvent($pdo, 'failed_login', $username, $visitor_ip, 'User not found');
                } else {
                    $current_time = date('Y-m-d H:i:s');
                    if (!empty($user['lockout_until']) && $user['lockout_until'] > $current_time) {
                        $wait = ceil((strtotime($user['lockout_until']) - time()) / 60);
                        $error = "Account temporarily locked. Please try again in $wait minute(s).";
                        logSecurityEvent($pdo, 'locked_attempt', $username, $visitor_ip, "Account locked");
                    } else {
                        if (password_verify($password, $user['password'])) {
                            $pdo->prepare("UPDATE users SET failed_attempts = 0, lockout_until = NULL, last_login = NOW() WHERE id = ?")->execute([$user['id']]);
                            
                            // Check maintenance mode for specific user role
                            if ($maint_mode == '1' && $user['role'] !== 'admin') {
                                $error = "System is under maintenance. Only administrators can log in.";
                                logSecurityEvent($pdo, 'maintenance_block', $username, $visitor_ip, 'Non-admin blocked');
                                $show_login = true; // Keep form visible to show error
                            } else {
                                session_regenerate_id(true);
                                if (isset($_POST['remember_me'])) {
                                    $params = session_get_cookie_params();
                                    setcookie(session_name(), session_id(), time() + (30 * 24 * 60 * 60), $params["path"], $params["domain"], $params["secure"], $params["httponly"]);
                                }
                                $_SESSION['user_id'] = $user['id'];
                                $_SESSION['full_name'] = $user['full_name'];
                                $_SESSION['role'] = $user['role'];
                                $_SESSION['avatar'] = $user['avatar'];
                                $_SESSION['layout_mode'] = $user['layout_mode'] ?? 'right';
                                $_SESSION['login_time'] = time();
                                $_SESSION['login_ip'] = $visitor_ip;
                                logSecurityEvent($pdo, 'successful_login', $username, $visitor_ip, "Role: {$user['role']}");
                                
                                if ($user['role'] === 'teacher' && empty(trim($user['subjects'] ?? ''))) {
                                    header("Location: profile.php?mode=onboarding");
                                    exit;
                                }
                                if (strpos($user['role'], 'form6_teacher') !== false) {
                                    header("Location: form6_dashboard.php");
                                    exit;
                                }
                                if (strpos($user['role'], 'akp') !== false) {
                                    header("Location: akp_dashboard.php");
                                    exit;
                                }
                                header("Location: dashboard.php");
                                exit;
                            }
                        } else {
                            $new_attempts = ($user['failed_attempts'] ?? 0) + 1;
                            if ($new_attempts >= 5) {
                                $lockout = date('Y-m-d H:i:s', strtotime('+15 minutes'));
                                $pdo->prepare("UPDATE users SET failed_attempts = ?, lockout_until = ? WHERE id = ?")->execute([$new_attempts, $lockout, $user['id']]);
                                $error = "Too many failed attempts. Account locked for 15 minutes.";
                                logSecurityEvent($pdo, 'account_locked', $username, $visitor_ip, "Locked");
                            } else {
                                $pdo->prepare("UPDATE users SET failed_attempts = ? WHERE id = ?")->execute([$new_attempts, $user['id']]);
                                $remaining = 5 - $new_attempts;
                                $error = "Invalid credentials. $remaining attempt(s) remaining.";
                                logSecurityEvent($pdo, 'failed_login', $username, $visitor_ip, "Failed attempt $new_attempts");
                            }
                        }
                    }
                }
            } else {
                $error = "Please fill in all required fields.";
            }
        }
    }
    // Ensure form stays visible if there was an error
    if ($maint_mode == '1' && $error) {
        $show_login = true;
    }
}
?>
<!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">
    
    <link rel="preload" href="/assets/fonts/PlusJakartaSans-Regular.woff2" as="font" type="font/woff2" crossorigin>
    <link rel="preload" href="/assets/fonts/PlusJakartaSans-SemiBold.woff2" as="font" type="font/woff2" crossorigin>

    <link rel="manifest" href="/manifest.json">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="default">
    <meta name="apple-mobile-web-app-title" content="SAS">
    <title><?= htmlspecialchars($s_name) ?></title>

    <style>
        @font-face {
            font-family: 'Plus Jakarta Sans';
            src: url('/assets/fonts/PlusJakartaSans-Regular.woff2') format('woff2');
            font-weight: 400; font-style: normal; font-display: swap;
        }
        @font-face {
            font-family: 'Plus Jakarta Sans';
            src: url('/assets/fonts/PlusJakartaSans-Medium.woff2') format('woff2');
            font-weight: 500; font-style: normal; font-display: swap;
        }
        @font-face {
            font-family: 'Plus Jakarta Sans';
            src: url('/assets/fonts/PlusJakartaSans-SemiBold.woff2') format('woff2');
            font-weight: 600; font-style: normal; font-display: swap;
        }
        @font-face {
            font-family: 'Plus Jakarta Sans';
            src: url('/assets/fonts/PlusJakartaSans-Bold.woff2') format('woff2');
            font-weight: 700; font-style: normal; font-display: swap;
        }

        :root { --primary-grad: <?= getHeaderTheme() ?>; --bg-color: #f8f9fd; --text-dark: #1e293b; --text-gray: #64748b; }
        body { font-family: 'Plus Jakarta Sans', system-ui, -apple-system, sans-serif; background-color: var(--bg-color); min-height: 100vh; display: flex; flex-direction: column; margin: 0; }
        .login-header { background: var(--primary-grad); height: 45vh; border-radius: 0 0 40px 40px; display: flex; flex-direction: column; align-items: center; justify-content: center; color: white; padding-bottom: 60px; position: relative; }
        .brand-logo { margin-bottom: 15px; display: flex; align-items: center; justify-content: center; }
        .brand-logo img { width: 75px; height: 75px; object-fit: contain; }
        .brand-logo i { font-size: 75px; color: white; }
        .login-card { background: white; margin: -80px 25px 0 25px; border-radius: 24px; padding: 30px 25px; box-shadow: 0 20px 40px rgba(0,0,0,0.08); position: relative; z-index: 10; }
        .form-label { font-size: 0.75rem; font-weight: 700; color: var(--text-gray); text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 8px; }
        .input-group-custom { background: #f1f5f9; border-radius: 16px; padding: 4px; display: flex; align-items: center; border: 1px solid transparent; transition: all 0.2s; }
        .input-group-custom:focus-within { background: white; border-color: #8B5CF6; box-shadow: 0 0 0 3px rgba(139, 92, 246, 0.1); }
        .input-icon { width: 40px; text-align: center; color: #94a3b8; font-size: 1.1rem; }
        .form-control-custom { border: none; background: transparent; width: 100%; padding: 12px 10px 12px 0; font-size: 0.95rem; color: var(--text-dark); outline: none; }
        .form-control-custom::placeholder { color: #cbd5e1; }
        .btn-primary-custom { background: var(--primary-grad); border: none; width: 100%; padding: 14px; border-radius: 16px; color: white; font-weight: 700; font-size: 1rem; box-shadow: 0 10px 20px rgba(99, 102, 241, 0.2); transition: transform 0.2s; }
        .btn-primary-custom:active { transform: scale(0.98); opacity: 0.9; }
        .footer-text { text-align: center; margin-top: 30px; color: #94a3b8; font-size: 0.75rem; padding-bottom: 20px; }
        .maintenance-box { text-align: center; padding: 20px 0; }
        .maint-icon { font-size: 3rem; color: #f59e0b; margin-bottom: 10px; animation: float 3s ease-in-out infinite; }
        @keyframes float { 0% { transform: translateY(0px); } 50% { transform: translateY(-10px); } 100% { transform: translateY(0px); } }
        .security-badge { display: inline-flex; align-items: center; gap: 5px; background: #f0fdf4; color: #166534; padding: 4px 12px; border-radius: 20px; font-size: 0.7rem; font-weight: 600; margin-top: 10px; }
        .form-check-input:checked { background-color: #8B5CF6; border-color: #8B5CF6; }
        
        /* Modal Customization */
        .modal-content { border-radius: 24px; border: none; }
        .modal-header { border-radius: 24px 24px 0 0; }
        .modal-body ul li { margin-bottom: 5px; }
    </style>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css" media="print" onload="this.media='all'">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
</head>
<body>
    <div class="login-header">
        <div class="brand-logo">
            <?php if($s_logo && file_exists($s_logo)): ?>
                <img src="<?= htmlspecialchars($s_logo) ?>" alt="Logo">
            <?php else: ?>
                <i class="bi bi-mortarboard-fill"></i>
            <?php endif; ?>
        </div>
        <h4 class="fw-bold mb-0"><?= htmlspecialchars($s_name) ?></h4>
        <div class="opacity-75 small"><?= htmlspecialchars($s_info) ?></div>
    </div>

    <div class="login-card">
        <?php if ($show_login): ?>
            <h5 class="fw-bold text-dark text-center mb-4">Welcome Back!</h5>
            <?php if($error): ?>
                <div class="alert alert-danger border-0 bg-danger-subtle text-danger text-center p-2 rounded-3 small mb-4 fw-bold">
                    <i class="bi bi-exclamation-circle-fill me-1"></i> <?= htmlspecialchars($error) ?>
                </div>
            <?php endif; ?>
            <form method="POST" autocomplete="off">
                <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token'] ?? '') ?>">
                
                <div class="mb-3">
                    <label class="form-label">IC Number</label>
                    <div class="input-group-custom">
                        <div class="input-icon"><i class="bi bi-person"></i></div>
                        <input type="tel" name="username" class="form-control-custom" placeholder="e.g. 900101105566" required maxlength="12" oninput="this.value = this.value.replace(/[^0-9]/g, '').slice(0, 12);" autocomplete="off">
                    </div>
                </div>
                <div class="mb-3">
                    <label class="form-label">Password</label>
                    <div class="input-group-custom">
                        <div class="input-icon"><i class="bi bi-lock"></i></div>
                        <input type="password" name="password" id="passInput" class="form-control-custom" placeholder="••••••••" required autocomplete="off">
                        <div class="input-icon" onclick="togglePass()" style="cursor:pointer;"><i class="bi bi-eye-slash" id="passIcon"></i></div>
                    </div>
                </div>
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" name="remember_me" id="rememberMe">
                        <label class="form-check-label small text-muted fw-bold" for="rememberMe">Remember Me</label>
                    </div>
                    <a href="forgot_password.php" class="small text-decoration-none fw-bold" style="color: #8B5CF6;">Forgot Password?</a>
                </div>
                <button type="submit" class="btn-primary-custom mb-3">Sign In <i class="bi bi-arrow-right ms-2 small"></i></button>
                <?php if ($public_enabled === '1'): ?>
                <div class="text-center mt-3"><a href="public.php" class="btn btn-light w-100 rounded-pill fw-bold border text-primary" style="padding: 12px;"><i class="bi bi-globe2 me-2"></i> Public Portal</a></div>
                <?php endif; ?>
                <?php if($reg_enabled == '1'): ?>
                    <div class="text-center mt-3"><a href="register.php" class="text-decoration-none fw-bold small" style="color: #8B5CF6;">Create New Account</a></div>
                <?php endif; ?>
            </form>
        <?php else: ?>
            <div class="maintenance-box">
                <div class="maint-icon"><i class="bi bi-cone-striped"></i></div>
                <h5 class="fw-bold text-dark">Under Maintenance</h5>
                <p class="text-muted small mb-4"><?= nl2br(htmlspecialchars($maint_msg)) ?></p>
                
                <button onclick="location.reload()" class="btn btn-light rounded-pill border fw-bold px-4 btn-sm mb-3">Check Status</button>
                
                <div class="mt-3 small text-muted">
                    <i class="bi bi-lock me-1"></i> 
                    <a href="?mode=login" class="text-decoration-none text-muted fw-bold">Administrator Login</a>
                </div>
            </div>
        <?php endif; ?>
    </div>

    <div class="footer-text">
        <div class="mb-1"><i class="bi bi-shield-check me-1"></i> Secure Attendance System <span class="security-badge"><i class="bi bi-lock-fill"></i> HTTPS Protected</span></div>
        <div class="mb-2">
            <a href="#" class="text-decoration-none small text-muted fw-bold me-2" data-bs-toggle="modal" data-bs-target="#privacyModal">Privacy Policy</a>
        </div>
        <div class="opacity-50">Version 2.1 &copy; <?= date('Y') ?></div>
    </div>

    <div class="modal fade" id="privacyModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
            <div class="modal-content border-0 shadow">
                <div class="modal-header border-bottom-0 pb-0">
                    <h5 class="modal-title fw-bold text-dark"><i class="bi bi-shield-lock me-2 text-primary"></i>Privacy Policy</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body text-secondary small pt-3">
                    <div class="alert alert-light border rounded-3 mb-3">
                        <strong><?= htmlspecialchars($s_name) ?></strong> respects your privacy. This system collects only the data necessary for school administration.
                    </div>

                    <h6 class="fw-bold text-dark">1. Data Collection</h6>
                    <p class="mb-2">We collect specific personal information including:</p>
                    <ul class="ps-3 mb-3">
                        <li><strong>IC Number & Name:</strong> For identification and official records.</li>
                        <li><strong>Phone Number:</strong> For emergency contact and notifications.</li>
                        <li><strong>Attendance Data:</strong> Clock-in/out times and locations (if GPS enabled).</li>
                    </ul>

                    <h6 class="fw-bold text-dark">2. Purpose of Use</h6>
                    <p class="mb-3">This data is used strictly for recording daily attendance, generating administrative reports for the Ministry (MOE), and identity verification.</p>

                    <h6 class="fw-bold text-dark">3. Data Security</h6>
                    <p class="mb-3">Your password is encrypted using robust hashing algorithms (bcrypt). Access to the database is restricted to authorized school administrators only.</p>

                    <h6 class="fw-bold text-dark">4. Cookies</h6>
                    <p class="mb-0">We use secure session cookies to keep you logged in. No third-party tracking or advertising cookies are used.</p>
                </div>
                <div class="modal-footer border-top-0 pt-0">
                    <button type="button" class="btn btn-light rounded-pill fw-bold w-100" data-bs-dismiss="modal">I Understand</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function togglePass() {
            const input = document.getElementById('passInput');
            const icon = document.getElementById('passIcon');
            if (input.type === 'password') { input.type = 'text'; icon.classList.replace('bi-eye-slash', 'bi-eye'); } 
            else { input.type = 'password'; icon.classList.replace('bi-eye', 'bi-eye-slash'); }
        }
        if (window.history.replaceState) { window.history.replaceState(null, null, window.location.href); }
    </script>
</body>
</html>