<?php
declare(strict_types=1);

namespace App\Modules\Facilities\Models;

use App\Core\Model;

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

    protected static array $fillable = [
        'code',
        'name_ar',
        'name_en',
        'facility_type',
        'location',
        'capacity',
        'hourly_rate_member',
        'hourly_rate_nonmember',
        'hourly_rate_member_pm',
        'hourly_rate_nonmember_pm',
        'linked_discipline_id',
        'config_json',
        'is_active',
    ];

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

    /**
     * Get all facility types with Arabic labels.
     */
    public static function getTypes(): array
    {
        return [
            'pitch'  => 'ملعب',
            'court'  => 'كورت',
            'hall'   => 'قاعة',
            'lane'   => 'حارة',
            'table'  => 'طاولة',
            'device' => 'جهاز',
            'track'  => 'مضمار',
            'pool'   => 'حمام سباحة',
        ];
    }

    /**
     * Get location options with Arabic labels.
     */
    public static function getLocations(): array
    {
        return [
            'indoor'  => 'داخلي',
            'outdoor' => 'خارجي',
        ];
    }

    /**
     * Get the Arabic label for a facility type.
     */
    public static function getTypeLabel(string $type): string
    {
        $types = self::getTypes();
        return $types[$type] ?? $type;
    }

    /**
     * Get the badge color for a facility type.
     */
    public static function getTypeColor(string $type): string
    {
        $colors = [
            'pitch'  => '#0D7377',
            'court'  => '#7C3AED',
            'hall'   => '#0284C7',
            'lane'   => '#059669',
            'table'  => '#D97706',
            'device' => '#DC2626',
            'track'  => '#EA580C',
            'pool'   => '#2563EB',
        ];
        return $colors[$type] ?? '#6B7280';
    }

    /**
     * Get the Arabic label for a location key.
     */
    public static function getLocationLabel(string $location): string
    {
        $locations = self::getLocations();
        return $locations[$location] ?? $location;
    }

    /**
     * Get all active facilities ordered by name_ar.
     */
    public static function allActive(): array
    {
        return static::query()
            ->where('is_active', '=', 1)
            ->orderBy('name_ar', 'ASC')
            ->get();
    }

    /**
     * Get active facilities filtered by facility_type.
     */
    public static function getByType(string $type): array
    {
        return static::query()
            ->where('is_active', '=', 1)
            ->where('facility_type', '=', $type)
            ->orderBy('name_ar', 'ASC')
            ->get();
    }

    /**
     * Search facilities with filters and pagination.
     */
    public static function search(array $filters, int $perPage = 25, int $page = 1): array
    {
        $query = static::query();

        if (!empty($filters['q'])) {
            $search = '%' . $filters['q'] . '%';
            $query = $query->whereRaw(
                '(`name_ar` LIKE ? OR `name_en` LIKE ? OR `code` LIKE ?)',
                [$search, $search, $search]
            );
        }

        if (!empty($filters['facility_type'])) {
            $query = $query->where('facility_type', '=', $filters['facility_type']);
        }

        if (!empty($filters['location'])) {
            $query = $query->where('location', '=', $filters['location']);
        }

        if (!empty($filters['linked_discipline_id'])) {
            $query = $query->where('linked_discipline_id', '=', (int) $filters['linked_discipline_id']);
        }

        if (isset($filters['is_active']) && $filters['is_active'] !== '') {
            $query = $query->where('is_active', '=', (int) $filters['is_active']);
        }

        $query = $query->orderBy('name_ar', 'ASC');

        return $query->paginate($perPage, $page);
    }

    /**
     * Get the correct hourly rate based on member status and time tier.
     *
     * @param bool   $isMember  Whether the person is a club member
     * @param string $timeTier  'AM' for morning rates, 'PM' for evening rates
     */
    public function getRate(bool $isMember, string $timeTier = 'AM'): float
    {
        if ($timeTier === 'PM') {
            return (float) ($isMember ? $this->hourly_rate_member_pm : $this->hourly_rate_nonmember_pm);
        }
        return (float) ($isMember ? $this->hourly_rate_member : $this->hourly_rate_nonmember);
    }
}
