<?php
session_start();
require_once __DIR__ . '/config.php';


/* =========================
   CONFIG
========================= */
define('MAX_LOGIN_ATTEMPTS', 3);
define('LOGIN_LOCK_TIME', 600); // 10 minutes

$error  = '';
$status = '';

/* =========================
   INIT ATTEMPTS
========================= */
if (!isset($_SESSION['login_attempts'])) {
    $_SESSION['login_attempts'] = 0;
}

/* =========================
   STATUS MESSAGES (NON-BLOCKING)
========================= */
if (isset($_GET['timeout'])) {
    $status = 'Your session expired. Please log in again.';
}

if (isset($_GET['password_changed'])) {
    $status = 'Password changed successfully. Please log in again.';
}

/* =========================
   LOCK CHECK
========================= */
if (
    isset($_SESSION['login_locked_until']) &&
    time() < $_SESSION['login_locked_until']
) {
    $remaining = $_SESSION['login_locked_until'] - time();
    $error = 'Too many failed attempts. Try again in '
           . ceil($remaining / 60) . ' minutes.';
}

/* =========================
   HANDLE LOGIN
========================= */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !$error) {

    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';

    if (
        $username === ADMIN_USER &&
        password_verify($password, ADMIN_PASS_HASH)
    ) {
        // Successful login
        $_SESSION['admin_logged_in'] = true;
        $_SESSION['admin_user'] = $username;
        $_SESSION['LAST_ACTIVITY'] = time();

        // Reset attempts
        $_SESSION['login_attempts'] = 0;
        unset($_SESSION['login_locked_until']);

        // 🔑 Redirect logic (ORDER MATTERS)
        $redirect =
    $_POST['from']
    ?? $_GET['from']
    ?? $_SESSION['post_logout_from']
    ?? 'index.php';

unset($_SESSION['post_logout_from']);


        // Security: internal paths only
        if (!is_string($redirect) || $redirect[0] !== '/') {
            $redirect = 'index.php';
        }

        header('Location: ' . $redirect);
        exit;

    } else {
        // Failed login
        $_SESSION['login_attempts']++;

        if ($_SESSION['login_attempts'] >= MAX_LOGIN_ATTEMPTS) {
            $_SESSION['login_locked_until'] = time() + LOGIN_LOCK_TIME;
            $_SESSION['login_attempts'] = 0;
            $error = 'Too many failed attempts. Login temporarily locked.';
        } else {
            $error = 'Invalid username or password.';
        }
    }
}

/* =========================
   CAPTURE FROM (GET ONLY)
========================= */
$from = $_GET['from'] ?? '';
?>
<link rel="icon" type="image/x-icon" href="icon.png">
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Admin Login</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body{
  margin:0;
  font-family:system-ui,Arial,sans-serif;
  background:#f1f5f9;
  display:flex;
  align-items:center;
  justify-content:center;
  height:100vh;
}
.login-box{
  background:#fff;
  padding:32px;
  border-radius:14px;
  width:340px;
  box-shadow:0 20px 40px rgba(0,0,0,.1);
}
input,button{
  width:100%;
  padding:12px;
  margin:8px 0;
}
button{
  background:#16a34a;
  color:#fff;
  border:0;
  border-radius:8px;
  font-weight:600;
}
.error{
  background:#fee2e2;
  color:#991b1b;
  padding:10px;
  border-radius:8px;
  font-size:.85rem;
}
.status{
  background:#e0f2fe;
  color:#075985;
  padding:10px;
  border-radius:8px;
  font-size:.85rem;
}
</style>
</head>
<body>

<form class="login-box" method="post" autocomplete="off">
  <h2>Admin Login</h2>

  <?php if ($status): ?>
    <div class="status"><?= htmlspecialchars($status) ?></div>
  <?php endif; ?>

  <?php if ($error): ?>
    <div class="error"><?= htmlspecialchars($error) ?></div>
  <?php endif; ?>

  <?php if ($from): ?>
    <input type="hidden" name="from"
           value="<?= htmlspecialchars($from) ?>">
  <?php endif; ?>

  <input type="text" name="username" placeholder="Username" required>
  <input type="password" name="password" placeholder="Password" required>

  <button type="submit">Login</button>
</form>

</body>
</html>