<?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;

class PoolConfigController extends Controller
{
    public function index(Request $request): Response
    {
        $pools = PoolConfiguration::allActive();

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

        return $this->view('PoolManagement.Views.index', [
            'pools'      => $pools,
            'facilities' => $facilities,
        ]);
    }

    public function create(Request $request): Response
    {
        $db = App::getInstance()->db();
        $facilities = $db->select(
            "SELECT id, name_ar FROM facilities WHERE facility_type = 'pool' AND is_active = 1 AND is_archived = 0 ORDER BY name_ar"
        );

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

    public function store(Request $request): Response
    {
        $facilityId = (int) $request->post('facility_id', 0);
        $nameAr = trim((string) $request->post('name_ar', ''));
        $length = (float) $request->post('length_meters', 0);
        $width = (float) $request->post('width_meters', 0);
        $totalLanesLength = (int) $request->post('total_lanes_lengthwise', 6);

        $errors = [];
        if ($facilityId <= 0) $errors[] = 'يجب اختيار المرفق';
        if ($nameAr === '') $errors[] = 'اسم الحمام مطلوب';
        if ($length <= 0) $errors[] = 'الطول مطلوب';
        if ($width <= 0) $errors[] = 'العرض مطلوب';
        if ($totalLanesLength < 1) $errors[] = 'عدد الحارات مطلوب';

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

        $laneWidth = round($width / $totalLanesLength, 2);
        $laneWidths = array_fill(0, $totalLanesLength, $laneWidth);

        $safetyRatios = [
            'lap_swimming'    => (int) $request->post('safety_lap', 6),
            'lessons'         => (int) $request->post('safety_lessons', 4),
            'free_swim'       => (int) $request->post('safety_free', 8),
            'academy_session' => (int) $request->post('safety_academy', 5),
            'competition'     => (int) $request->post('safety_competition', 4),
            'maintenance'     => 0,
        ];

        $operatingHours = [
            'start'        => trim((string) $request->post('op_start', '06:00')),
            'end'          => trim((string) $request->post('op_end', '22:00')),
            'slot_minutes' => (int) $request->post('slot_minutes', 60),
        ];

        $pool = PoolConfiguration::create([
            'facility_id'            => $facilityId,
            'name_ar'                => $nameAr,
            'name_en'                => trim((string) $request->post('name_en', '')) ?: null,
            'length_meters'          => $length,
            'width_meters'           => $width,
            'depth_shallow'          => $request->post('depth_shallow', '') !== '' ? (float) $request->post('depth_shallow') : null,
            'depth_deep'             => $request->post('depth_deep', '') !== '' ? (float) $request->post('depth_deep') : null,
            'total_lanes_lengthwise' => $totalLanesLength,
            'total_lanes_widthwise'  => (int) $request->post('total_lanes_widthwise', 0),
            'lane_widths_json'       => json_encode($laneWidths),
            'max_total_swimmers'     => (int) $request->post('max_total_swimmers', 50),
            'max_per_lane'           => (int) $request->post('max_per_lane', 8),
            'safety_ratio_json'      => json_encode($safetyRatios),
            'operating_hours_json'   => json_encode($operatingHours),
            'is_active'              => 1,
        ]);

        $db = App::getInstance()->db();
        for ($i = 1; $i <= $totalLanesLength; $i++) {
            $db->insert('pool_lanes', [
                'pool_config_id' => (int) $pool->id,
                'lane_number'    => $i,
                'direction'      => 'lengthwise',
                'width_meters'   => $laneWidth,
                'label_ar'       => 'حارة ' . $i,
                'max_swimmers'   => (int) $request->post('max_per_lane', 8),
                'is_active'      => 1,
                'sort_order'     => $i,
            ]);
        }

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

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

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

        return $this->view('PoolManagement.Views.config_edit', [
            'pool'       => $pool,
            'facilities' => $facilities,
            'safety'     => $pool->getSafetyRatios(),
            'hours'      => $pool->getOperatingHours(),
        ]);
    }

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

        $pool->update([
            'name_ar'              => trim((string) $request->post('name_ar', $pool->name_ar)),
            'name_en'              => trim((string) $request->post('name_en', '')) ?: null,
            'depth_shallow'        => $request->post('depth_shallow', '') !== '' ? (float) $request->post('depth_shallow') : null,
            'depth_deep'           => $request->post('depth_deep', '') !== '' ? (float) $request->post('depth_deep') : null,
            'max_total_swimmers'   => (int) $request->post('max_total_swimmers', $pool->max_total_swimmers),
            'max_per_lane'         => (int) $request->post('max_per_lane', $pool->max_per_lane),
            'safety_ratio_json'    => json_encode([
                'lap_swimming'    => (int) $request->post('safety_lap', 6),
                'lessons'         => (int) $request->post('safety_lessons', 4),
                'free_swim'       => (int) $request->post('safety_free', 8),
                'academy_session' => (int) $request->post('safety_academy', 5),
                'competition'     => (int) $request->post('safety_competition', 4),
                'maintenance'     => 0,
            ]),
            'operating_hours_json' => json_encode([
                'start'        => trim((string) $request->post('op_start', '06:00')),
                'end'          => trim((string) $request->post('op_end', '22:00')),
                'slot_minutes' => (int) $request->post('slot_minutes', 60),
            ]),
        ]);

        return $this->redirect('/pool/' . $id . '/grid')->withSuccess('تم تحديث التكوين');
    }
}
