<?php
declare(strict_types=1);

namespace App\Modules\TrainingGroups\Services;

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

class GroupTransferService
{
    public static function submitRequest(int $playerId, int $fromGroupId, ?int $toGroupId, string $reason = ''): int
    {
        $db = App::getInstance()->db();

        $db->insert('group_transfer_requests', [
            'player_id'     => $playerId,
            'from_group_id' => $fromGroupId,
            'to_group_id'   => $toGroupId,
            'reason_ar'     => $reason,
            'status'        => 'pending',
            'created_at'    => date('Y-m-d H:i:s'),
            'updated_at'    => date('Y-m-d H:i:s'),
        ]);

        $requestId = (int) $db->selectOne("SELECT LAST_INSERT_ID() AS id")['id'];

        EventBus::dispatch('group.transfer_requested', [
            'request_id'    => $requestId,
            'player_id'     => $playerId,
            'from_group_id' => $fromGroupId,
            'to_group_id'   => $toGroupId,
        ]);

        return $requestId;
    }

    public static function approveRequest(int $requestId, int $reviewedBy): bool
    {
        $db = App::getInstance()->db();
        $request = $db->selectOne("SELECT * FROM group_transfer_requests WHERE id = ? AND status = 'pending'", [$requestId]);
        if (!$request) return false;

        $toGroupId = $request['to_group_id'] ? (int) $request['to_group_id'] : null;

        if ($toGroupId) {
            $group = $db->selectOne("SELECT * FROM training_groups WHERE id = ?", [$toGroupId]);
            if ($group && $group['max_capacity']) {
                $currentCount = (int) $db->selectOne(
                    "SELECT COUNT(*) AS c FROM group_players WHERE group_id = ? AND is_active = 1",
                    [$toGroupId]
                )['c'];

                if ($currentCount >= (int) $group['max_capacity']) {
                    $db->update('group_transfer_requests', [
                        'status'       => 'waitlisted',
                        'review_notes' => 'المجموعة المطلوبة ممتلئة - تم إضافة اللاعب لقائمة الانتظار',
                        'updated_at'   => date('Y-m-d H:i:s'),
                    ], '`id` = ?', [$requestId]);

                    $db->insert('group_waitlist', [
                        'group_id'     => $toGroupId,
                        'player_id'    => (int) $request['player_id'],
                        'priority'     => 0,
                        'status'       => 'waiting',
                        'requested_at' => date('Y-m-d H:i:s'),
                        'notes'        => 'من طلب نقل #' . $requestId,
                        'created_at'   => date('Y-m-d H:i:s'),
                        'updated_at'   => date('Y-m-d H:i:s'),
                    ]);

                    return true;
                }
            }
        }

        $db->update('group_transfer_requests', [
            'status'      => 'approved',
            'reviewed_by' => $reviewedBy,
            'reviewed_at' => date('Y-m-d H:i:s'),
            'updated_at'  => date('Y-m-d H:i:s'),
        ], '`id` = ?', [$requestId]);

        $db->update('group_players', ['is_active' => 0, 'updated_at' => date('Y-m-d H:i:s')], '`group_id` = ? AND `player_id` = ?', [(int) $request['from_group_id'], (int) $request['player_id']]);

        if ($toGroupId) {
            $exists = $db->selectOne("SELECT id FROM group_players WHERE group_id = ? AND player_id = ?", [$toGroupId, (int) $request['player_id']]);
            if ($exists) {
                $db->update('group_players', ['is_active' => 1, 'updated_at' => date('Y-m-d H:i:s')], '`group_id` = ? AND `player_id` = ?', [$toGroupId, (int) $request['player_id']]);
            } else {
                $db->insert('group_players', [
                    'group_id'   => $toGroupId,
                    'player_id'  => (int) $request['player_id'],
                    'is_active'  => 1,
                    'joined_at'  => date('Y-m-d H:i:s'),
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s'),
                ]);
            }
        }

        EventBus::dispatch('group.transfer_approved', [
            'request_id'    => $requestId,
            'player_id'     => (int) $request['player_id'],
            'from_group_id' => (int) $request['from_group_id'],
            'to_group_id'   => $toGroupId,
        ]);

        return true;
    }

    public static function rejectRequest(int $requestId, int $reviewedBy, string $notes = ''): bool
    {
        $db = App::getInstance()->db();
        $db->update('group_transfer_requests', [
            'status'       => 'rejected',
            'reviewed_by'  => $reviewedBy,
            'reviewed_at'  => date('Y-m-d H:i:s'),
            'review_notes' => $notes,
            'updated_at'   => date('Y-m-d H:i:s'),
        ], '`id` = ? AND `status` = ?', [$requestId, 'pending']);

        return true;
    }
}
