<?php

namespace App\Services;

use App\Models\Product;

class TaxService
{
    /**
     * Calculate tax amount for a single item (tax-inclusive formula)
     * Formula: tax = (price * qty) * (tax_rate / (100 + tax_rate))
     * 
     * @param float $price Unit price (tax-inclusive)
     * @param int $qty Quantity
     * @param float|null $taxRate Tax rate percentage (e.g., 18 for 18%)
     * @return float Tax amount
     */
    public function calculateItemTax(float $price, int $qty, ?float $taxRate): float
    {
        if (!$taxRate || $taxRate <= 0) {
            return 0.0;
        }

        $itemTotal = $price * $qty;
        // Tax-inclusive formula: extract tax from inclusive price
        $taxAmount = $itemTotal * ($taxRate / (100 + $taxRate));
        
        return round($taxAmount, 2);
    }

    /**
     * Get tax rate for a product
     * Returns tax_rate_snapshot from product
     * 
     * @param Product $product
     * @param mixed $variant (deprecated - kept for backward compatibility, not used)
     * @return float Tax rate percentage (0 if no tax)
     */
    public function getTaxRateForItem(Product $product, $variant = null): float
    {
        // Variants inherit tax from parent product
        // Prefer snapshot; fallback to active tax relation
        if ($product->tax_rate_snapshot !== null) {
            return (float) $product->tax_rate_snapshot;
        }

        // Fallback: use related tax if available and active
        if ($product->relationLoaded('tax')) {
            $tax = $product->tax;
        } else {
            $tax = $product->tax()->where('is_active', true)->first();
        }

        if ($tax && $tax->is_active) {
            if ($tax->type === 'single') {
                return (float) $tax->rate;
            }

            // For component taxes, sum component rates
            if (!empty($tax->components) && is_array($tax->components)) {
                return (float) array_sum(array_column($tax->components, 'rate'));
            }
        }

        return 0.0;
    }

    /**
     * Calculate and aggregate tax for multiple order items
     * This is a helper method that can be used for validation or recalculation
     * 
     * @param array $items Array of items with 'price', 'qty', 'product_id', 'product_variant_id'
     * @return float Total tax amount
     */
    public function calculateOrderTax(array $items): float
    {
        $totalTax = 0.0;

        foreach ($items as $item) {
            $product = Product::find($item['product_id']);
            if (!$product) {
                continue;
            }

            // Unified model: product is the actual sellable item
            $taxRate = $this->getTaxRateForItem($product);
            $taxAmount = $this->calculateItemTax(
                $item['price'],
                $item['qty'],
                $taxRate
            );

            $totalTax += $taxAmount;
        }

        return round($totalTax, 2);
    }
}
