<?php
declare(strict_types=1);

namespace App\Modules\FacilityGrids\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;

class ZoneTraineeController extends Controller
{
    public function assign(Request $request, string $gridId): Response
    {
        $this->authorize('facility_grid.manage');
        $gridId = (int) $gridId;
        $db = App::getInstance()->db();

        $zoneId = (int) ($request->post('zone_id') ?? 0);
        $playerId = $request->post('player_id') ? (int) $request->post('player_id') : null;
        $traineeName = $request->post('trainee_name');
        $scheduleId = $request->post('schedule_id') ? (int) $request->post('schedule_id') : null;

        if (!$zoneId || (!$playerId && !$traineeName)) {
            return $this->json(['success' => false, 'message' => 'بيانات غير كاملة']);
        }

        // If player_id is provided, verify registration and medical status
        if ($playerId) {
            $player = $db->selectOne("SELECT card_status, medical_status FROM players WHERE id = ?", [$playerId]);
            if (!$player) {
                return $this->json(['success' => false, 'message' => 'اللاعب غير مسجل في النظام']);
            }
            if ($player['card_status'] !== 'active') {
                return $this->json(['success' => false, 'message' => 'بطاقة اللاعب غير فعالة — يجب تفعيل البطاقة أولاً']);
            }
            if (!in_array($player['medical_status'], ['fit', 'conditional'], true)) {
                return $this->json(['success' => false, 'message' => 'اللاعب غير لائق طبياً — يجب اعتماد الشهادة الطبية أولاً']);
            }
        }

        $zone = $db->selectOne("SELECT * FROM facility_grid_zones WHERE id = ? AND grid_id = ?", [$zoneId, $gridId]);
        if (!$zone) {
            return $this->json(['success' => false, 'message' => 'المنطقة غير موجودة']);
        }

        $currentCount = $db->selectOne(
            "SELECT COUNT(*) as cnt FROM facility_zone_trainees WHERE zone_id = ?",
            [$zoneId]
        );
        if ((int) $currentCount['cnt'] >= (int) $zone['max_occupants']) {
            return $this->json(['success' => false, 'message' => 'المنطقة ممتلئة']);
        }

        $session = App::getInstance()->session();
        $db->insert('facility_zone_trainees', [
            'zone_id'      => $zoneId,
            'schedule_id'  => $scheduleId,
            'player_id'    => $playerId,
            'trainee_name' => $traineeName ?? $this->getPlayerName($playerId),
            'assigned_by'  => $session->get('employee_id'),
        ]);

        return $this->json(['success' => true, 'message' => 'تم تسجيل المتدرب']);
    }

    public function remove(Request $request, string $gridId, string $traineeId): Response
    {
        $this->authorize('facility_grid.manage');
        $traineeId = (int) $traineeId;
        $db = App::getInstance()->db();

        $db->delete('facility_zone_trainees', 'id = ?', [$traineeId]);
        return $this->json(['success' => true, 'message' => 'تم إزالة المتدرب']);
    }

    public function move(Request $request, string $gridId, string $traineeId): Response
    {
        $this->authorize('facility_grid.manage');
        $gridId = (int) $gridId;
        $traineeId = (int) $traineeId;
        $db = App::getInstance()->db();

        $targetZoneId = (int) ($request->post('target_zone_id') ?? 0);
        if (!$targetZoneId) {
            return $this->json(['success' => false, 'message' => 'لم يتم تحديد المنطقة']);
        }

        $targetZone = $db->selectOne(
            "SELECT * FROM facility_grid_zones WHERE id = ? AND grid_id = ?",
            [$targetZoneId, $gridId]
        );
        if (!$targetZone) {
            return $this->json(['success' => false, 'message' => 'المنطقة غير موجودة']);
        }

        $currentCount = $db->selectOne(
            "SELECT COUNT(*) as cnt FROM facility_zone_trainees WHERE zone_id = ?",
            [$targetZoneId]
        );
        if ((int) $currentCount['cnt'] >= (int) $targetZone['max_occupants']) {
            return $this->json(['success' => false, 'message' => 'المنطقة المستهدفة ممتلئة']);
        }

        $db->update('facility_zone_trainees', ['zone_id' => $targetZoneId], 'id = ?', [$traineeId]);
        return $this->json(['success' => true, 'message' => 'تم نقل المتدرب']);
    }

    public function clearZone(Request $request, string $gridId, string $zoneId): Response
    {
        $this->authorize('facility_grid.manage');
        $zoneId = (int) $zoneId;
        $db = App::getInstance()->db();

        $db->delete('facility_zone_trainees', 'zone_id = ?', [$zoneId]);
        return $this->json(['success' => true, 'message' => 'تم إفراغ المنطقة']);
    }

    private function getPlayerName(?int $playerId): ?string
    {
        if (!$playerId) return null;
        $db = App::getInstance()->db();
        $player = $db->selectOne("SELECT full_name_ar FROM players WHERE id = ?", [$playerId]);
        return $player['full_name_ar'] ?? null;
    }
}
