<?php
declare(strict_types=1);

namespace App\Modules\PoolManagement\Models;

use App\Core\Model;

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

    protected static array $fillable = [
        'booking_code',
        'pool_config_id',
        'booking_date',
        'start_time',
        'end_time',
        'booking_type',
        'selection_mode',
        'lanes_json',
        'booker_type',
        'booker_id',
        'booker_name',
        'expected_swimmers',
        'actual_swimmers',
        'unit_rate',
        'total_amount',
        'payment_status',
        'payment_id',
        'status',
        'cancelled_by',
        'cancelled_at',
        'cancel_reason',
        'notes',
    ];

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

    public static function getStatuses(): array
    {
        return [
            'confirmed'  => 'مؤكد',
            'checked_in' => 'تم الدخول',
            'completed'  => 'مكتمل',
            'cancelled'  => 'ملغي',
            'no_show'    => 'لم يحضر',
        ];
    }

    public static function getBookerTypes(): array
    {
        return [
            'member'     => 'عضو',
            'non_member' => 'غير عضو',
            'academy'    => 'أكاديمية',
            'staff'      => 'موظف',
        ];
    }

    public static function search(array $filters, int $perPage = 25, int $page = 1): array
    {
        $query = static::query();

        if (!empty($filters['pool_config_id'])) {
            $query = $query->where('pool_config_id', '=', (int) $filters['pool_config_id']);
        }
        if (!empty($filters['date_from'])) {
            $query = $query->where('booking_date', '>=', $filters['date_from']);
        }
        if (!empty($filters['date_to'])) {
            $query = $query->where('booking_date', '<=', $filters['date_to']);
        }
        if (!empty($filters['booking_date'])) {
            $query = $query->where('booking_date', '=', $filters['booking_date']);
        }
        if (!empty($filters['status'])) {
            $query = $query->where('status', '=', $filters['status']);
        }
        if (!empty($filters['booking_type'])) {
            $query = $query->where('booking_type', '=', $filters['booking_type']);
        }

        $query = $query->orderBy('booking_date', 'DESC')->orderBy('start_time', 'ASC');
        return $query->paginate($perPage, $page);
    }
}
