<?php
session_start();
require_once __DIR__ . '/db.php';
function current_user() { return $_SESSION['user'] ?? null; }
function require_login($roles = []) {
    $user = current_user();
    if (!$user) { header('Location: '.APP_URL.'/login.php'); exit; }
    if ($roles && !in_array($user['role'], $roles, true)) { http_response_code(403); exit('Forbidden'); }
}
function login_user($email, $password): bool {
    $stmt = db()->prepare('SELECT * FROM users WHERE email=? AND status="active" LIMIT 1');
    $stmt->execute([$email]);
    $user = $stmt->fetch();
    if ($user && password_verify($password, $user['password_hash'])) {
        unset($user['password_hash']);
        $_SESSION['user'] = $user;
        return true;
    }
    return false;
}
function logout_user(){ session_destroy(); }
function csrf_token(){ if(empty($_SESSION['csrf'])) $_SESSION['csrf']=bin2hex(random_bytes(32)); return $_SESSION['csrf']; }
function verify_csrf(){ if(($_POST['csrf'] ?? '') !== ($_SESSION['csrf'] ?? '')) { http_response_code(400); exit('Bad CSRF token'); } }
function redirect_dashboard($role){
    if ($role === 'admin') header('Location: '.APP_URL.'/admin/index.php');
    elseif ($role === 'manager') header('Location: '.APP_URL.'/manager/index.php');
    else header('Location: '.APP_URL.'/staff/index.php');
    exit;
}
