<?php
declare(strict_types=1);

namespace App\Modules\FacilityDashboards\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Modules\FacilityDashboards\Services\MirrorDisplayService;

class MirrorDisplayController extends Controller
{
    public function index(Request $request): Response
    {
        $this->authorize('facility.mirror');

        $grids = MirrorDisplayService::getAllGrids();

        $db = App::getInstance()->db();
        $facilities = $db->select(
            "SELECT id, name_ar FROM facilities WHERE is_active = 1 AND is_archived = 0 ORDER BY name_ar"
        );

        return $this->view('FacilityDashboards.Views.mirror_index', [
            'grids'      => $grids,
            'facilities' => $facilities,
        ]);
    }

    public function createGrid(Request $request): Response
    {
        $this->authorize('facility.mirror');

        $facilityId = (int) $request->post('facility_id', 0);
        $nameAr = trim((string) $request->post('name_ar', ''));
        $rows = max(1, min(10, (int) $request->post('rows_count', 4)));
        $cols = max(1, min(12, (int) $request->post('cols_count', 6)));

        if ($facilityId <= 0 || $nameAr === '') {
            return $this->redirect('/mirror')->withError('يجب اختيار المرفق وإدخال الاسم');
        }

        $gridId = MirrorDisplayService::createGrid($facilityId, $nameAr, $rows, $cols);

        return $this->redirect('/mirror/' . $gridId)->withSuccess('تم إنشاء المراية بنجاح');
    }

    public function show(Request $request, string $id): Response
    {
        $this->authorize('facility.mirror');

        $grid = MirrorDisplayService::getGrid((int) $id);
        if (!$grid) {
            return $this->redirect('/mirror')->withError('المراية غير موجودة');
        }

        $db = App::getInstance()->db();
        $coaches = $db->select(
            "SELECT id, full_name_ar FROM coaches WHERE is_active = 1 AND is_archived = 0 ORDER BY full_name_ar"
        );
        $academies = $db->select(
            "SELECT id, name_ar FROM academies WHERE is_active = 1 ORDER BY name_ar"
        );
        $players = $db->select(
            "SELECT id, full_name_ar FROM players WHERE is_archived = 0 AND card_status = 'active' ORDER BY full_name_ar"
        );

        return $this->view('FacilityDashboards.Views.mirror', [
            'grid'      => $grid,
            'coaches'   => $coaches,
            'academies' => $academies,
            'players'   => $players,
        ]);
    }

    public function updateBox(Request $request, string $gridId, string $boxId): Response
    {
        $this->authorize('facility.mirror');

        $data = [];
        if ($request->post('coach_id') !== null) {
            $coachId = (int) $request->post('coach_id', 0);
            $data['coach_id'] = $coachId > 0 ? $coachId : null;
        }
        if ($request->post('coach_name') !== null) {
            $data['coach_name'] = trim((string) $request->post('coach_name', ''));
        }
        if ($request->post('academy_id') !== null) {
            $academyId = (int) $request->post('academy_id', 0);
            $data['academy_id'] = $academyId > 0 ? $academyId : null;
        }
        if ($request->post('age_group') !== null) {
            $data['age_group'] = trim((string) $request->post('age_group', ''));
        }
        if ($request->post('gender') !== null) {
            $data['gender'] = trim((string) $request->post('gender', ''));
        }
        if ($request->post('max_trainees') !== null) {
            $data['max_trainees'] = max(1, min(10, (int) $request->post('max_trainees', 5)));
        }
        if ($request->post('label') !== null) {
            $data['label'] = trim((string) $request->post('label', ''));
        }

        if (!empty($data)) {
            MirrorDisplayService::updateBox((int) $boxId, $data);
        }

        return $this->redirect('/mirror/' . $gridId)->withSuccess('تم تحديث الخانة');
    }

    public function addTrainee(Request $request, string $gridId, string $boxId): Response
    {
        $this->authorize('facility.mirror');

        $playerId = (int) $request->post('player_id', 0);
        $traineeName = trim((string) $request->post('trainee_name', ''));

        if ($playerId <= 0 && $traineeName === '') {
            return $this->redirect('/mirror/' . $gridId)->withError('يجب اختيار لاعب أو كتابة اسم');
        }

        $success = MirrorDisplayService::addTrainee(
            (int) $boxId,
            $playerId > 0 ? $playerId : null,
            $traineeName ?: null
        );

        if (!$success) {
            return $this->redirect('/mirror/' . $gridId)->withError('الخانة ممتلئة — الحد الأقصى 5');
        }

        return $this->redirect('/mirror/' . $gridId)->withSuccess('تم إضافة المتدرب');
    }

    public function removeTrainee(Request $request, string $gridId, string $traineeId): Response
    {
        $this->authorize('facility.mirror');
        MirrorDisplayService::removeTrainee((int) $traineeId);
        return $this->redirect('/mirror/' . $gridId)->withSuccess('تم إزالة المتدرب');
    }

    public function moveTrainee(Request $request, string $gridId, string $traineeId): Response
    {
        $this->authorize('facility.mirror');

        $toBoxId = (int) $request->post('to_box_id', 0);
        if ($toBoxId <= 0) {
            return $this->redirect('/mirror/' . $gridId)->withError('يجب اختيار الخانة المستهدفة');
        }

        $success = MirrorDisplayService::moveTrainee((int) $traineeId, $toBoxId);
        if (!$success) {
            return $this->redirect('/mirror/' . $gridId)->withError('الخانة المستهدفة ممتلئة');
        }

        return $this->redirect('/mirror/' . $gridId)->withSuccess('تم نقل المتدرب');
    }

    public function apiState(Request $request, string $id): Response
    {
        $this->authorize('facility.mirror');
        $state = MirrorDisplayService::getGridState((int) $id);
        return $this->json([
            'boxes'     => $state,
            'timestamp' => date('Y-m-d H:i:s'),
        ]);
    }

    public function deleteGrid(Request $request, string $id): Response
    {
        $this->authorize('facility.mirror');
        $db = App::getInstance()->db();
        $db->update('mirror_grids', ['is_active' => 0], 'id = ?', [(int) $id]);
        return $this->redirect('/mirror')->withSuccess('تم حذف المراية');
    }
}
