<?php

namespace App\Models;

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

class CartItem extends Model
{
    use HasFactory;

    protected $fillable = [
        'cart_id',
        'placement_id',
        'booking_type',
        'start_date',
        'end_date',
        'availability_slot_id',
        'package_name',
        'spots',
        'currency',
        'unit_price',
        'quantity',
        'subtotal',
        'platform_fee',
        'total',
        'offer_price',
        'offer_status',
        'counter_price',
    ];

    protected $casts = [
        'start_date'   => 'date',
        'end_date'     => 'date',
        'unit_price'   => 'decimal:2',
        'quantity'     => 'decimal:2',
        'subtotal'     => 'decimal:2',
        'platform_fee' => 'decimal:2',
        'total'        => 'decimal:2',
        'offer_price'  => 'decimal:2',
        'counter_price'=> 'decimal:2',
    ];

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

    public function isOffer(): bool
    {
        return $this->booking_type === 'offer';
    }

    public function isOfferAccepted(): bool
    {
        return $this->offer_status === 'accepted';
    }

    public function isOfferPending(): bool
    {
        return $this->offer_status === 'pending';
    }

    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 calculatePlatformFee(float $rate = 0.10): float
    {
        return round($this->subtotal * $rate, 2);
    }

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

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

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