<?php
// index.php - v9.1: Hardened headers + session bootstrap delegated to db.php
// Security Headers (db.php emits the same set; duplication is harmless and
// guarantees coverage even if db.php fails to load).
header('X-Frame-Options: SAMEORIGIN');
header('X-Content-Type-Options: nosniff');
header('X-XSS-Protection: 1; mode=block');
header('Referrer-Policy: strict-origin-when-cross-origin');
header('Permissions-Policy: geolocation=(), microphone=(), camera=()');

$isHttps = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on')
    || (($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https');
if ($isHttps) {
    header('Strict-Transport-Security: max-age=300');
}
header(
    "Content-Security-Policy-Report-Only: " .
    "default-src 'self'; " .
    "script-src 'self' 'unsafe-inline' 'unsafe-eval' " .
        "https://cdn.jsdelivr.net https://cdnjs.cloudflare.com https://unpkg.com; " .
    "style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; " .
    "img-src 'self' data: blob:; " .
    "font-src 'self' data: https://fonts.gstatic.com; " .
    "frame-ancestors 'none'"
);

// Bot Detection - Block common crawlers
$userAgent = strtolower($_SERVER['HTTP_USER_AGENT'] ?? '');
$blockedBots = ['googlebot', 'bingbot', 'slurp', 'duckduckbot', 'baiduspider', 'yandex', 'sogou', 'exabot', 'facebot', 'ia_archiver', 'crawler', 'spider', 'bot'];
foreach ($blockedBots as $bot) {
    if (strpos($userAgent, $bot) !== false) {
        http_response_code(403);
        die('Access Denied');
    }
}

// Block empty or suspicious user agents
if (empty($userAgent) || preg_match('/^(curl|wget|python|libwww|perl|java|scrapy)/i', $userAgent)) {
    http_response_code(403);
    die('Access Denied');
}

// SameSite standardised to 'Lax' (was 'Strict' here, 'Lax' in db.php). Lax
// allows top-level navigation from external links (e.g. WhatsApp deep links),
// matching the cookie that db.php sets for the active session.
ini_set('session.cookie_httponly', 1);
ini_set('session.use_only_cookies', 1);
ini_set('session.cookie_samesite', 'Lax');
ini_set('session.use_strict_mode', 1);
if ($isHttps) {
    ini_set('session.cookie_secure', 1);
}

session_name('FONFIX_SYSTEM_ID');
session_start();
require 'db.php';

if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
    header('Location: dashboard.php');
    exit;
}

// Rate Limiting - Check login attempts
$ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
$maxAttempts = 5;
$lockoutDuration = 900; // 15 minutes

// Create login_attempts table if it doesn't exist
$pdo->exec("CREATE TABLE IF NOT EXISTS login_attempts (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(100),
    ip_address VARCHAR(45),
    attempt_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    success TINYINT(1) DEFAULT 0,
    INDEX idx_username_time (username, attempt_time),
    INDEX idx_ip_time (ip_address, attempt_time)
) ENGINE=InnoDB");

$error = null;

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Rate limiting check
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM login_attempts 
        WHERE (username = ? OR ip_address = ?) 
        AND attempt_time > DATE_SUB(NOW(), INTERVAL ? SECOND)
        AND success = 0");
    $stmt->execute([$_POST['username'] ?? '', $ip, $lockoutDuration]);
    $failedAttempts = $stmt->fetchColumn();
    
    if ($failedAttempts >= $maxAttempts) {
        // Record failed attempt
        $stmt = $pdo->prepare("INSERT INTO login_attempts (username, ip_address, success) VALUES (?, ?, 0)");
        $stmt->execute([$_POST['username'] ?? '', $ip]);
        $error = "Too many failed login attempts. Please try again in " . round($lockoutDuration / 60) . " minutes.";
    } else {
        $u = trim($_POST['username'] ?? '');
        $p = trim($_POST['password'] ?? '');
        
        // Input validation
        if (empty($u) || empty($p) || strlen($u) > 100 || strlen($p) > 255) {
            $error = "Invalid input.";
        } else {
            try {
                $stmt = $pdo->prepare("SELECT id, username, password, role, assigned_branch, restrict_branch FROM users WHERE username = ? LIMIT 1");
                $stmt->execute([$u]);
                $user = $stmt->fetch(PDO::FETCH_ASSOC);

                if ($user && password_verify($p, $user['password'])) {
                    // Clear failed attempts on successful login
                    $pdo->prepare("DELETE FROM login_attempts WHERE username = ? OR ip_address = ?")->execute([$u, $ip]);
                    
                    // Record successful login
                    $stmt = $pdo->prepare("INSERT INTO login_attempts (username, ip_address, success) VALUES (?, ?, 1)");
                    $stmt->execute([$u, $ip]);
                    
                    session_regenerate_id(true);
                    $_SESSION['loggedin'] = true;
                    $_SESSION['user_id']  = $user['id'];
                    $_SESSION['user']     = ucfirst($user['username']);
                    $_SESSION['role']     = $user['role'];
                    $_SESSION['assigned_branch'] = $user['assigned_branch'] ?? 'Gombak';
                    $_SESSION['restrict_branch'] = ($user['restrict_branch'] == 1);
                    $_SESSION['branch'] = $_SESSION['assigned_branch'];
                    if (empty($_SESSION['csrf_token'])) { $_SESSION['csrf_token'] = bin2hex(random_bytes(32)); }
                    header("Location: dashboard.php");
                    exit;
                } else {
                    // Record failed attempt
                    $stmt = $pdo->prepare("INSERT INTO login_attempts (username, ip_address, success) VALUES (?, ?, 0)");
                    $stmt->execute([$u, $ip]);
                    $error = "Invalid Username or Password.";
                }
            } catch (Exception $e) {
                error_log("Login error: " . $e->getMessage());
                $error = "System Error.";
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Fon2Fix :: LOGIN</title>
    <link rel="icon" type="image/png" href="logo.png">
    <link rel="shortcut icon" type="image/png" href="logo.png">
    <link rel="apple-touch-icon" href="logo.png">
    <link rel="preload" as="image" href="logo.png">
    
    <style>
        /* ROS DESIGN SYSTEM */
        :root {
            --primary: hsl(245 58% 51%);
            --primary-strong: hsl(245 58% 45%);
            --bg: hsl(220 20% 97%);
            --card-bg: #ffffff;
            --text-main: hsl(220 26% 12%);
            --text-muted: hsl(220 12% 46%);
            --border: hsl(220 16% 88%);
            --focus-ring: hsl(245 58% 70% / 0.2);
        }
        body { 
            margin: 0; padding: 0;
            font-family: Inter, 'Segoe UI', Roboto, Helvetica, sans-serif;
            background:
                radial-gradient(circle at 12% 8%, hsl(245 90% 74% / 0.16), transparent 38%),
                radial-gradient(circle at 84% 14%, hsl(197 92% 70% / 0.14), transparent 40%),
                linear-gradient(180deg, hsl(220 34% 98%) 0%, var(--bg) 34%, hsl(220 24% 95%) 100%);
            height: 100vh; 
            display: flex; align-items: center; justify-content: center; 
            color: var(--text-main); 
        }
        
        .login-card { 
            background: linear-gradient(180deg, hsl(0 0% 100% / 0.92) 0%, hsl(0 0% 100% / 0.86) 100%);
            padding: 50px 40px; 
            border-radius: 22px;
            box-shadow: 0 1px 2px hsl(220 20% 20% / 0.05), 0 18px 40px hsl(220 22% 16% / 0.12);
            width: 100%; max-width: 380px; 
            text-align: center; 
            border: 1px solid hsl(220 14% 88% / 0.65);
            backdrop-filter: blur(10px);
        }
        
        .logo { 
            max-width: 220px; 
            width: 100%; /* Ensure it takes space immediately */
            height: auto; 
            display: block; 
            margin: 0 auto 30px auto; 
            transition: transform 0.3s ease;
        }
        .logo:hover { transform: scale(1.05); }

        .input-group { margin-bottom: 20px; text-align: left; }
        
        label { 
            font-size: 0.8rem; 
            color: var(--text-muted); 
            margin-bottom: 8px; 
            display: block; 
            font-weight: 700; 
            letter-spacing: 1px; 
        }
        
        input { 
            width: 100%; 
            padding: 15px; 
            background: #fff;
            border: 1px solid hsl(220 14% 84%);
            border-radius: 12px;
            color: var(--text-main);
            font-size: 16px; 
            box-sizing: border-box; 
            transition: border-color 0.2s ease, box-shadow 0.2s ease;
        }
        
        input:focus { 
            outline: none; 
            border-color: hsl(245 58% 60%);
            background: #fff;
            box-shadow: 0 0 0 4px var(--focus-ring);
        }
        
        button { 
            width: 100%; 
            padding: 15px; 
            margin-top: 15px; 
            background: linear-gradient(180deg, var(--primary) 0%, var(--primary-strong) 100%);
            border: none; 
            border-radius: 12px;
            color: white; 
            font-size: 16px; 
            font-weight: 800; 
            cursor: pointer; 
            text-transform: uppercase; 
            letter-spacing: 1px; 
            box-shadow: 0 14px 28px hsl(245 60% 30% / 0.28);
            transition: transform 0.2s ease, box-shadow 0.2s ease;
        }
        
        button:hover { 
            transform: translateY(-2px) scale(1.01);
            box-shadow: 0 18px 32px hsl(245 60% 28% / 0.34);
        }
        
        .error { 
            color: hsl(350 72% 46%);
            background: hsl(350 80% 97%);
            padding: 12px; 
            border-radius: 12px;
            margin-bottom: 25px; 
            font-size: 0.9rem; 
            border-left: 4px solid hsl(350 72% 54%);
            text-align: left;
        }
        
        .footer-text { 
            margin-top: 30px; 
            color: #aaa; 
            font-size: 0.7rem; 
            text-transform: uppercase; 
            letter-spacing: 1.5px; 
        }
    </style>
</head>
<body>
<div class="login-card">
    <img src="logo.png" alt="Fon2Fix" class="logo" width="220" height="100">
    <?php if($error): ?>
        <div class="error">⚠️ <?php echo htmlspecialchars($error); ?></div>
    <?php endif; ?>
    <form method="POST">
        <div class="input-group">
            <label>USERNAME</label>
            <input type="text" name="username" required autofocus autocomplete="off">
        </div>
        <div class="input-group">
            <label>PASSWORD</label>
            <input type="password" name="password" required>
        </div>
        <button type="submit">LOGIN SYSTEM</button>
    </form>
    <div class="footer-text">Authorized Personnel Only</div>
</div>
</body>
</html>