<?php
// includes/auth.php - procedural auth helpers (DB-backed)

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/db.php';

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

function require_login() {
    if (!is_logged_in()) {
        header('Location: /admin/login.php');
        exit;
    }
}

function attempt_login(string $username, string $password): bool {
    $db = get_db();
    $stmt = $db->prepare('SELECT * FROM admins WHERE username = :u LIMIT 1');
    $stmt->execute([':u' => $username]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($row && password_verify($password, $row['password'])) {
        $_SESSION['admin_logged_in'] = true;
        $_SESSION['admin_user'] = $username;
        $_SESSION['admin_id'] = $row['id'];
        return true;
    }
    return false;
}

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

function create_admin_if_not_exists(string $username, string $password) {
    $db = get_db();
    $stmt = $db->prepare('SELECT id FROM admins WHERE username = :u');
    $stmt->execute([':u' => $username]);
    if ($stmt->fetch()) return;
    $hash = password_hash($password, PASSWORD_DEFAULT);
    $ins = $db->prepare('INSERT INTO admins (username,password) VALUES (:u,:p)');
    $ins->execute([':u' => $username, ':p' => $hash]);
}

?>