<?php

namespace App\Models;

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

class BusRoute extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'school_id',
        'bus_id',
        'route_name',
        'route_number',
        'start_point',
        'end_point',
        'pickup_time',
        'drop_time',
        'distance_km',
        'fare_amount',
        'stops',
        'is_active',
    ];

    protected $casts = [
        'pickup_time' => 'datetime',
        'drop_time' => 'datetime',
        'distance_km' => 'decimal:2',
        'fare_amount' => 'decimal:2',
        'stops' => 'array',
        'is_active' => 'boolean',
    ];

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

    public function bus()
    {
        return $this->belongsTo(Bus::class);
    }

    public function assignments()
    {
        return $this->hasMany(BusAssignment::class, 'route_id');
    }

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

    public function scopeForBus($query, $busId)
    {
        return $query->where('bus_id', $busId);
    }

    // Accessors
    public function getDurationInMinutesAttribute()
    {
        return $this->pickup_time->diffInMinutes($this->drop_time);
    }
}
