<?php
declare(strict_types=1);

namespace App\Modules\PoolManagement\Models;

use App\Core\Model;
use App\Core\App;

class PoolConfiguration extends Model
{
    protected static string $table = 'pool_configurations';
    protected static string $primaryKey = 'id';
    protected static bool $timestamps = true;
    protected static bool $softDelete = false;
    protected static bool $autoTrackAuthor = true;

    protected static array $fillable = [
        'facility_id',
        'name_ar',
        'name_en',
        'length_meters',
        'width_meters',
        'depth_shallow',
        'depth_deep',
        'total_lanes_lengthwise',
        'total_lanes_widthwise',
        'lane_widths_json',
        'max_total_swimmers',
        'max_per_lane',
        'safety_ratio_json',
        'operating_hours_json',
        'is_active',
    ];

    public function getLaneWidths(): array
    {
        $raw = $this->lane_widths_json;
        if (empty($raw)) return [];
        $decoded = json_decode($raw, true);
        return is_array($decoded) ? $decoded : [];
    }

    public function getSafetyRatios(): array
    {
        $raw = $this->safety_ratio_json;
        if (empty($raw)) {
            return ['lap_swimming' => 6, 'lessons' => 4, 'free_swim' => 8, 'academy_session' => 5, 'competition' => 4, 'maintenance' => 0];
        }
        $decoded = json_decode($raw, true);
        return is_array($decoded) ? $decoded : [];
    }

    public function getOperatingHours(): array
    {
        $raw = $this->operating_hours_json;
        if (empty($raw)) {
            return ['start' => '06:00', 'end' => '22:00', 'slot_minutes' => 60];
        }
        $decoded = json_decode($raw, true);
        return is_array($decoded) ? $decoded : [];
    }

    public function getLanes(): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT * FROM pool_lanes WHERE pool_config_id = ? AND is_active = 1 ORDER BY sort_order ASC, lane_number ASC",
            [(int) $this->id]
        );
    }

    public static function getBookingTypes(): array
    {
        return [
            'lap_swimming'    => 'سباحة حرة (لفات)',
            'lessons'         => 'دروس سباحة',
            'free_swim'       => 'سباحة ترفيهية',
            'academy_session' => 'حصة أكاديمية',
            'competition'     => 'مسابقة / تدريب فريق',
            'maintenance'     => 'صيانة',
        ];
    }

    public static function allActive(): array
    {
        return static::query()
            ->where('is_active', '=', 1)
            ->get();
    }
}
