<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use App\Traits\SyncsToAccounting;
use App\Traits\HotelScopeTrait;
use App\Traits\RequiresHotelId;

class InOutLog extends Model
{   
    use SyncsToAccounting;
    use HasFactory;
    use HotelScopeTrait;
    use RequiresHotelId;

    protected $table = 'in_out_logs';

    protected $fillable = [
        'hotel_id',
        'reservation_id',
        'guest_id',
        'room_id',
        'type',
        'logged_at',
        'notes',
        'amount_paid',
        'payment_method',
        'processed_by',
        'invoice_id',
        'receipt_issued'
    ];

    protected $casts = [
        'logged_at' => 'datetime',
        'receipt_issued' => 'boolean',
        'amount_paid' => 'decimal:2'
    ];

    // Boot method is intentionally not overridden here because RequiresHotelId trait handles hotel_id enforcement.

    /**
     * Get the reservation associated with the log.
     */
    public function reservation(): BelongsTo
    {
        return $this->belongsTo(Reservation::class);
    }

    /**
     * Get the guest associated with the log.
     */
    public function guest(): BelongsTo
    {
        return $this->belongsTo(Guest::class);
    }

    /**
     * Get the room associated with the log.
     */
    public function room(): BelongsTo
    {
        return $this->belongsTo(Room::class);
    }

    /**
     * Get the invoice associated with the log.
     */
    public function invoice(): BelongsTo
    {
        return $this->belongsTo(Invoice::class, 'invoice_id');
    }

    /**
     * Get the user who processed the check-in/out.
     */
    public function processedBy(): BelongsTo
    {
        return $this->belongsTo(User::class, 'processed_by');
    }

    /**
     * Scope for check-ins.
     */
    public function scopeCheckins($query)
    {
        return $query->where('type', 'checkin');
    }

    /**
     * Scope for check-outs.
     */
    public function scopeCheckouts($query)
    {
        return $query->where('type', 'checkout');
    }

    /**
     * Scope for recent logs.
     */
    public function scopeRecent($query, $days = 30)
    {
        return $query->where('logged_at', '>=', now()->subDays($days));
    }

    /**
     * Scope for logs with receipts issued.
     */
    public function scopeWithReceipt($query)
    {
        return $query->where('receipt_issued', true);
    }

    /**
     * Scope for logs with invoices.
     */
    public function scopeWithInvoice($query)
    {
        return $query->whereNotNull('invoice_id');
    }
}