<?php

declare(strict_types=1);

function users_headers(): array
{
    return ['id', 'name', 'surname', 'email', 'password_hash', 'role', 'created_at', 'updated_at'];
}

function businesses_headers(): array
{
    return ['id', 'name', 'address', 'description', 'lat', 'lng', 'image_url', 'icon_url', 'avg_rating', 'pin_color'];
}

function subscriptions_headers(): array
{
    return ['user_id', 'business_id', 'created_at'];
}

function business_accounts_headers(): array
{
    return ['id', 'business_id', 'email', 'password_hash', 'created_at', 'updated_at'];
}

function current_user(): ?array
{
    $userId = $_SESSION['user_id'] ?? null;
    if (!is_string($userId) || $userId === '') {
        return null;
    }

    $users = csv_read_assoc(USERS_CSV, users_headers());
    $user = csv_find_one($users, fn($u) => ($u['id'] ?? '') === $userId);

    return $user;
}

function is_logged_in(): bool
{
    return current_user() !== null;
}

function require_login_json(): array
{
    $user = current_user();
    if ($user === null) {
        fail('Unauthorized', 401);
    }
    return $user;
}

function require_admin_json(): array
{
    $user = require_login_json();
    $role = strtolower(trim((string)($user['role'] ?? '')));
    if ($role !== ADMIN_ROLE_NAME) {
        fail('Forbidden (admin only)', 403);
    }
    return $user;
}

function set_session_user_id(string $userId): void
{
    $_SESSION['user_id'] = $userId;
}

function logout_user(): void
{
    $_SESSION = [];
    if (session_status() === PHP_SESSION_ACTIVE) {
        session_destroy();
    }
}

function public_user_fields(array $user): array
{
    return [
        'name' => (string)($user['name'] ?? ''),
        'surname' => (string)($user['surname'] ?? ''),
        'email' => (string)($user['email'] ?? ''),
        'role' => (string)($user['role'] ?? ''),
    ];
}

function business_session(): ?array
{
    $businessId = $_SESSION['business_id'] ?? null;
    $accountId = $_SESSION['business_account_id'] ?? null;
    if (!is_string($businessId) || $businessId === '' || !is_string($accountId) || $accountId === '') {
        return null;
    }

    $accounts = csv_read_assoc(DATA_DIR . '/business_accounts.csv', business_accounts_headers());
    $acc = csv_find_one($accounts, fn($a) => (string)($a['id'] ?? '') === $accountId && (string)($a['business_id'] ?? '') === $businessId);
    if ($acc === null) {
        return null;
    }

    return $acc;
}

function set_business_session(string $accountId, string $businessId): void
{
    $_SESSION['business_account_id'] = $accountId;
    $_SESSION['business_id'] = $businessId;
}

function logout_business(): void
{
    unset($_SESSION['business_account_id']);
    unset($_SESSION['business_id']);
}
