<?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';
require_once dirname(__DIR__, 2) . '/core/upload.php';
require_once dirname(__DIR__, 2) . '/modules/clubs/helpers.php';

function staff_module_boot(): void
{
    require_login();
    require_permission('manage_club_staff');
}

function staff_role_options(): array
{
    return ['coach', 'assistant_coach', 'doctor', 'physiotherapist', 'manager', 'media_officer'];
}

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

function staff_visible_club_id(): ?int
{
    if (is_club_admin()) {
        return user_club_id();
    }

    $clubId = isset($_GET['club_id']) ? (int) $_GET['club_id'] : 0;
    return $clubId > 0 ? $clubId : null;
}

function staff_list(): array
{
    $clubId = staff_visible_club_id();
    $params = [];
    $sql = 'SELECT cs.*, c.name AS club_name, c.short_name
            FROM club_staff cs
            INNER JOIN clubs c ON c.id = cs.club_id';

    if ($clubId !== null) {
        require_club_scope($clubId);
        $sql .= ' WHERE cs.club_id = :club_id';
        $params['club_id'] = $clubId;
    }

    $sql .= ' ORDER BY cs.created_at DESC, cs.id DESC';

    return db_fetch_all($sql, $params);
}

function get_staff_by_id(int $staffId): ?array
{
    $staff = db_fetch_one(
        'SELECT cs.*, c.name AS club_name, c.short_name
         FROM club_staff cs
         INNER JOIN clubs c ON c.id = cs.club_id
         WHERE cs.id = :id
         LIMIT 1',
        ['id' => $staffId]
    );

    if ($staff !== null) {
        require_club_scope((int) $staff['club_id']);
    }

    return $staff;
}

function find_staff_or_abort(int $staffId): array
{
    $staff = get_staff_by_id($staffId);

    if ($staff === null) {
        abort_request(404, 'Staff member not found', 'The requested club staff record does not exist.');
    }

    return $staff;
}

function validate_staff_payload(array $data, array &$errors, ?array $existingStaff = null): array
{
    validate_required($data, [
        'full_name' => 'Full name',
        'role' => 'Staff role',
        'status' => 'Status',
    ], $errors);
    validate_email_field($data, 'email', 'Email', $errors);
    validate_phone_field($data, 'phone', 'Phone', $errors);
    validate_in_array_field($data, 'role', staff_role_options(), 'Staff role', $errors);
    validate_in_array_field($data, 'status', staff_status_options(), 'Status', $errors);

    $clubId = is_club_admin() ? (int) user_club_id() : (int) ($data['club_id'] ?? 0);

    if ($clubId <= 0 || get_club_by_id($clubId) === null) {
        $errors['club_id'] = 'Selected club is invalid.';
    } else {
        require_club_scope($clubId);
    }

    return [
        'club_id' => $clubId,
        'full_name' => trim((string) ($data['full_name'] ?? '')),
        'role' => (string) ($data['role'] ?? 'coach'),
        'phone' => trim((string) ($data['phone'] ?? '')),
        'email' => strtolower(trim((string) ($data['email'] ?? ''))),
        'status' => (string) ($data['status'] ?? ($existingStaff['status'] ?? 'active')),
    ];
}
