<?php

namespace App\Models;

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

class TaxConfig extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'code',
        'rate',
        'is_active',
        'is_default',
        'type',
        'description',
    ];

    protected function casts(): array
    {
        return [
            'rate' => 'decimal:2',
            'is_active' => 'boolean',
            'is_default' => 'boolean',
        ];
    }

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

    public function scopeDefault($query)
    {
        return $query->where('is_default', true);
    }

    public static function getActiveTaxes()
    {
        return self::active()->orderBy('is_default', 'desc')->get();
    }

    public static function getDefaultTax()
    {
        return self::active()->default()->first() ?? self::active()->first();
    }

    public static function calculateTax($subtotal, $taxConfigs = null)
    {
        $taxConfigs = $taxConfigs ?? self::getActiveTaxes();
        $totalTax = 0;
        $taxDetails = [];

        foreach ($taxConfigs as $tax) {
            $taxAmount = $subtotal * ($tax->rate / 100);
            $totalTax += $taxAmount;
            $taxDetails[] = [
                'tax_id' => $tax->id,
                'tax_name' => $tax->name,
                'tax_code' => $tax->code,
                'tax_rate' => $tax->rate,
                'tax_amount' => $taxAmount,
            ];
        }

        return [
            'total_tax' => $totalTax,
            'tax_details' => $taxDetails,
        ];
    }
}
