<?php
declare(strict_types=1);

$secureCookie = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off');

session_name('SCARUSSESSID');
ini_set('session.use_strict_mode', '1');
ini_set('session.use_only_cookies', '1');
ini_set('session.cookie_httponly', '1');
ini_set('session.cookie_secure', $secureCookie ? '1' : '0');
ini_set('session.cookie_samesite', 'Lax');

session_set_cookie_params([
    'lifetime' => 0,
    'path' => '/',
    'domain' => '',
    'secure' => $secureCookie,
    'httponly' => true,
    'samesite' => 'Lax',
]);

session_start();

$expectedPassword = '18032012';
$error = false;

function clientFingerprint(): string
{
    $ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
    $ip = $_SERVER['REMOTE_ADDR'] ?? '';
    return hash('sha256', $ua . '|' . $ip);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $password = isset($_POST['password']) ? trim((string) $_POST['password']) : '';

    if (hash_equals($expectedPassword, $password)) {
        session_regenerate_id(true);

        $_SESSION['scarus_auth'] = true;
        $_SESSION['created_at'] = time();
        $_SESSION['last_activity'] = time();
        $_SESSION['last_regeneration'] = time();
        $_SESSION['fingerprint'] = clientFingerprint();

        header('Location: home.php', true, 302);
        exit;
    }

    $error = true;
}
?><!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Scarus</title>
  <link rel="stylesheet" href="assets/css/style.css">
</head>
<body class="login-body">
  <main class="login-shell">
    <form method="post" class="password-form<?php echo $error ? ' is-error' : ''; ?>" autocomplete="off">
      <input type="password" name="password" aria-label="Mot de passe" autofocus required>
      <button type="submit" hidden aria-hidden="true"></button>
    </form>
  </main>
</body>
</html>
