<?php
function auth_user(): ?array { return $_SESSION['auth_user'] ?? null; }

function auth_require_login(): void
{
    if (!auth_user()) redirect('/public/auth/login.php');
}

function auth_login(array $user): void
{
    $_SESSION['auth_user'] = [
        'id' => $user['id'],
        'username' => $user['username'],
        'role' => $user['role'],
        'employee_id' => $user['employee_id'] ?? null,
        'external_partner_id' => $user['external_partner_id'] ?? null,
        'customer_id' => $user['customer_id'] ?? null,
    ];
}

function auth_logout(): void { unset($_SESSION['auth_user']); }

function auth_post_login_redirect(array $user): string
{
    $role = strtolower(trim((string)($user['role'] ?? '')));

    if (in_array($role, ['admin', 'administrator', 'super_admin', 'owner', 'manager', 'secretary', 'secretariat', 'office'], true)) {
        return '/public/dashboard/index.php';
    }

    if ($role === 'employee') {
        return '/public/employees/my_jobs.php';
    }

    if ($role === 'partner') {
        return '/public/partners/my_jobs.php';
    }

    if ($role === 'customer') {
        return '/public/customers/my_warranties.php';
    }

    return '/public/dashboard/index.php';
}

function auth_current_redirect_path(): string
{
    $user = auth_user();
    if (!$user) {
        return '/public/auth/login.php';
    }
    return auth_post_login_redirect($user);
}
