<?php

namespace App\Models;

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

class Delivery extends Model
{
    use HasFactory;

    protected $fillable = [
        'subscription_id',
        'address_id',
        'scheduled_date',
        'time_slot',
        'status',
        'delivered_at',
        'driver_notes',
        'tracking_code',
    ];

    protected $casts = [
        'scheduled_date' => 'date',
        'delivered_at' => 'datetime',
    ];

    public function subscription()
    {
        return $this->belongsTo(Subscription::class);
    }

    public function address()
    {
        return $this->belongsTo(Address::class);
    }

    public function meals()
    {
        return $this->belongsToMany(Meal::class, 'delivery_meals')
                     ->withPivot('quantity')
                     ->withTimestamps();
    }

    public function scopeUpcoming($query)
    {
        return $query->where('scheduled_date', '>=', now()->toDateString())
                     ->where('status', 'scheduled');
    }

    public function scopeForDate($query, $date)
    {
        return $query->where('scheduled_date', $date);
    }

    public function skip(): void
    {
        $this->update(['status' => 'skipped']);
    }

    public function markDelivered(): void
    {
        $this->update([
            'status' => 'delivered',
            'delivered_at' => now(),
        ]);
    }
}
