<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class VehicleTypePricing extends Model
{
    use HasFactory;

    protected $table = 'vehicle_type_pricing';

    protected $fillable = [
        'tenant_id',
        'vehicle_type_id',
        'base_fare',
        'per_km_rate',
        'per_minute_rate',
        'per_hour_rate',
        'ot_wait_rate',
        'extra_stop_rate',
        'per_mile_rate',
        'std_gear_rate',
        'minimum_fare',
        'currency',
        'pricing_type',
        'is_active',
        'valid_from',
        'valid_until',
    ];

    protected $casts = [
        'base_fare'        => 'decimal:2',
        'per_km_rate'      => 'decimal:2',
        'per_minute_rate'  => 'decimal:2',
        'per_hour_rate'    => 'decimal:2',
        'ot_wait_rate'     => 'decimal:2',
        'extra_stop_rate'  => 'decimal:2',
        'per_mile_rate'    => 'decimal:2',
        'std_gear_rate'    => 'decimal:2',
        'minimum_fare'     => 'decimal:2',
        'is_active'        => 'boolean',
        'valid_from'       => 'datetime',
        'valid_until'      => 'datetime',
    ];

    /**
     * Relationship with Tenant
     */
    public function tenant(): BelongsTo
    {
        return $this->belongsTo(Tenant::class);
    }

    /**
     * Relationship with Vehicle Type
     */
    public function vehicleType(): BelongsTo
    {
        return $this->belongsTo(VehicleType::class, 'vehicle_type_id');
    }

    /**
     * Scope to get active pricing
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true)
            ->where(function ($q) {
                $q->whereNull('valid_from')->orWhere('valid_from', '<=', now());
            })
            ->where(function ($q) {
                $q->whereNull('valid_until')->orWhere('valid_until', '>=', now());
            });
    }

    /**
     * Scope for tenant
     */
    public function scopeForTenant($query, $tenantId)
    {
        return $query->where('tenant_id', $tenantId);
    }
}
