<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class DeliveryAssignment extends Model
{
    protected $fillable = [
        'order_id', 'delivery_partner_id', 'vendor_id', 'status',
        'offer_expires_at', 'offer_attempt',
        'arrived_at_vendor_at', 'picked_up_at',
        'cod_amount', 'cod_collected', 'cod_collected_at',
        'arrived_at_customer_at', 'delivered_at',
        'delivery_otp_verified', 'delivery_proof_photo',
        'delivery_attempt_count', 'last_attempt_at',
        'delivery_fee', 'partner_earning', 'earning_credited',
    ];

    protected function casts(): array
    {
        return [
            'offer_expires_at'       => 'datetime',
            'arrived_at_vendor_at'   => 'datetime',
            'picked_up_at'           => 'datetime',
            'cod_collected_at'       => 'datetime',
            'arrived_at_customer_at' => 'datetime',
            'delivered_at'           => 'datetime',
            'last_attempt_at'        => 'datetime',
            'cod_amount'             => 'decimal:2',
            'delivery_fee'           => 'decimal:2',
            'partner_earning'        => 'decimal:2',
            'cod_collected'          => 'boolean',
            'delivery_otp_verified'  => 'boolean',
            'earning_credited'       => 'boolean',
        ];
    }

    public function order()   { return $this->belongsTo(Order::class); }
    public function partner() { return $this->belongsTo(DeliveryPartner::class, 'delivery_partner_id'); }
    public function vendor()  { return $this->belongsTo(Vendor::class); }
    public function stops()   { return $this->hasMany(DeliveryPickupStop::class)->orderBy('sequence'); }

    public function isOfferExpired(): bool
    {
        return $this->status === 'offered'
            && $this->offer_expires_at
            && $this->offer_expires_at->isPast();
    }

    /** All pickup stops collected? (true for a no-stop legacy record too). */
    public function allPickedUp(): bool
    {
        return ! $this->stops()->where('status', '!=', 'picked_up')->exists();
    }
}
