<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Traits\BranchScoped;

class VehicleDocument extends Model
{
    use BranchScoped;

    protected $fillable = [
        'branch_id',
        'car_id', 'registration_expiry_date', 'inspection_date',
        'inspection_expiry_date', 'registration_document',
        'inspection_document', 'status', 'notes', 'created_by'
    ];

    protected $casts = [
        'registration_expiry_date' => 'date',
        'inspection_date' => 'date',
        'inspection_expiry_date' => 'date',
    ];

    protected $appends = ['calculated_status'];

    public function car()
    {
        return $this->belongsTo(Car::class);
    }

    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public function getCalculatedStatusAttribute()
    {
        $today = now()->startOfDay();
        $regExpiry = $this->registration_expiry_date->startOfDay();
        $insExpiry = $this->inspection_expiry_date->startOfDay();

        $minExpiry = $regExpiry->min($insExpiry);

        if ($minExpiry->isPast()) {
            return 'expired';
        }

        if ($minExpiry->diffInDays($today) <= 30) {
            return 'expiring_soon';
        }

        return 'valid';
    }
}
