<?php
// ============================================================
// auth.php — sessions et contrôle d'accès du back-office.
// ============================================================
require_once __DIR__ . '/config.php';

function auth_start(): void {
    if (session_status() !== PHP_SESSION_ACTIVE) {
        session_name('tuina_admin');
        // cookie cohérent http ET https (secure=false), valable sur tout le site
        $https = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
                 || (($_SERVER['SERVER_PORT'] ?? '') == 443)
                 || (($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https');
        session_set_cookie_params([
            'lifetime' => 0,
            'path' => '/',
            'domain' => '',
            'secure' => $https,
            'httponly' => true,
            'samesite' => 'Lax',
        ]);
        session_start();
    }
}

function auth_attempt(string $login, string $pass): bool {
    $db = db();
    $st = $db->prepare('SELECT * FROM utilisateurs WHERE login = ?');
    $st->execute([$login]);
    $u = $st->fetch();
    if ($u && password_verify($pass, $u['mot_de_passe'])) {
        auth_start();
        session_regenerate_id(true);
        $_SESSION['uid'] = $u['id'];
        $_SESSION['login'] = $u['login'];
        $_SESSION['nom'] = $u['nom'];
        return true;
    }
    return false;
}

function auth_check(): bool {
    auth_start();
    return !empty($_SESSION['uid']);
}

function auth_require(): void {
    if (!auth_check()) {
        header('Location: index.php');
        exit;
    }
}

function auth_logout(): void {
    auth_start();
    $_SESSION = [];
    session_destroy();
}

function csrf_token(): string {
    auth_start();
    if (empty($_SESSION['csrf'])) $_SESSION['csrf'] = bin2hex(random_bytes(16));
    return $_SESSION['csrf'];
}
function csrf_check(?string $t): bool {
    auth_start();
    return !empty($t) && hash_equals($_SESSION['csrf'] ?? '', $t);
}
