<?php
declare(strict_types=1);

namespace App\Modules\PoolManagement\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Modules\PoolManagement\Models\PoolConfiguration;
use App\Modules\PoolManagement\Models\PoolSchedule;

class PoolScheduleController extends Controller
{
    public function index(Request $request, string $id): Response
    {
        $pool = PoolConfiguration::find((int) $id);
        if (!$pool) {
            return $this->redirect('/pool')->withError('حمام السباحة غير موجود');
        }

        $schedules = PoolSchedule::getAllForPool((int) $id);

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

    public function store(Request $request, string $id): Response
    {
        $pool = PoolConfiguration::find((int) $id);
        if (!$pool) {
            return $this->redirect('/pool')->withError('حمام السباحة غير موجود');
        }

        $name = trim((string) $request->post('schedule_name', ''));
        $dayOfWeek = (int) $request->post('day_of_week', 0);
        $startTime = trim((string) $request->post('start_time', ''));
        $endTime = trim((string) $request->post('end_time', ''));
        $lanes = $request->post('lanes', []);
        $bookingType = trim((string) $request->post('booking_type', 'academy_session'));
        $coachName = trim((string) $request->post('coach_name', '')) ?: null;
        $ageGroup = trim((string) $request->post('age_group', '')) ?: null;
        $gender = trim((string) $request->post('gender', 'mixed'));
        $maxSwimmers = max(1, (int) $request->post('max_swimmers', 8));
        $effectiveFrom = trim((string) $request->post('effective_from', date('Y-m-d')));
        $effectiveTo = trim((string) $request->post('effective_to', '')) ?: null;
        $color = trim((string) $request->post('color', '#8B5CF6'));

        if (!is_array($lanes)) $lanes = [];
        $lanes = array_map('intval', $lanes);

        $errors = [];
        if (empty($name)) $errors[] = 'اسم الجدول مطلوب';
        if (empty($startTime) || empty($endTime)) $errors[] = 'الوقت مطلوب';
        if ($startTime >= $endTime) $errors[] = 'وقت البداية يجب أن يكون قبل النهاية';
        if (empty($lanes)) $errors[] = 'يجب اختيار حارة واحدة على الأقل';

        if (!empty($errors)) {
            $session = App::getInstance()->session();
            $session->flash('_alerts', array_map(fn($e) => ['type' => 'error', 'message' => $e], $errors));
            return $this->redirect('/pool/' . $id . '/schedules');
        }

        PoolSchedule::create([
            'pool_config_id'  => (int) $id,
            'schedule_name'   => $name,
            'day_of_week'     => $dayOfWeek,
            'start_time'      => $startTime,
            'end_time'        => $endTime,
            'lanes_json'      => json_encode($lanes),
            'booking_type'    => $bookingType,
            'coach_name'      => $coachName,
            'age_group'       => $ageGroup,
            'gender'          => $gender,
            'max_swimmers'    => $maxSwimmers,
            'color'           => $color,
            'effective_from'  => $effectiveFrom,
            'effective_to'    => $effectiveTo,
            'is_active'       => 1,
        ]);

        return $this->redirect('/pool/' . $id . '/schedules')->withSuccess('تم إنشاء الجدول الأسبوعي بنجاح');
    }

    public function delete(Request $request, string $poolId, string $scheduleId): Response
    {
        $db = App::getInstance()->db();
        $db->update('pool_schedules', ['is_active' => 0], 'id = ? AND pool_config_id = ?', [(int) $scheduleId, (int) $poolId]);
        return $this->redirect('/pool/' . $poolId . '/schedules')->withSuccess('تم حذف الجدول');
    }
}
