<?php

namespace App\Models;

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

class PricingRule extends Model
{
    use HasFactory;

    protected $table = 'pricing_rules';

    protected $fillable = [
        'price_per_kg',
        'effective_from',
        'effective_to',
        'is_active',
    ];

    protected $casts = [
        'price_per_kg' => 'decimal:4',
        'effective_from' => 'date',
        'effective_to' => 'date',
        'is_active' => 'boolean',
    ];

    /**
     * Reglas aplicables a una fecha concreta (cobro por peso).
     */
    /**
     * @param  \Carbon\Carbon|string  $fecha
     */
    public function scopeVigenteEn($query, $fecha)
    {
        $d = $fecha instanceof Carbon ? $fecha : Carbon::parse($fecha);
        $dateStr = $d->toDateString();

        return $query->where('is_active', true)
            ->where(function ($q) use ($dateStr): void {
                $q->whereNull('effective_from')
                    ->orWhereDate('effective_from', '<=', $dateStr);
            })
            ->where(function ($q) use ($dateStr): void {
                $q->whereNull('effective_to')
                    ->orWhereDate('effective_to', '>=', $dateStr);
            });
    }
}
