<?php
declare(strict_types=1);

namespace App\Modules\PlaygroundAdmin\Controllers;

use App\Core\Controller;
use App\Core\App;
use App\Core\Request;
use App\Core\Response;
use App\Modules\PlaygroundAdmin\Models\PlaygroundMonthlySchedule;
use App\Modules\PlaygroundAdmin\Models\PlaygroundScheduleSlot;

final class PlaygroundScheduleController extends Controller
{
    public function __construct(Request $request)
    {
        parent::__construct($request);
    }

    public function schedules(Request $request, string $id): Response
    {
        $this->authorize('playground.schedule');
        $schedules = PlaygroundMonthlySchedule::getForPlayground((int) $id);

        $db = App::getInstance()->db();
        $playground = $db->selectOne("SELECT * FROM playground_configurations WHERE id = ?", [(int) $id]);

        return $this->view('PlaygroundAdmin.Views.schedules', [
            'playground' => $playground,
            'schedules' => $schedules,
        ]);
    }

    public function createSchedule(Request $request, string $id): Response
    {
        $this->authorize('playground.schedule');
        $db = App::getInstance()->db();
        $playground = $db->selectOne("SELECT * FROM playground_configurations WHERE id = ?", [(int) $id]);

        return $this->view('PlaygroundAdmin.Views.schedule_edit', [
            'playground' => $playground,
            'schedule' => null,
            'mode' => 'create',
        ]);
    }

    public function storeSchedule(Request $request, string $id): Response
    {
        $this->authorize('playground.schedule');
        $data = $request->all();
        $db = App::getInstance()->db();
        $employee = App::getInstance()->currentEmployee();

        $workingDays = $data['working_days'] ?? [];

        $db->insert('playground_monthly_schedules', [
            'playground_id' => (int) $id,
            'plan_month' => $data['plan_month'],
            'plan_name_ar' => $data['plan_name_ar'],
            'status' => 'draft',
            'working_days_json' => json_encode(array_map('intval', $workingDays)),
            'day_start_time' => $data['day_start_time'] ?? '07:00:00',
            'day_end_time' => $data['day_end_time'] ?? '22:00:00',
            'notes' => $data['notes'] ?? null,
            'created_by' => $employee ? (int) $employee->id : null,
        ]);

        $schedId = (int) $db->selectOne("SELECT LAST_INSERT_ID() as id")['id'];
        return $this->redirect('/playgrounds/' . $id . '/schedules/' . $schedId)->withSuccess('تم إنشاء الجدول بنجاح');
    }

    public function showSchedule(Request $request, string $id, string $schedId): Response
    {
        $this->authorize('playground.schedule');
        $db = App::getInstance()->db();

        $playground = $db->selectOne("SELECT * FROM playground_configurations WHERE id = ?", [(int) $id]);
        $schedule = $db->selectOne("SELECT * FROM playground_monthly_schedules WHERE id = ? AND playground_id = ?", [(int) $schedId, (int) $id]);

        if (!$schedule) {
            return $this->redirect('/playgrounds/' . $id . '/schedules')->withError('الجدول غير موجود');
        }

        $date = $request->get('date', $schedule['plan_month']);
        $slots = PlaygroundScheduleSlot::getForDate((int) $schedId, $date);

        return $this->view('PlaygroundAdmin.Views.schedule_view', [
            'playground' => $playground,
            'schedule' => $schedule,
            'date' => $date,
            'slots' => $slots,
        ]);
    }

    public function editSchedule(Request $request, string $id, string $schedId): Response
    {
        $this->authorize('playground.schedule');
        $db = App::getInstance()->db();

        $playground = $db->selectOne("SELECT * FROM playground_configurations WHERE id = ?", [(int) $id]);
        $schedule = $db->selectOne("SELECT * FROM playground_monthly_schedules WHERE id = ? AND playground_id = ?", [(int) $schedId, (int) $id]);

        return $this->view('PlaygroundAdmin.Views.schedule_edit', [
            'playground' => $playground,
            'schedule' => $schedule,
            'mode' => 'edit',
        ]);
    }

