<?php

namespace App\Models;

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

class Vehicle extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'school_id',
        'vehicle_number',
        'vehicle_type',
        'vehicle_model',
        'manufacturer',
        'manufacture_year',
        'seating_capacity',
        'registration_number',
        'registration_date',
        'registration_expiry',
        'insurance_number',
        'insurance_expiry',
        'fitness_certificate_number',
        'fitness_expiry',
        'pollution_certificate_number',
        'pollution_expiry',
        'fuel_type',
        'mileage',
        'is_active',
    ];

    protected $casts = [
        'manufacture_year' => 'integer',
        'seating_capacity' => 'integer',
        'registration_date' => 'date',
        'registration_expiry' => 'date',
        'insurance_expiry' => 'date',
        'fitness_expiry' => 'date',
        'pollution_expiry' => 'date',
        'mileage' => 'decimal:2',
        'is_active' => 'boolean',
    ];

    // Relationships
    public function school()
    {
        return $this->belongsTo(School::class);
    }

    public function drivers()
    {
        return $this->belongsToMany(Driver::class, 'vehicle_driver_assignments')
                    ->withPivot('assigned_date', 'is_primary')
                    ->withTimestamps();
    }

    public function routes()
    {
        return $this->hasMany(TransportRoute::class, 'vehicle_id');
    }

    public function trackingLogs()
    {
        return $this->hasMany(VehicleTrackingLog::class, 'vehicle_id');
    }

    // Scopes
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    public function scopeByType($query, $type)
    {
        return $query->where('vehicle_type', $type);
    }

    public function scopeExpiringInsurance($query, $days = 30)
    {
        return $query->whereBetween('insurance_expiry', [now(), now()->addDays($days)]);
    }

    public function scopeExpiringFitness($query, $days = 30)
    {
        return $query->whereBetween('fitness_expiry', [now(), now()->addDays($days)]);
    }

    // Accessors
    public function getIsInsuranceValidAttribute()
    {
        return $this->insurance_expiry && $this->insurance_expiry >= now();
    }

    public function getIsFitnessValidAttribute()
    {
        return $this->fitness_expiry && $this->fitness_expiry >= now();
    }
}
