<?php

namespace App\Models;

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

class TransportRoute extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'school_id',
        'vehicle_id',
        'driver_id',
        'route_name',
        'route_code',
        'start_location',
        'end_location',
        'distance_km',
        'estimated_duration_minutes',
        'fare',
        'is_active',
    ];

    protected $casts = [
        'distance_km' => 'decimal:2',
        'estimated_duration_minutes' => 'integer',
        'fare' => 'decimal:2',
        'is_active' => 'boolean',
    ];

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

    public function vehicle()
    {
        return $this->belongsTo(Vehicle::class);
    }

    public function driver()
    {
        return $this->belongsTo(Driver::class);
    }

    public function stops()
    {
        return $this->hasMany(RouteStop::class, 'transport_route_id');
    }

    public function studentTransports()
    {
        return $this->hasMany(StudentTransport::class, 'transport_route_id');
    }

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

    public function scopeForVehicle($query, $vehicleId)
    {
        return $query->where('vehicle_id', $vehicleId);
    }

    public function scopeForDriver($query, $driverId)
    {
        return $query->where('driver_id', $driverId);
    }

    public function scopeSearch($query, $search)
    {
        return $query->where(function($q) use ($search) {
            $q->where('route_name', 'like', "%{$search}%")
              ->orWhere('route_code', 'like', "%{$search}%");
        });
    }

    // Accessors
    public function getStopCountAttribute()
    {
        return $this->stops()->count();
    }

    public function getStudentCountAttribute()
    {
        return $this->studentTransports()->count();
    }
}
