<?php
// File: admin/login.php

ob_start();
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
error_reporting(E_ALL);

require_once '../includes/db_connect.php';
require_once '../includes/security.php';

secureSessionStart();

// Jika sudah login, lempar ke dashboard
if (isset($_SESSION['admin_id']) && validateAdminSession()) {
    header("Location: dashboard.php");
    exit;
}

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Rate limiting: maks 5 percobaan login per 5 menit per IP
    if (!checkRateLimit('admin_login', 5, 300)) {
        $error = "Terlalu banyak percobaan login. Coba lagi dalam 5 menit.";
    } else {
        $username = sanitizeInput($_POST['username'] ?? '', 50);
        $password = $_POST['password'] ?? '';

        try {
            $stmt = $pdo->prepare("SELECT * FROM admin_users WHERE username = ?");
            $stmt->execute([$username]);
            $user = $stmt->fetch();

            if ($user && password_verify($password, $user['password_hash'])) {
                // ✅ Session regeneration — mencegah session fixation
                regenerateSession($user['id'], $user['username']);
                $pdo->prepare("UPDATE admin_users SET last_login = NOW() WHERE id = ?")->execute([$user['id']]);
                ob_end_clean();
                header("Location: dashboard.php");
                exit;
            } else {
                // Delay kecil untuk mencegah timing attack
                usleep(500000); // 0.5 detik
                $error = "Username atau Password salah!";
            }
        } catch (PDOException $e) {
            error_log("Login error: " . $e->getMessage());
            $error = "Terjadi kesalahan sistem. Silakan coba lagi.";
        }
    }
}

ob_end_flush();
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="robots" content="noindex, nofollow">
    <title>Login Admin</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>body { background-color: #f3f4f6; }</style>
</head>
<body class="h-screen flex items-center justify-center">
    <div class="bg-white p-8 rounded-xl shadow-2xl w-full max-w-sm border-t-4 border-red-600 mx-4">
        <div class="text-center mb-8">
            <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-red-100 text-red-600 mb-4">
                <i class="fa-solid fa-car-on text-3xl"></i>
            </div>
            <h1 class="text-2xl font-bold text-gray-800">Admin Login</h1>
            <p class="text-sm text-gray-500 mt-1">Dealer Sales System</p>
        </div>

        <?php if (!empty($error)): ?>
        <div class="bg-red-50 text-red-600 p-3 rounded-lg mb-6 text-sm flex items-center border border-red-100">
            <i class="fa-solid fa-circle-exclamation mr-2 text-lg"></i> <?= htmlspecialchars($error) ?>
        </div>
        <?php endif; ?>

        <form method="POST" autocomplete="off">
            <?= csrfInput() ?>
            <div class="mb-5">
                <label class="block text-gray-700 text-xs font-bold uppercase mb-2 tracking-wider">Username</label>
                <div class="relative">
                    <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-400"><i class="fa-solid fa-user"></i></span>
                    <input type="text" name="username" autocomplete="username"
                           class="w-full pl-10 p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-red-500 outline-none transition"
                           placeholder="Masukkan username" required>
                </div>
            </div>
            <div class="mb-6">
                <div class="flex justify-between items-center mb-2">
                    <label class="block text-gray-700 text-xs font-bold uppercase tracking-wider">Password</label>
                </div>
                <div class="relative">
                    <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-400"><i class="fa-solid fa-lock"></i></span>
                    <input type="password" name="password" autocomplete="current-password"
                           class="w-full pl-10 p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-red-500 outline-none transition"
                           placeholder="••••••••" required>
                </div>
                <div class="text-right mt-2">
                    <a href="forgot_password.php" class="text-xs text-red-600 hover:underline">Lupa Password?</a>
                </div>
            </div>
            <button type="submit" class="w-full bg-red-600 text-white font-bold py-3 px-4 rounded-lg hover:bg-red-700 transition shadow-lg transform hover:-translate-y-0.5">
                Masuk Dashboard <i class="fa-solid fa-arrow-right ml-2"></i>
            </button>
        </form>
        <div class="mt-8 text-center border-t border-gray-100 pt-4">
            <a href="../index.php" class="text-sm text-gray-400 hover:text-gray-600 flex items-center justify-center gap-2">
                <i class="fa-solid fa-house"></i> Kembali ke Website
            </a>
        </div>
    </div>
</body>
</html>
