<?php
session_start();

require_once __DIR__ . '/db.php';

function require_login($required_role = null) {
    if (empty($_SESSION['user_id']) || empty($_SESSION['role'])) {
        $_SESSION['redirect_after_login'] = $_SERVER['REQUEST_URI'];
        header('Location: ' . BASE_URL . '/login.php');
        exit;
    }

    if ($required_role && $_SESSION['role'] !== $required_role && $_SESSION['role'] !== 'admin') {
        http_response_code(403);
        die('Access denied');
    }
}

function get_user() {
    global $conn;

    if (empty($_SESSION['user_id'])) {
        return null;
    }

    $stmt = $conn->prepare('SELECT id, username, email, role, company_name FROM users WHERE id = ? AND is_active = 1');
    $stmt->bind_param('i', $_SESSION['user_id']);
    $stmt->execute();
    $result = $stmt->get_result();
    $user = $result->fetch_assoc();
    $stmt->close();

    return $user;
}

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

function get_role() {
    return $_SESSION['role'] ?? 'guest';
}
