<?php
declare(strict_types=1);

namespace App\Modules\SportsActivity\Services;

use App\Core\App;
use App\Core\EventBus;

final class WaitlistAutoOfferService
{
    public static function offerNextInLine(int $groupId): ?array
    {
        $db = App::getInstance()->db();

        $group = $db->selectOne(
            "SELECT id, name_ar, current_count, max_capacity FROM sa_groups WHERE id = ? AND status = 'active'",
            [$groupId]
        );

        if (!$group) {
            return null;
        }

        if ((int) $group['current_count'] >= (int) $group['max_capacity']) {
            return null;
        }

        $next = $db->selectOne(
            "SELECT w.*, p.full_name_ar, p.phone, p.guardian_phone
             FROM sa_waitlist w
             INNER JOIN sa_players p ON p.id = w.player_id
             WHERE w.group_id = ? AND w.status = 'waiting'
             ORDER BY w.position ASC, w.created_at ASC
             LIMIT 1",
            [$groupId]
        );

        if (!$next) {
            return null;
        }

        $now = date('Y-m-d H:i:s');
        $expiresAt = date('Y-m-d H:i:s', strtotime('+48 hours'));

        $db->update('sa_waitlist', [
            'status'     => 'offered',
            'offered_at' => $now,
            'expires_at' => $expiresAt,
            'updated_at' => $now,
        ], 'id = ?', [(int) $next['id']]);

        $phone = $next['guardian_phone'] ?: ($next['phone'] ?? '');

        EventBus::dispatch('sa.waitlist.offer', [
            'waitlist_id'  => (int) $next['id'],
            'player_id'    => (int) $next['player_id'],
            'player_name'  => $next['full_name_ar'],
            'group_id'     => $groupId,
            'group_name'   => $group['name_ar'],
            'phone'        => $phone,
            'expires_at'   => $expiresAt,
        ]);

        return [
            'offered_to'  => (int) $next['player_id'],
            'player_name' => $next['full_name_ar'],
            'waitlist_id' => (int) $next['id'],
            'expires_at'  => $expiresAt,
        ];
    }

    public static function acceptOffer(int $waitlistId): array
    {
        $db = App::getInstance()->db();

        $entry = $db->selectOne(
            "SELECT * FROM sa_waitlist WHERE id = ? AND status = 'offered'",
            [$waitlistId]
        );

        if (!$entry) {
            return ['success' => false, 'error' => 'العرض غير موجود أو منتهي'];
        }

        if ($entry['expires_at'] && $entry['expires_at'] < date('Y-m-d H:i:s')) {
            $db->update('sa_waitlist', [
                'status' => 'expired', 'updated_at' => date('Y-m-d H:i:s'),
            ], 'id = ?', [$waitlistId]);
            return ['success' => false, 'error' => 'انتهت صلاحية العرض'];
        }

        $db->update('sa_waitlist', [
            'status'      => 'accepted',
            'accepted_at' => date('Y-m-d H:i:s'),
            'updated_at'  => date('Y-m-d H:i:s'),
        ], 'id = ?', [$waitlistId]);

        $result = EnrollmentService::enroll((int) $entry['group_id'], (int) $entry['player_id']);

        return $result;
    }
}
