<?php
declare(strict_types=1);

namespace App\Modules\SportsActivity\Models;

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

class Facility extends Model
{
    protected static string $table = 'sa_facilities';
    protected static string $primaryKey = 'id';
    protected static bool $timestamps = true;
    protected static bool $softDelete = true;
    protected static bool $dispatchEvents = true;
    protected static bool $autoTrackAuthor = true;

    protected static array $fillable = [
        'code', 'name_ar', 'name_en', 'facility_type', 'discipline_id',
        'location_description', 'operating_hours_json', 'is_active', 'branch_id',
    ];

    public static function getTypeOptions(): array
    {
        return [
            'pool'         => 'حمام سباحة',
            'court'        => 'ملعب (كورت)',
            'pitch'        => 'ملعب كبير',
            'gym'          => 'صالة رياضية',
            'track'        => 'مضمار',
            'multipurpose' => 'متعدد الاستخدام',
        ];
    }

    public function getTypeLabel(): string
    {
        return static::getTypeOptions()[$this->facility_type] ?? $this->facility_type;
    }

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

    public function getUnits(): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT * FROM sa_facility_units WHERE facility_id = ? AND is_active = 1 ORDER BY sort_order, id",
            [$this->id]
        );
    }

    public function getTimeBrackets(): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT * FROM sa_time_brackets WHERE facility_id = ? AND is_active = 1 ORDER BY start_time",
            [$this->id]
        );
    }

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