    public function updateSchedule(Request $request, string $id, string $schedId): Response
    {
        $this->authorize('playground.schedule');
        $data = $request->all();
        $db = App::getInstance()->db();

        $workingDays = $data['working_days'] ?? [];

        $updateData = [
            'plan_name_ar' => $data['plan_name_ar'],
            'working_days_json' => json_encode(array_map('intval', $workingDays)),
            'day_start_time' => $data['day_start_time'] ?? '07:00:00',
            'day_end_time' => $data['day_end_time'] ?? '22:00:00',
            'notes' => $data['notes'] ?? null,
            'updated_at' => date('Y-m-d H:i:s'),
        ];

        if (($data['status'] ?? '') === 'active') {
            $updateData['status'] = 'active';
            $updateData['activated_at'] = date('Y-m-d H:i:s');
        }

        $db->update('playground_monthly_schedules', $updateData, 'id = ? AND playground_id = ?', [(int) $schedId, (int) $id]);

        return $this->redirect('/playgrounds/' . $id . '/schedules/' . $schedId)->withSuccess('تم تحديث الجدول');
    }

    public function slotEditor(Request $request, string $id, string $schedId, string $date, string $hour): Response
    {
        $this->authorize('playground.schedule');
        $db = App::getInstance()->db();

        $playground = $db->selectOne("SELECT * FROM playground_configurations WHERE id = ?", [(int) $id]);
        $slots = PlaygroundScheduleSlot::getForDateAndHour((int) $schedId, $date, $hour . ':00');

        $coaches = $db->select("SELECT id, name_ar FROM coaches WHERE is_archived = 0 ORDER BY name_ar");
        $academies = $db->select("SELECT id, name_ar FROM academies WHERE is_active = 1 ORDER BY name_ar");

        return $this->view('PlaygroundAdmin.Views.slot_editor', [
            'playground' => $playground,
            'schedule_id' => (int) $schedId,
            'date' => $date,
            'hour' => $hour,
            'slots' => $slots,
            'coaches' => $coaches,
            'academies' => $academies,
        ]);
    }

    public function saveSlot(Request $request, string $id, string $schedId, string $date, string $hour): Response
    {
        $this->authorize('playground.schedule');
        $db = App::getInstance()->db();
        $data = $request->all();

        $db->query(
            "DELETE FROM playground_schedule_slots WHERE schedule_id = ? AND slot_date = ? AND slot_hour = ?",
            [(int) $schedId, $date, $hour . ':00']
        );

        foreach ($data['slots'] ?? [] as $slotData) {
            if (empty($slotData['coach_id']) && empty($slotData['academy_id'])) {
                continue;
            }
            $db->insert('playground_schedule_slots', [
                'schedule_id' => (int) $schedId,
                'slot_date' => $date,
                'slot_hour' => $hour . ':00',
                'row_number' => !empty($slotData['row_number']) ? (int) $slotData['row_number'] : null,
                'coach_id' => !empty($slotData['coach_id']) ? (int) $slotData['coach_id'] : null,
                'academy_id' => !empty($slotData['academy_id']) ? (int) $slotData['academy_id'] : null,
                'group_type' => $slotData['group_type'] ?? null,
                'max_trainees' => !empty($slotData['max_trainees']) ? (int) $slotData['max_trainees'] : null,
                'age_group_ar' => $slotData['age_group_ar'] ?? null,
                'gender' => $slotData['gender'] ?? null,
                'notes' => $slotData['notes'] ?? null,
            ]);
        }

        return $this->redirect('/playgrounds/' . $id . '/schedules/' . $schedId . '?date=' . $date)
            ->withSuccess('تم حفظ الخانة بنجاح');
    }
}
