<?php

require_once __DIR__ . '/../db/config.php';

function login($email, $password) {
    $pdo = db();
    $stmt = $pdo->prepare('SELECT * FROM users WHERE email = ? AND is_active = 1');
    $stmt->execute([$email]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($user && password_verify($password, $user['password_hash'])) {
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['user_role'] = $user['role'];
        if (isset($user['client_id'])) {
            $_SESSION['client_id'] = $user['client_id'];
        }
        return $user['role'];
    }
    return false;
}

function logout() {
    session_unset();
    session_destroy();
}

function is_logged_in() {
    return isset($_SESSION['user_id']);
}

function get_user_role() {
    return $_SESSION['user_role'] ?? null;
}

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

function require_role($role) {
    require_login();
    $user_role = get_user_role();
    if (is_array($role)) {
        if (!in_array($user_role, $role)) {
            http_response_code(403);
            die('Forbidden');
        }
    } else {
        if ($user_role !== $role) {
            http_response_code(403);
            die('Forbidden');
        }
    }
}

function require_admin() {
    require_role('admin');
}
