<?php

namespace App\Models;

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

class RouteStop extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'transport_route_id',
        'stop_name',
        'stop_code',
        'address',
        'latitude',
        'longitude',
        'pickup_time',
        'drop_time',
        'stop_order',
        'fare',
        'is_active',
    ];

    protected $casts = [
        'latitude' => 'decimal:8',
        'longitude' => 'decimal:8',
        'stop_order' => 'integer',
        'fare' => 'decimal:2',
        'is_active' => 'boolean',
    ];

    // Relationships
    public function transportRoute()
    {
        return $this->belongsTo(TransportRoute::class, 'transport_route_id');
    }

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

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

    public function scopeForRoute($query, $routeId)
    {
        return $query->where('transport_route_id', $routeId);
    }

    public function scopeOrdered($query)
    {
        return $query->orderBy('stop_order');
    }

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