<?php

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class BookingDeadlineRule extends Model
{
    use HasFactory;

    protected $fillable = [
        'is_active',
        'mode',
        'date_from',
        'date_to',
        'days_to_payment',
        'room_ids',
    ];

    protected function casts(): array
    {
        return [
            'is_active' => 'boolean',
            'date_from' => 'date',
            'date_to' => 'date',
            'days_to_payment' => 'integer',
            'room_ids' => 'array',
        ];
    }

    public static function activeRuleFor(int $roomId, Carbon $arrivalDate): ?self
    {
        return self::query()
            ->where(function ($query) use ($arrivalDate): void {
                $query->whereNull('date_from')->orWhereDate('date_from', '<=', $arrivalDate->toDateString());
            })
            ->where(function ($query) use ($arrivalDate): void {
                $query->whereNull('date_to')->orWhereDate('date_to', '>=', $arrivalDate->toDateString());
            })
            ->latest('id')
            ->get()
            ->first(function (self $rule) use ($roomId): bool {
                $rooms = $rule->room_ids;
                if (! is_array($rooms) || count($rooms) === 0) {
                    return true;
                }

                return in_array($roomId, array_map('intval', $rooms), true);
            });
    }

    public function roomNames(): string
    {
        $rooms = $this->room_ids;
        if (! is_array($rooms) || count($rooms) === 0) {
            return 'Все комнаты';
        }

        return Room::query()
            ->whereIn('id', array_map('intval', $rooms))
            ->orderBy('sort_order')
            ->pluck('code')
            ->map(fn ($code) => '№ '.$code)
            ->implode(', ');
    }
}
