<?php

// app/Models/Tax.php

namespace App\Models;

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

class Tax extends Model
{
    use HasFactory;

    protected $fillable = [
        'market_id', 'tax_type_id', 'business_type_id', 'name', 'description',
        'amount', 'valid_from', 'valid_until', 'status', 'metadata',
    ];

    protected $casts = [
        'amount' => 'decimal:2',
        'valid_from' => 'date',
        'valid_until' => 'date',
        'metadata' => 'array',
    ];

    public function market()
    {
        return $this->belongsTo(Market::class);
    }

    public function taxType()
    {
        return $this->belongsTo(TaxType::class);
    }

    public function businessType()
    {
        return $this->belongsTo(BusinessType::class);
    }

    public function payments()
    {
        return $this->hasMany(Payment::class);
    }

    public function exemptions()
    {
        return $this->hasMany(TaxExemption::class);
    }

    public function scopeActive($query)
    {
        return $query->where('status', 'active')
            ->where('valid_from', '<=', now())
            ->where(function ($q) {
                $q->whereNull('valid_until')
                    ->orWhere('valid_until', '>=', now());
            });
    }
}
