<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Route extends Model
{
    protected $fillable = [
        'from_city_id',
        'to_city_id',
        'distance_km',
        'estimated_duration_minutes',
        'base_price_per_seat',
        'is_popular',
    ];

    protected function casts(): array
    {
        return [
            'distance_km' => 'decimal:2',
            'estimated_duration_minutes' => 'integer',
            'base_price_per_seat' => 'decimal:2',
            'is_popular' => 'boolean',
        ];
    }

    // Relationships

    /**
     * Get the starting city
     */
    public function fromCity(): BelongsTo
    {
        return $this->belongsTo(City::class, 'from_city_id');
    }

    /**
     * Get the destination city
     */
    public function toCity(): BelongsTo
    {
        return $this->belongsTo(City::class, 'to_city_id');
    }

    /**
     * Get all rides on this route
     */
    public function rides(): HasMany
    {
        return $this->hasMany(Ride::class);
    }

    // Helper Methods

    /**
     * Get the route name (From → To)
     */
    public function getRouteNameAttribute(): string
    {
        return "{$this->fromCity->name} → {$this->toCity->name}";
    }

    /**
     * Get formatted duration
     */
    public function getFormattedDurationAttribute(): string
    {
        $hours = floor($this->estimated_duration_minutes / 60);
        $minutes = $this->estimated_duration_minutes % 60;
        
        if ($hours > 0 && $minutes > 0) {
            return "{$hours}h {$minutes}m";
        } elseif ($hours > 0) {
            return "{$hours}h";
        } else {
            return "{$minutes}m";
        }
    }
}
