<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasOne;

class Booking extends Model
{
    protected $fillable = [
        'listing_id',
        'user_id',
        'pickup_location_id',
        'dropoff_location_id',
        'pickup_time',
        'dropoff_time',
        'check_in',
        'check_out',
        'guests',
        'total_price',
        'status',
        'discount_amount',
        'discount_percentage',
        'platform_fee',
        'invoice_number',
    ];

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($booking) {
            if (empty($booking->invoice_number)) {
                // Generate invoice number: YYYYMMDD-XXXXX (e.g., 20251016-12345)
                $booking->invoice_number = date('Ymd') . '-' . str_pad(rand(1, 99999), 5, '0', STR_PAD_LEFT);
            }
        });
    }

    protected $casts = [
        'check_in' => 'date',
        'check_out' => 'date',
        'total_price' => 'decimal:2',
    ];

    public function listing(): BelongsTo
    {
        return $this->belongsTo(Listing::class);
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    public function guest(): BelongsTo
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    public function payment(): HasOne
    {
        return $this->hasOne(Payment::class);
    }

    public function review(): HasOne
    {
        return $this->hasOne(Review::class);
    }

    public function addOns(): BelongsToMany
    {
        return $this->belongsToMany(AddOn::class, 'booking_add_on')
            ->withPivot('quantity', 'price_paid')
            ->withTimestamps();
    }

    public function pickupLocation(): BelongsTo
    {
        return $this->belongsTo(PickupLocation::class, 'pickup_location_id');
    }

    public function dropoffLocation(): BelongsTo
    {
        return $this->belongsTo(PickupLocation::class, 'dropoff_location_id');
    }

    public function hostReceipt(): HasOne
    {
        return $this->hasOne(HostReceipt::class);
    }

    public function getDaysAttribute()
    {
        return $this->check_in->diffInDays($this->check_out);
    }

    /**
     * Check if this booking overlaps with given dates (including buffer time)
     */
    public function overlapsWithDates($checkIn, $checkOut, $bufferHours = 0): bool
    {
        $checkInDate = \Carbon\Carbon::parse($checkIn);
        $checkOutDate = \Carbon\Carbon::parse($checkOut);

        // Add buffer time to this booking's checkout
        $bufferedCheckout = $this->check_out->copy()->addHours($bufferHours);

        // Check for overlap
        return $checkInDate < $bufferedCheckout && $checkOutDate > $this->check_in;
    }
}
