<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;
use Wildside\Userstamps\Userstamps;
use Illuminate\Database\Eloquent\SoftDeletes;

class Guest extends Model
{
    use HasFactory, Userstamps,SoftDeletes;

    protected $fillable = [
        'name',
        'identity_number',
        'phone',
        'email',
        'address',
        'gender',
        'birth_date',


    ];

    protected $casts = [
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    // ================================
    // RELATIONSHIPS
    // ================================

    public function bookings()
    {
        return $this->hasMany(Booking::class);
    }

    // public function checkins()
    // {
    //     return $this->hasManyThrough(Checkin::class, Booking::class);
    // }

    public function activeBookings()
    {
        return $this->bookings()->whereIn('status', ['booked', 'checked_in']);
    }

    public function lastBooking()
    {
        return $this->bookings()->latest()->first();
    }

    // ================================
    // ACCESSORS
    // ================================

    public function getCreatedAtFormattedAttribute()
    {
        return $this->created_at ? $this->created_at->format('d/m/Y H:i') : null;
    }

    public function getUpdatedAtFormattedAttribute()
    {
        return $this->updated_at ? $this->updated_at->format('d/m/Y H:i') : null;
    }

    public function getLastVisitAttribute()
    {
        $lastBooking = $this->lastBooking();
        return $lastBooking ? $lastBooking->check_in_date : null;
    }
    public function getUmur()
    {
        if (!$this->birth_date) {
            return null; // kalau birthdate kosong
        }

        return Carbon::parse($this->birth_date)->age;
    }
    public function getTotalBookingsAttribute()
    {
        return $this->bookings()->count();
    }

    public function getTotalSpentAttribute()
    {
        return $this->bookings()
                   ->where('status', '!=', 'cancelled')
                   ->with('bookingDetails')
                   ->get()
                   ->sum(function ($booking) {
                       return $booking->bookingDetails->sum('grand_total');
                   });
    }

    // ================================
    // SCOPES
    // ================================

    public function scopeSearch($query, $search)
    {
        return $query->where(function ($q) use ($search) {
            $q->where('name', 'like', "%{$search}%")
              ->orWhere('phone', 'like', "%{$search}%")
              ->orWhere('email', 'like', "%{$search}%")
              ->orWhere('identity_number', 'like', "%{$search}%");
        });
    }

    public function scopeActive($query)
    {
        return $query->whereHas('bookings', function ($q) {
            $q->whereIn('status', ['booked', 'checked_in']);
        });
    }

    public function scopeRecent($query)
    {
        return $query->where('created_at', '>=', Carbon::now()->subMonths(6));
    }

    // ================================
    // METHODS
    // ================================

    public function isCurrentlyStaying()
    {
        return $this->bookings()
                   ->where('status', 'checked_in')
                   ->exists();
    }

    public function hasUpcomingBooking()
    {
        return $this->bookings()
                   ->where('status', 'booked')
                   ->where('check_in_date', '>=', today())
                   ->exists();
    }

    public function getBookingHistory($limit = 10)
    {
        return $this->bookings()
                   ->with(['bookingDetails.room.typeRoom'])
                   ->orderBy('created_at', 'desc')
                   ->limit($limit)
                   ->get();
    }
}
