<?php

declare(strict_types=1);

require_once dirname(__DIR__, 2) . '/core/auth.php';
require_once dirname(__DIR__, 2) . '/core/csrf.php';
require_once dirname(__DIR__, 2) . '/core/validation.php';
require_once dirname(__DIR__, 2) . '/core/audit.php';

function referee_module_boot(): void
{
    require_login();
    require_permission('manage_referees');
}

function referee_status_options(): array
{
    return ['active', 'inactive', 'suspended'];
}

function referee_level_options(): array
{
    return ['elite', 'national', 'state', 'local', 'trainee'];
}

function can_assign_match_referees(): bool
{
    return can('assign_referees');
}

function referee_list(): array
{
    return db_fetch_all(
        'SELECT r.*, COUNT(f.id) AS assignments_count
         FROM referees r
         LEFT JOIN fixtures f ON f.referee_id = r.id
         GROUP BY r.id
         ORDER BY FIELD(r.status, "active", "inactive", "suspended"), r.full_name ASC, r.id DESC'
    );
}

function get_referee_by_id(int $refereeId): ?array
{
    return db_fetch_one('SELECT * FROM referees WHERE id = :id LIMIT 1', ['id' => $refereeId]);
}

function find_referee_or_abort(int $refereeId): array
{
    $referee = get_referee_by_id($refereeId);

    if ($referee === null) {
        abort_request(404, 'Referee not found', 'The requested referee record does not exist.');
    }

    return $referee;
}

function referee_has_dependencies(int $refereeId): bool
{
    return (int) db_fetch_value('SELECT COUNT(*) FROM fixtures WHERE referee_id = :referee_id', ['referee_id' => $refereeId], 0) > 0;
}

function validate_referee_payload(array $data, array &$errors, ?int $refereeId = null): array
{
    validate_required($data, [
        'full_name' => 'Full name',
        'level' => 'Level',
        'status' => 'Status',
    ], $errors);
    validate_email_field($data, 'email', 'Email', $errors);
    validate_phone_field($data, 'phone', 'Phone', $errors);
    validate_in_array_field($data, 'level', referee_level_options(), 'Level', $errors);
    validate_in_array_field($data, 'status', referee_status_options(), 'Status', $errors);

    $normalized = [
        'full_name' => trim((string) ($data['full_name'] ?? '')),
        'phone' => trim((string) ($data['phone'] ?? '')),
        'email' => strtolower(trim((string) ($data['email'] ?? ''))),
        'level' => (string) ($data['level'] ?? 'local'),
        'status' => (string) ($data['status'] ?? 'active'),
    ];

    if ($normalized['email'] !== '' && duplicate_exists('referees', 'email', $normalized['email'], $refereeId)) {
        $errors['email'] = 'Email address already exists.';
    }

    return $normalized;
}

function referee_badge_class(string $status): string
{
    return match ($status) {
        'active' => 'badge-soft-success',
        'inactive' => 'text-bg-light',
        'suspended' => 'badge-soft-danger',
        default => 'text-bg-light',
    };
}
