<?php
declare(strict_types=1);

namespace App\Modules\SportsActivity\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Modules\SportsActivity\Models\Facility;
use App\Modules\SportsActivity\Models\FacilityUnit;

class FacilityUnitController extends Controller
{
    public function index(Request $request, string $fid): Response
    {
        $this->authorize('sa.facility.view');

        $facility = Facility::find((int) $fid);
        if (!$facility) {
            return $this->redirect('/sa/facilities')->withError('المنشأة غير موجودة');
        }

        $units = FacilityUnit::getByFacility((int) $fid);

        return $this->view('SportsActivity.Views.facilities.units', [
            'facility'        => $facility,
            'units'           => $units,
            'unitTypeOptions' => FacilityUnit::getUnitTypeOptions(),
            'bookingModes'    => FacilityUnit::getBookingModeOptions(),
        ]);
    }

    public function create(Request $request, string $fid): Response
    {
        $this->authorize('sa.facility.manage');

        $facility = Facility::find((int) $fid);
        if (!$facility) {
            return $this->redirect('/sa/facilities')->withError('المنشأة غير موجودة');
        }

        return $this->view('SportsActivity.Views.facilities.unit_form', [
            'facility'        => $facility,
            'unit'            => null,
            'unitTypeOptions' => FacilityUnit::getUnitTypeOptions(),
            'bookingModes'    => FacilityUnit::getBookingModeOptions(),
        ]);
    }

    public function store(Request $request, string $fid): Response
    {
        $this->authorize('sa.facility.manage');

        $facility = Facility::find((int) $fid);
        if (!$facility) {
            return $this->redirect('/sa/facilities')->withError('المنشأة غير موجودة');
        }

        $code = trim((string) $request->post('code', ''));
        $nameAr = trim((string) $request->post('name_ar', ''));
        $nameEn = trim((string) $request->post('name_en', ''));
        $unitType = trim((string) $request->post('unit_type', ''));
        $bookingMode = trim((string) $request->post('booking_mode', ''));
        $maxCapacity = (int) $request->post('max_capacity', 1);
        $expectedCapacity = (int) $request->post('expected_capacity', 1);
        $sortOrder = (int) $request->post('sort_order', 0);

        // Validation
        $errors = [];
        if ($code === '') {
            $errors[] = 'الكود مطلوب';
        } elseif (mb_strlen($code) > 30) {
            $errors[] = 'الكود يجب ألا يتجاوز 30 حرف';
        }
        if ($nameAr === '') {
            $errors[] = 'الاسم بالعربية مطلوب';
        } elseif (mb_strlen($nameAr) > 200) {
            $errors[] = 'الاسم بالعربية يجب ألا يتجاوز 200 حرف';
        }
        if ($nameEn !== '' && mb_strlen($nameEn) > 200) {
            $errors[] = 'الاسم بالإنجليزية يجب ألا يتجاوز 200 حرف';
        }
        if ($unitType === '' || !isset(FacilityUnit::getUnitTypeOptions()[$unitType])) {
            $errors[] = 'نوع الوحدة مطلوب';
        }
        if ($bookingMode === '' || !isset(FacilityUnit::getBookingModeOptions()[$bookingMode])) {
            $errors[] = 'نمط الحجز مطلوب';
        }
        if ($maxCapacity < 1) {
            $errors[] = 'السعة القصوى يجب أن تكون 1 على الأقل';
        }
        if ($expectedCapacity < 1) {
            $expectedCapacity = 1;
        }

        if (!empty($errors)) {
            $session = App::getInstance()->session();
            $session->flash('_old_input', $_POST);
            $alerts = array_map(fn($msg) => ['type' => 'error', 'message' => $msg], $errors);
            $session->flash('_alerts', $alerts);
            return $this->redirect("/sa/facilities/{$fid}/units/create");
        }

        // Check duplicate code within facility
        $db = App::getInstance()->db();
        $existing = $db->selectOne(
            "SELECT id FROM sa_facility_units WHERE code = ? AND facility_id = ? AND is_active = 1",
            [$code, (int) $fid]
        );
        if ($existing) {
            $session = App::getInstance()->session();
            $session->flash('_old_input', $_POST);
            $session->flash('_alerts', [['type' => 'error', 'message' => 'الكود مستخدم بالفعل في هذه المنشأة']]);
            return $this->redirect("/sa/facilities/{$fid}/units/create");
        }

        FacilityUnit::create([
            'facility_id'       => (int) $fid,
            'code'              => $code,
            'name_ar'           => $nameAr,
            'name_en'           => $nameEn ?: null,
            'unit_type'         => $unitType,
            'booking_mode'      => $bookingMode,
            'max_capacity'      => $maxCapacity,
            'expected_capacity' => $expectedCapacity,
            'sort_order'        => $sortOrder,
            'is_active'         => 1,
        ]);

        return $this->redirect("/sa/facilities/{$fid}/units")->withSuccess('تم إضافة الوحدة بنجاح');
    }

