<?php

namespace App\Models;

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

class Tax extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'code',
        'rate',
        'description',
        'is_active',
        'is_compound',
        'order',
    ];

    protected $casts = [
        'rate' => 'decimal:2',
        'is_active' => 'boolean',
        'is_compound' => 'boolean',
        'order' => 'integer',
    ];

    /**
     * Get all active taxes ordered.
     */
    public static function getActive()
    {
        return static::where('is_active', true)
            ->orderBy('order')
            ->get();
    }

    /**
     * Calculate tax amount for a given subtotal.
     */
    public function calculate(float $amount): float
    {
        return round($amount * ($this->rate / 100), 2);
    }

    /**
     * Calculate taxes for a subtotal and return detailed breakdown.
     */
    public static function calculateTaxes(float $subtotal): array
    {
        $taxes = static::getActive();
        $breakdown = [];
        $totalTax = 0;
        $baseForCompound = $subtotal;

        // First pass: non-compound taxes
        foreach ($taxes as $tax) {
            if (!$tax->is_compound) {
                $amount = $tax->calculate($subtotal);
                $breakdown[] = [
                    'id' => $tax->id,
                    'name' => $tax->name,
                    'code' => $tax->code,
                    'rate' => $tax->rate,
                    'amount' => $amount,
                ];
                $totalTax += $amount;
                $baseForCompound += $amount;
            }
        }

        // Second pass: compound taxes (calculated on subtotal + previous taxes)
        foreach ($taxes as $tax) {
            if ($tax->is_compound) {
                $amount = $tax->calculate($baseForCompound);
                $breakdown[] = [
                    'id' => $tax->id,
                    'name' => $tax->name,
                    'code' => $tax->code,
                    'rate' => $tax->rate,
                    'amount' => $amount,
                ];
                $totalTax += $amount;
            }
        }

        return [
            'breakdown' => $breakdown,
            'total' => $totalTax,
        ];
    }

    /**
     * Scope for active taxes.
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    /**
     * Scope for ordered taxes.
     */
    public function scopeOrdered($query)
    {
        return $query->orderBy('order');
    }
}
