<?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;
use App\Modules\FacilityGrids\Models\FacilityGrid;
use App\Modules\FacilityGrids\Models\FacilityZoneSchedule;
use App\Modules\FacilityGrids\Services\GridStateService;

class ZoneScheduleController extends Controller
{
    public function index(Request $request, string $gridId): Response
    {
        $this->authorize('facility_grid.manage');
        $gridId = (int) $gridId;

        $grid = FacilityGrid::find($gridId);
        if (!$grid) return $this->redirect('/facility-grids')->withError('الشبكة غير موجودة');

        $schedules = FacilityZoneSchedule::getAllForGrid($gridId);
        $dayNames = FacilityZoneSchedule::getDayNames();

        return $this->view('FacilityGrids.Views.schedules', [
            'grid'      => $grid,
            'schedules' => $schedules,
            'dayNames'  => $dayNames,
        ]);
    }

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

        $grid = FacilityGrid::find($gridId);
        if (!$grid) return $this->json(['success' => false, 'message' => 'شبكة غير موجودة']);

        $rules = [
            'schedule_name'       => 'required|string|max:255',
            'zone_selection_type' => 'required|in:cells,row,column,all',
            'day_of_week'         => 'required|numeric|min:0|max:6',
            'start_time'          => 'required',
            'end_time'            => 'required',
            'effective_from'      => 'required|date',
        ];

        if (!$this->validate($_POST, $rules)) {
            return $this->json(['success' => false, 'message' => 'بيانات غير صالحة']);
        }

        $selectionType = $_POST['zone_selection_type'];
        $selectionJson = $_POST['zone_selection_json'] ?? '[]';

        $positions = GridStateService::resolvePositions([
            'zone_selection_type' => $selectionType,
            'zone_selection_json' => $selectionJson,
        ], (int) $grid->rows_count, (int) $grid->cols_count);

        $conflicts = GridStateService::checkConflicts(
            $gridId,
            $positions,
            (int) $_POST['day_of_week'],
            $_POST['start_time'],
            $_POST['end_time'],
            $_POST['effective_from'],
            $_POST['effective_to'] ?? null
        );

        if (!empty($conflicts)) {
            return $this->json([
                'success'   => false,
                'message'   => 'يوجد تعارض مع جداول أخرى',
                'conflicts' => $conflicts,
            ]);
        }

        $maxOccupants = FacilityZoneSchedule::getMaxOccupants($selectionType);
        $planMonth = $_POST['plan_month'] ?? date('Y-m');

        $schedule = FacilityZoneSchedule::create([
            'grid_id'             => $gridId,
            'plan_month'          => $planMonth,
            'schedule_name'       => $_POST['schedule_name'],
            'zone_selection_type' => $selectionType,
            'zone_selection_json' => $selectionJson,
            'day_of_week'         => (int) $_POST['day_of_week'],
            'start_time'          => $_POST['start_time'],
            'end_time'            => $_POST['end_time'],
            'activity_type'       => $_POST['activity_type'] ?? null,
            'coach_id'            => !empty($_POST['coach_id']) ? (int) $_POST['coach_id'] : null,
            'coach_name'          => $_POST['coach_name'] ?? null,
            'academy_id'          => !empty($_POST['academy_id']) ? (int) $_POST['academy_id'] : null,
            'academy_name'        => $_POST['academy_name'] ?? null,
            'age_group'           => $_POST['age_group'] ?? null,
            'gender'              => $_POST['gender'] ?? 'male',
            'max_occupants'       => $maxOccupants,
            'color'               => $_POST['color'] ?? '#3B82F6',
            'effective_from'      => $_POST['effective_from'],
            'effective_to'        => $_POST['effective_to'] ?? null,
            'is_active'           => 1,
            'notes'               => $_POST['notes'] ?? null,
        ]);

