<?php

namespace Modules\Vrc\Entities;

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

class VrcCustomerPlan extends Model
{
    protected $table = 'vrc_customer_plans';
    protected $fillable = [
        'business_id', 'erp_customer_id', 'plan_id', 'vehicle_id',
        'purchased_at', 'expires_at', 'visits_remaining', 'status',
    ];
    protected $casts = ['purchased_at' => 'date', 'expires_at' => 'date'];

    public function plan(): BelongsTo
    {
        return $this->belongsTo(VrcServicePlan::class, 'plan_id');
    }

    /** Active = status active, not expired, visits remaining. */
    public function scopeActive(Builder $q): Builder
    {
        return $q->where('status', 'active')
            ->where('visits_remaining', '>', 0)
            ->where(function ($w) {
                $w->whereNull('expires_at')->orWhereDate('expires_at', '>=', now()->toDateString());
            });
    }
}
