<?php
// includes/auth.php
require_once __DIR__ . '/db.php';

function app_config(): array { return require __DIR__ . '/config.php'; }

function start_session(): void {
  $cfg = app_config();
  if (session_status() === PHP_SESSION_NONE) {
    session_name($cfg['app']['session_name']);
    session_set_cookie_params([
      'lifetime' => 0,
      'path' => '/',
      'secure' => (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off'),
      'httponly' => true,
      'samesite' => 'Lax',
    ]);
    session_start();
  }
}

function current_user(): ?array {
  start_session();
  if (empty($_SESSION['uid'])) return null;
  $pdo = db();
  $st = $pdo->prepare("SELECT id,email,display_name,created_at FROM users WHERE id=?");
  $st->execute([$_SESSION['uid']]);
  $u = $st->fetch();
  return $u ?: null;
}

function require_login(): array {
  $u = current_user();
  if (!$u) {
    header("Location: /login.php");
    exit;
  }
  return $u;
}

function csrf_token(): string {
  start_session();
  if (empty($_SESSION['csrf'])) $_SESSION['csrf'] = bin2hex(random_bytes(16));
  return $_SESSION['csrf'];
}

function csrf_check(): void {
  start_session();
  $sent = $_POST['csrf'] ?? ($_SERVER['HTTP_X_CSRF_TOKEN'] ?? '');
  if (!$sent || empty($_SESSION['csrf']) || !hash_equals($_SESSION['csrf'], $sent)) {
    http_response_code(403);
    echo "Forbidden (CSRF)";
    exit;
  }
}

function h($s): string { return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
