<?php
declare(strict_types=1);

namespace App\Modules\PlayerApi\Controllers\Api;

use App\Core\ApiController;
use App\Core\App;
use App\Core\Request;
use App\Core\Response;
use App\Core\Exceptions\ValidationException;

final class TransferController extends ApiController
{
    public function __construct(Request $request)
    {
        parent::__construct();
        $this->request = $request;
    }

    public function requestTransfer(Request $request): Response
    {
        try {
            $data = $this->validatedJson([
                'from_group_id' => 'required|numeric',
                'to_group_id' => 'required|numeric',
                'reason' => 'nullable|string|max:500',
            ]);
        } catch (ValidationException $e) {
            return $this->errorResponse('بيانات غير صالحة', 422, $e->errors());
        }

        $player = App::getInstance()->currentPlayer();
        $db = App::getInstance()->db();

        $membership = $db->selectOne(
            "SELECT id FROM group_memberships WHERE player_id = ? AND group_id = ? AND status = 'active'",
            [$player->id, (int) $data['from_group_id']]
        );

        if (!$membership) {
            return $this->errorResponse('أنت غير مسجل في المجموعة المصدر', 422);
        }

        $toGroup = $db->selectOne(
            "SELECT id, name_ar, is_full, current_count, max_capacity FROM training_groups WHERE id = ? AND is_active = 1 AND is_archived = 0",
            [(int) $data['to_group_id']]
        );

        if (!$toGroup) {
            return $this->errorResponse('المجموعة المستهدفة غير متاحة', 404);
        }

        $pending = $db->selectOne(
            "SELECT id FROM group_transfer_requests WHERE player_id = ? AND status = 'pending'",
            [$player->id]
        );

        if ($pending) {
            return $this->errorResponse('لديك طلب نقل معلق بالفعل', 422);
        }

        $db->insert('group_transfer_requests', [
            'player_id' => $player->id,
            'from_group_id' => (int) $data['from_group_id'],
            'to_group_id' => (int) $data['to_group_id'],
            'reason_ar' => $data['reason'] ?? null,
            'status' => 'pending',
        ]);

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

        return $this->successResponse([
            'id' => $requestId,
            'status' => 'pending',
            'message' => 'تم إرسال طلب النقل وسيتم مراجعته',
        ], 201);
    }

    public function myTransfers(Request $request): Response
    {
        $player = App::getInstance()->currentPlayer();
        $db = App::getInstance()->db();

        $transfers = $db->select(
            "SELECT gtr.id, gtr.status, gtr.reason_ar, gtr.review_notes, gtr.created_at, gtr.reviewed_at,
                    fg.name_ar as from_group_name,
                    tg.name_ar as to_group_name
             FROM group_transfer_requests gtr
             LEFT JOIN training_groups fg ON fg.id = gtr.from_group_id
             LEFT JOIN training_groups tg ON tg.id = gtr.to_group_id
             WHERE gtr.player_id = ?
             ORDER BY gtr.created_at DESC",
            [$player->id]
        );

        return $this->successResponse($transfers);
    }
}
