<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Booking extends Model
{
    use HasFactory;

    public const ACTIVE_STATUSES = ['pending_payment', 'awaiting_prepayment', 'payment_uploaded', 'payment_rejected', 'confirmed'];

    protected $fillable = [
        'booking_number',
        'secure_token',
        'guest_id',
        'created_by_user_id',
        'room_id',
        'guest_name',
        'phone',
        'email',
        'source',
        'booking_variant',
        'rate_name',
        'status',
        'arrival_date',
        'departure_date',
        'nights',
        'adults',
        'children_under_2',
        'min_nights_applied',
        'breakfast',
        'discount_applied',
        'discount_code',
        'pricing_mode',
        'manual_price_override',
        'rate_snapshot_json',
        'price_calculated_at',
        'nightly_amount',
        'full_amount',
        'prepayment_amount',
        'remaining_amount',
        'payment_deadline',
        'comment_guest',
        'comment_admin',
        'booking_link',
        'check_in_time_from',
        'check_in_time_to',
        'confirmed_at',
        'receipt_received',
        'prepayment_received',
        'guest_documents_received',
        'guest_documents_consent_at',
        'guest_rating',
        'release_on_expire',
    ];

    protected function casts(): array
    {
        return [
            'arrival_date' => 'date',
            'departure_date' => 'date',
            'payment_deadline' => 'datetime',
            'confirmed_at' => 'datetime',
            'guest_documents_consent_at' => 'datetime',
            'price_calculated_at' => 'datetime',
            'breakfast' => 'boolean',
            'discount_applied' => 'boolean',
            'manual_price_override' => 'boolean',
            'receipt_received' => 'boolean',
            'prepayment_received' => 'boolean',
            'guest_documents_received' => 'boolean',
            'rate_snapshot_json' => 'array',
            'nightly_amount' => 'decimal:2',
            'full_amount' => 'decimal:2',
            'prepayment_amount' => 'decimal:2',
            'remaining_amount' => 'decimal:2',
            'nights' => 'integer',
            'min_nights_applied' => 'integer',
            'adults' => 'integer',
            'children_under_2' => 'integer',
            'guest_rating' => 'integer',
            'release_on_expire' => 'boolean',
        ];
    }

    public static function statusOptions(): array
    {
        return [
            'draft' => 'Черновик',
            'pending_payment' => 'Ожидает предоплату',
            'awaiting_prepayment' => 'Ожидает предоплату (старый статус)',
            'payment_uploaded' => 'Квитанция загружена',
            'payment_rejected' => 'Платёж отклонён',
            'confirmed' => 'Подтверждена',
            'cancelled' => 'Отменена',
            'expired' => 'Истёк срок оплаты',
        ];
    }

    public static function sourceOptions(): array
    {
        return [
            'draft' => 'Черновик',
            'site' => 'Site',
            'booking' => 'Booking',
            'whatsapp' => 'WhatsApp',
            'telegram' => 'Telegram',
            'admin' => 'Admin',
        ];
    }

    public static function activeStatuses(): array
    {
        return self::ACTIVE_STATUSES;
    }


    public function latestReceipt(): ?BookingDocument
    {
        return $this->documents()->where('type', 'receipt')->latest('uploaded_at')->first();
    }

    public function latestPayment(): ?BookingPayment
    {
        return $this->payments()->latest('paid_at')->latest('id')->first();
    }

    public function room()
    {
        return $this->belongsTo(Room::class);
    }

    public function guest()
    {
        return $this->belongsTo(Guest::class);
    }

    public function createdBy()
    {
        return $this->belongsTo(User::class, 'created_by_user_id');
    }

    public function payments()
    {
        return $this->hasMany(BookingPayment::class);
    }

    public function documents()
    {
        return $this->hasMany(BookingDocument::class);
    }

    public function statusLogs()
    {
        return $this->hasMany(BookingStatusLog::class)->latest();
    }

    public function syncLogs()
    {
        return $this->hasMany(GoogleSyncLog::class)->latest();
    }

    public function roomDays()
    {
        return $this->hasMany(BookingRoomDay::class);
    }
}