        return $this->json([
            'success'  => true,
            'message'  => 'تم إنشاء الجدول بنجاح',
            'schedule' => ['id' => (int) $schedule->id],
        ]);
    }

    public function update(Request $request, string $gridId, string $scheduleId): Response
    {
        $this->authorize('facility_grid.manage');
        $gridId = (int) $gridId;
        $scheduleId = (int) $scheduleId;

        $schedule = FacilityZoneSchedule::find($scheduleId);
        if (!$schedule || (int) $schedule->grid_id !== $gridId) {
            return $this->json(['success' => false, 'message' => 'جدول غير موجود']);
        }

        $grid = FacilityGrid::find($gridId);
        $selectionType = $_POST['zone_selection_type'] ?? $schedule->zone_selection_type;
        $selectionJson = $_POST['zone_selection_json'] ?? $schedule->zone_selection_json;

        $positions = GridStateService::resolvePositions([
            'zone_selection_type' => $selectionType,
            'zone_selection_json' => $selectionJson,
        ], (int) $grid->rows_count, (int) $grid->cols_count);

        $conflicts = GridStateService::checkConflicts(
            $gridId,
            $positions,
            (int) ($_POST['day_of_week'] ?? $schedule->day_of_week),
            $_POST['start_time'] ?? $schedule->start_time,
            $_POST['end_time'] ?? $schedule->end_time,
            $_POST['effective_from'] ?? $schedule->effective_from,
            $_POST['effective_to'] ?? $schedule->effective_to,
            $scheduleId
        );

        if (!empty($conflicts)) {
            return $this->json([
                'success'   => false,
                'message'   => 'يوجد تعارض مع جداول أخرى',
                'conflicts' => $conflicts,
            ]);
        }

        $schedule->update([
            'schedule_name'       => $_POST['schedule_name'] ?? $schedule->schedule_name,
            'zone_selection_type' => $selectionType,
            'zone_selection_json' => $selectionJson,
            'day_of_week'         => (int) ($_POST['day_of_week'] ?? $schedule->day_of_week),
            'start_time'          => $_POST['start_time'] ?? $schedule->start_time,
            'end_time'            => $_POST['end_time'] ?? $schedule->end_time,
            'activity_type'       => $_POST['activity_type'] ?? $schedule->activity_type,
            'coach_id'            => !empty($_POST['coach_id']) ? (int) $_POST['coach_id'] : $schedule->coach_id,
            'coach_name'          => $_POST['coach_name'] ?? $schedule->coach_name,
            'academy_id'          => !empty($_POST['academy_id']) ? (int) $_POST['academy_id'] : $schedule->academy_id,
            'academy_name'        => $_POST['academy_name'] ?? $schedule->academy_name,
            'age_group'           => $_POST['age_group'] ?? $schedule->age_group,
            'gender'              => $_POST['gender'] ?? $schedule->gender,
            'max_occupants'       => !empty($_POST['max_occupants']) ? (int) $_POST['max_occupants'] : (int) $schedule->max_occupants,
            'color'               => $_POST['color'] ?? $schedule->color,
            'effective_from'      => $_POST['effective_from'] ?? $schedule->effective_from,
            'effective_to'        => $_POST['effective_to'] ?? $schedule->effective_to,
            'notes'               => $_POST['notes'] ?? $schedule->notes,
        ]);

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

    public function destroy(Request $request, string $gridId, string $scheduleId): Response
    {
        $this->authorize('facility_grid.manage');
        $gridId = (int) $gridId;
        $scheduleId = (int) $scheduleId;

        $schedule = FacilityZoneSchedule::find($scheduleId);
        if (!$schedule || (int) $schedule->grid_id !== $gridId) {
            return $this->json(['success' => false, 'message' => 'جدول غير موجود']);
        }

        $schedule->update(['is_active' => 0]);
        return $this->json(['success' => true, 'message' => 'تم حذف الجدول']);
    }

    public function checkConflicts(Request $request, string $gridId): Response
    {
        $gridId = (int) $gridId;
        $grid = FacilityGrid::find($gridId);
        if (!$grid) return $this->json(['success' => false]);

        $positions = GridStateService::resolvePositions([
            'zone_selection_type' => $_GET['type'] ?? 'cells',
            'zone_selection_json' => $_GET['json'] ?? '[]',
        ], (int) $grid->rows_count, (int) $grid->cols_count);

        $conflicts = GridStateService::checkConflicts(
            $gridId,
            $positions,
            (int) ($_GET['day'] ?? 0),
            $_GET['start'] ?? '00:00',
            $_GET['end'] ?? '23:59',
            $_GET['from'] ?? date('Y-m-d'),
            $_GET['to'] ?? null,
            !empty($_GET['exclude']) ? (int) $_GET['exclude'] : null
        );

        return $this->json(['success' => true, 'conflicts' => $conflicts]);
    }
}
