<?php
require_once __DIR__ . '/helpers.php';

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

function login_user(array $user): void
{
    session_regenerate_id(true);
    $_SESSION['user'] = [
        'id' => $user['id'],
        'name' => $user['name'],
        'email' => $user['email'],
        'role' => $user['role'],
    ];
}

function logout_user(): 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 is_logged_in(): bool
{
    return !empty($_SESSION['user']);
}

function current_user(): ?array
{
    return $_SESSION['user'] ?? null;
}

function require_role(array $roles, string $loginPath): void
{
    if (!is_logged_in()) {
        flash_message('error', 'Silakan login terlebih dahulu.');
        redirect(base_url($loginPath));
    }

    $user = current_user();
    $userRole = $user['role'] ?? null;
    if (!in_array($userRole, $roles, true)) {
        flash_message('error', 'Akses tidak diizinkan.');
        redirect(base_url($loginPath));
    }
}

function require_login(?string $role = null): void
{
    if (!is_logged_in()) {
        flash_message('error', 'Silakan login terlebih dahulu.');
        redirect(base_url('pages/login.php'));
    }

    if ($role !== null) {
        $user = current_user();
        $userRole = $user['role'] ?? null;
        if ($userRole !== $role) {
            flash_message('error', 'Akses tidak diizinkan.');
            redirect(base_url('pages/login.php'));
        }
    }
}

function require_customer(): void
{
    require_role(['customer'], 'pages/login.php');
}

function require_admin(): void
{
    require_role(['admin'], 'admin/user_login.php');
}

function require_owner_or_admin(): void
{
    require_role(['owner', 'admin'], 'admin/user_login.php');
}

function require_owner(): void
{
    require_role(['owner'], 'admin/user_login.php');
}
