<?php

namespace App\Models;

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

class BookingItem extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'booking_id',
        'placement_id',
        'media_owner_id',
        'availability_slot_id',
        'availability_block_id',
        'booking_type',
        'package_name',
        'start_date',
        'end_date',
        'spots',
        'currency',
        'unit_price',
        'subtotal',
        'platform_fee',
        'total',
        'offer_price',
        'offer_status',
        'counter_price',
        'status',
        'proof_due_at',
        'proof_submitted_at',
        'proof_sla_met',
    ];

    protected $casts = [
        'start_date'         => 'date',
        'end_date'           => 'date',
        'unit_price'         => 'decimal:2',
        'subtotal'           => 'decimal:2',
        'platform_fee'       => 'decimal:2',
        'total'              => 'decimal:2',
        'offer_price'        => 'decimal:2',
        'counter_price'      => 'decimal:2',
        'proof_due_at'       => 'datetime',
        'proof_submitted_at' => 'datetime',
        'proof_sla_met'      => 'boolean',
    ];

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

    public function scopeProofOverdue($query)
    {
        return $query->where('status', 'proof_pending')
                     ->where('proof_due_at', '<', now());
    }

    public function scopeForOwner($query, int $mediaOwnerId)
    {
        return $query->where('media_owner_id', $mediaOwnerId);
    }

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

    // ============================================================
    // Helpers
    // ============================================================
    public function isInstant(): bool
    {
        return $this->booking_type === 'instant';
    }

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

    public function isProofOverdue(): bool
    {
        return $this->isProofPending() &&
               $this->proof_due_at &&
               now()->isAfter($this->proof_due_at);
    }

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

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

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

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

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

    public function getProofTimeRemaining(): string
    {
        if (!$this->proof_due_at) return 'N/A';
        if (now()->isAfter($this->proof_due_at)) return 'Overdue';
        return now()->diffForHumans($this->proof_due_at, true) . ' remaining';
    }

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

    public function placement()
    {
        return $this->belongsTo(Placement::class);
    }

    public function mediaOwner()
    {
        return $this->belongsTo(MediaOwner::class);
    }

    public function availabilitySlot()
    {
        return $this->belongsTo(AvailabilitySlot::class);
    }

    public function availabilityBlock()
    {
        return $this->belongsTo(AvailabilityBlock::class);
    }

    public function creativeAssets()
    {
        return $this->hasMany(CreativeAsset::class);
    }

    public function currentCreative()
    {
        return $this->hasOne(CreativeAsset::class)
                    ->where('is_current', true)
                    ->latest();
    }

    public function proofSubmissions()
    {
        return $this->hasMany(ProofSubmission::class);
    }

    public function latestProof()
    {
        return $this->hasOne(ProofSubmission::class)->latest();
    }

    public function payout()
    {
        return $this->hasOne(Payout::class);
    }

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