    public function edit(Request $request, string $fid, string $id): Response
    {
        $this->authorize('sa.facility.manage');

        $facility = Facility::find((int) $fid);
        if (!$facility) {
            return $this->redirect('/sa/facilities')->withError('المنشأة غير موجودة');
        }

        $unit = FacilityUnit::find((int) $id);
        if (!$unit || (int) $unit->facility_id !== (int) $fid) {
            return $this->redirect("/sa/facilities/{$fid}/units")->withError('الوحدة غير موجودة');
        }

        return $this->view('SportsActivity.Views.facilities.unit_form', [
            'facility'        => $facility,
            'unit'            => $unit,
            'unitTypeOptions' => FacilityUnit::getUnitTypeOptions(),
            'bookingModes'    => FacilityUnit::getBookingModeOptions(),
        ]);
    }

    public function update(Request $request, string $fid, string $id): Response
    {
        $this->authorize('sa.facility.manage');

        $facility = Facility::find((int) $fid);
        if (!$facility) {
            return $this->redirect('/sa/facilities')->withError('المنشأة غير موجودة');
        }

        $unit = FacilityUnit::find((int) $id);
        if (!$unit || (int) $unit->facility_id !== (int) $fid) {
            return $this->redirect("/sa/facilities/{$fid}/units")->withError('الوحدة غير موجودة');
        }

        $code = trim((string) $request->post('code', ''));
        $nameAr = trim((string) $request->post('name_ar', ''));
        $nameEn = trim((string) $request->post('name_en', ''));
        $unitType = trim((string) $request->post('unit_type', ''));
        $bookingMode = trim((string) $request->post('booking_mode', ''));
        $maxCapacity = (int) $request->post('max_capacity', 1);
        $expectedCapacity = (int) $request->post('expected_capacity', 1);
        $sortOrder = (int) $request->post('sort_order', 0);

        // Validation
        $errors = [];
        if ($code === '') {
            $errors[] = 'الكود مطلوب';
        } elseif (mb_strlen($code) > 30) {
            $errors[] = 'الكود يجب ألا يتجاوز 30 حرف';
        }
        if ($nameAr === '') {
            $errors[] = 'الاسم بالعربية مطلوب';
        } elseif (mb_strlen($nameAr) > 200) {
            $errors[] = 'الاسم بالعربية يجب ألا يتجاوز 200 حرف';
        }
        if ($nameEn !== '' && mb_strlen($nameEn) > 200) {
            $errors[] = 'الاسم بالإنجليزية يجب ألا يتجاوز 200 حرف';
        }
        if ($unitType === '' || !isset(FacilityUnit::getUnitTypeOptions()[$unitType])) {
            $errors[] = 'نوع الوحدة مطلوب';
        }
        if ($bookingMode === '' || !isset(FacilityUnit::getBookingModeOptions()[$bookingMode])) {
            $errors[] = 'نمط الحجز مطلوب';
        }
        if ($maxCapacity < 1) {
            $errors[] = 'السعة القصوى يجب أن تكون 1 على الأقل';
        }
        if ($expectedCapacity < 1) {
            $expectedCapacity = 1;
        }

        if (!empty($errors)) {
            $session = App::getInstance()->session();
            $session->flash('_old_input', $_POST);
            $alerts = array_map(fn($msg) => ['type' => 'error', 'message' => $msg], $errors);
            $session->flash('_alerts', $alerts);
            return $this->redirect("/sa/facilities/{$fid}/units/{$id}/edit");
        }

        // Check duplicate code (excluding current)
        $db = App::getInstance()->db();
        $existing = $db->selectOne(
            "SELECT id FROM sa_facility_units WHERE code = ? AND facility_id = ? AND is_active = 1 AND id != ?",
            [$code, (int) $fid, (int) $id]
        );
        if ($existing) {
            $session = App::getInstance()->session();
            $session->flash('_old_input', $_POST);
            $session->flash('_alerts', [['type' => 'error', 'message' => 'الكود مستخدم بالفعل في هذه المنشأة']]);
            return $this->redirect("/sa/facilities/{$fid}/units/{$id}/edit");
        }

        $unit->update([
            'code'              => $code,
            'name_ar'           => $nameAr,
            'name_en'           => $nameEn ?: null,
            'unit_type'         => $unitType,
            'booking_mode'      => $bookingMode,
            'max_capacity'      => $maxCapacity,
            'expected_capacity' => $expectedCapacity,
            'sort_order'        => $sortOrder,
        ]);

        return $this->redirect("/sa/facilities/{$fid}/units")->withSuccess('تم تحديث الوحدة بنجاح');
    }
}
