<?php
declare(strict_types=1);

namespace App\Modules\FacilityGrids\Models;

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

class FacilityGrid extends Model
{
    protected static string $table = 'facility_grids';
    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', 'grid_type',
        'rows_count', 'cols_count', 'row_label_ar', 'col_label_ar',
        'physical_length', 'physical_width', 'config_json', 'is_active',
    ];

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

    public function getZones(): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT * FROM facility_grid_zones WHERE grid_id = ? AND is_active = 1 ORDER BY row_index ASC, col_index ASC",
            [(int) $this->id]
        );
    }

    public static function allActive(): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT fg.*, f.name_ar AS facility_name
             FROM facility_grids fg
             LEFT JOIN facilities f ON f.id = fg.facility_id
             WHERE fg.is_active = 1
             ORDER BY fg.name_ar ASC"
        );
    }

    public static function getGridTypes(): array
    {
        return [
            'pool'    => 'حمام سباحة',
            'court'   => 'ملعب',
            'generic' => 'عام',
        ];
    }
}
