<?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 venue_module_boot(): void
{
    require_login();
    require_permission('manage_venues');
}

function venue_status_options(): array
{
    return ['active', 'inactive', 'under_maintenance'];
}

function venue_list(): array
{
    return db_fetch_all(
        'SELECT v.*, COUNT(f.id) AS fixtures_count
         FROM venues v
         LEFT JOIN fixtures f ON f.venue_id = v.id
         GROUP BY v.id
         ORDER BY FIELD(v.status, "active", "under_maintenance", "inactive"), v.name ASC, v.id DESC'
    );
}

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

function find_venue_or_abort(int $venueId): array
{
    $venue = get_venue_by_id($venueId);

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

    return $venue;
}

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

function validate_venue_payload(array $data, array &$errors, ?int $venueId = null): array
{
    validate_required($data, [
        'name' => 'Venue name',
        'location' => 'Location',
        'status' => 'Status',
    ], $errors);
    validate_in_array_field($data, 'status', venue_status_options(), 'Status', $errors);
    validate_numeric_min($data, 'capacity', 'Capacity', 0, $errors);

    $capacity = trim((string) ($data['capacity'] ?? ''));

    $normalized = [
        'name' => trim((string) ($data['name'] ?? '')),
        'location' => trim((string) ($data['location'] ?? '')),
        'capacity' => $capacity === '' ? null : (int) $capacity,
        'pitch_type' => trim((string) ($data['pitch_type'] ?? '')),
        'status' => (string) ($data['status'] ?? 'active'),
    ];

    $query = 'SELECT COUNT(*) FROM venues WHERE name = :name AND location = :location';
    $params = ['name' => $normalized['name'], 'location' => $normalized['location']];

    if ($venueId !== null) {
        $query .= ' AND id <> :id';
        $params['id'] = $venueId;
    }

    if ($normalized['name'] !== '' && $normalized['location'] !== '' && (int) db_fetch_value($query, $params, 0) > 0) {
        $errors['name'] = 'Venue name already exists for this location.';
    }

    return $normalized;
}

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