<?php
require_once __DIR__ . '/../includes/config.php';

function admin_start(): void {
  if (session_status() === PHP_SESSION_NONE) {
    session_set_cookie_params(['lifetime' => 0, 'httponly' => true, 'samesite' => 'Lax']);
    session_start();
  }
}

function admin_logged_in(): bool {
  admin_start();
  return !empty($_SESSION['admin']);
}

function admin_require(): void {
  if (!admin_logged_in()) {
    header('Location: login.php');
    exit;
  }
}

function admin_login(string $user, string $password): bool {
  admin_start();
  if ($user !== ADMIN_USER) return false;

  $ok = false;
  // Prioriteit aan bcrypt hash (productie)
  if (defined('ADMIN_PASSWORD_HASH') && ADMIN_PASSWORD_HASH !== '') {
    $ok = password_verify($password, ADMIN_PASSWORD_HASH);
  }
  // Fallback: plain demo-wachtwoord
  elseif (defined('ADMIN_PASSWORD') && ADMIN_PASSWORD !== '') {
    $ok = hash_equals(ADMIN_PASSWORD, $password);
  }
  if (!$ok) return false;

  session_regenerate_id(true);
  $_SESSION['admin'] = ['user' => $user, 'since' => time()];
  return true;
}

function admin_logout(): void {
  admin_start();
  $_SESSION = [];
  if (ini_get('session.use_cookies')) {
    $p = session_get_cookie_params();
    setcookie(session_name(), '', time() - 42000, $p['path'], $p['domain'], $p['secure'], $p['httponly']);
  }
  session_destroy();
}
