<?php

namespace App\Models;

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

class Booking extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'reference',
        'user_id',
        'cart_id',
        'payment_id',
        'status',
        'currency',
        'subtotal',
        'platform_fee',
        'total',
        'campaign_name',
        'campaign_brief',
        'industry',
        'start_date',
        'end_date',
        'confirmed_at',
        'cancelled_at',
        'cancellation_reason',
    ];

    protected $casts = [
        'subtotal'     => 'decimal:2',
        'platform_fee' => 'decimal:2',
        'total'        => 'decimal:2',
        'start_date'   => 'date',
        'end_date'     => 'date',
        'confirmed_at' => 'datetime',
        'cancelled_at' => 'datetime',
    ];

    // ============================================================
    // Boot — auto generate reference
    // ============================================================
    protected static function boot()
    {
        parent::boot();

        static::creating(function ($booking) {
            if (empty($booking->reference)) {
                $latest = static::withTrashed()->latest('id')->first();
                $next   = $latest ? $latest->id + 1 : 1;
                $booking->reference = 'BK-' . str_pad($next, 6, '0', STR_PAD_LEFT);
            }
        });
    }

    // ============================================================
    // Scopes
    // ============================================================
    public function scopeConfirmed($query)
    {
        return $query->where('status', 'confirmed');
    }

    public function scopeActive($query)
    {
        return $query->where('status', 'active');
    }

    public function scopeCompleted($query)
    {
        return $query->where('status', 'completed');
    }

    public function scopeDisputed($query)
    {
        return $query->where('status', 'disputed');
    }

    public function scopeForUser($query, int $userId)
    {
        return $query->where('user_id', $userId);
    }

    // ============================================================
    // Helpers
    // ============================================================
    public function isPending(): bool
    {
        return $this->status === 'pending';
    }

    public function isConfirmed(): bool
    {
        return $this->status === 'confirmed';
    }

    public function isActive(): bool
    {
        return $this->status === 'active';
    }

    public function isCompleted(): bool
    {
        return $this->status === 'completed';
    }

    public function isCancelled(): bool
    {
        return $this->status === 'cancelled';
    }

    public function isDisputed(): bool
    {
        return $this->status === 'disputed';
    }

    public function getFormattedTotal(): string
    {
        return $this->currency . ' ' . number_format($this->total, 0);
    }

    public function getStatusBadgeClass(): string
    {
        return match($this->status) {
            'confirmed',
            'active',
            'completed'  => 'nx-badge-good',
            'pending'    => 'nx-badge-warn',
            'disputed'   => 'nx-badge-warn',
            'cancelled',
            'refunded'   => 'nx-badge-danger',
            default      => 'nx-badge',
        };
    }

    public function getDurationDays(): int
    {
        if (!$this->start_date || !$this->end_date) return 0;
        return $this->start_date->diffInDays($this->end_date) + 1;
    }

    // ============================================================
    // Relationships
    // ============================================================
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function cart()
    {
        return $this->belongsTo(Cart::class);
    }

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

    public function items()
    {
        return $this->hasMany(BookingItem::class);
    }

    public function disputes()
    {
        return $this->hasMany(Dispute::class);
    }
}