<?php

namespace Modules\Vrc\Entities;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class VrcServiceReminder extends Model
{
    protected $table = 'vrc_service_reminders';

    protected $fillable = [
        'business_id', 'vehicle_id', 'erp_customer_id', 'type', 'due_date',
        'due_odometer', 'last_service_id', 'status', 'channel', 'scheduled_for',
        'sent_at', 'note',
    ];

    protected $casts = ['due_date' => 'date', 'scheduled_for' => 'datetime', 'sent_at' => 'datetime'];

    public function vehicle(): BelongsTo
    {
        return $this->belongsTo(VrcVehicle::class, 'vehicle_id');
    }

    /** Pending reminders whose due/scheduled date has arrived. */
    public function scopeDue(Builder $q, ?string $onDate = null): Builder
    {
        $date = $onDate ?: now()->toDateString();
        return $q->where('status', 'pending')
            ->where(function ($w) use ($date) {
                $w->whereDate('scheduled_for', '<=', $date)
                    ->orWhere(function ($x) use ($date) {
                        $x->whereNull('scheduled_for')->whereDate('due_date', '<=', $date);
                    });
            });
    }
}
