<?php

namespace App\Services;

use App\Models\Setting;
use Illuminate\Support\Facades\Log;

class TaxService
{
    protected $taxRates = [
        'FR' => ['name' => 'TVA', 'rate' => 20],
        'BE' => ['name' => 'TVA', 'rate' => 21],
        'DE' => ['name' => 'MwSt', 'rate' => 19],
        'ES' => ['name' => 'IVA', 'rate' => 21],
        'IT' => ['name' => 'IVA', 'rate' => 22],
        'CI' => ['name' => 'TVA', 'rate' => 18],
        'SN' => ['name' => 'TVA', 'rate' => 18],
        'CM' => ['name' => 'TVA', 'rate' => 19.25],
        'BF' => ['name' => 'TVA', 'rate' => 18],
        'ML' => ['name' => 'TVA', 'rate' => 18],
        'TG' => ['name' => 'TVA', 'rate' => 18],
        'BJ' => ['name' => 'TVA', 'rate' => 18],
        'NE' => ['name' => 'TVA', 'rate' => 19],
        'GN' => ['name' => 'TVA', 'rate' => 18],
    ];

    public function getTaxRate($countryCode)
    {
        $countryCode = strtoupper($countryCode);
        
        $customRate = Setting::get("tax_rate_{$countryCode}");
        if ($customRate !== null) {
            return floatval($customRate);
        }

        return $this->taxRates[$countryCode]['rate'] ?? 0;
    }

    public function getTaxName($countryCode)
    {
        $countryCode = strtoupper($countryCode);
        return $this->taxRates[$countryCode]['name'] ?? 'Tax';
    }

    public function calculateTax($amount, $countryCode)
    {
        $rate = $this->getTaxRate($countryCode);
        return round(($amount * $rate) / 100, 2);
    }

    public function calculatePriceWithTax($amount, $countryCode)
    {
        $tax = $this->calculateTax($amount, $countryCode);
        return [
            'subtotal' => $amount,
            'tax_rate' => $this->getTaxRate($countryCode),
            'tax_name' => $this->getTaxName($countryCode),
            'tax_amount' => $tax,
            'total' => $amount + $tax,
        ];
    }

    public function calculatePriceFromTaxIncluded($totalWithTax, $countryCode)
    {
        $rate = $this->getTaxRate($countryCode);
        $subtotal = round($totalWithTax / (1 + ($rate / 100)), 2);
        $tax = $totalWithTax - $subtotal;

        return [
            'subtotal' => $subtotal,
            'tax_rate' => $rate,
            'tax_name' => $this->getTaxName($countryCode),
            'tax_amount' => $tax,
            'total' => $totalWithTax,
        ];
    }

    public function isEUCountry($countryCode)
    {
        $euCountries = ['AT', 'BE', 'BG', 'HR', 'CY', 'CZ', 'DK', 'EE', 'FI', 'FR', 
                        'DE', 'GR', 'HU', 'IE', 'IT', 'LV', 'LT', 'LU', 'MT', 'NL', 
                        'PL', 'PT', 'RO', 'SK', 'SI', 'ES', 'SE'];
        return in_array(strtoupper($countryCode), $euCountries);
    }

    public function validateVatNumber($vatNumber, $countryCode)
    {
        $vatNumber = preg_replace('/[^A-Z0-9]/', '', strtoupper($vatNumber));
        
        if (strlen($vatNumber) < 8 || strlen($vatNumber) > 14) {
            return false;
        }

        return true;
    }

    public function generateInvoiceNumber()
    {
        $prefix = Setting::get('invoice_prefix', 'INV');
        $year = date('Y');
        $month = date('m');
        
        $lastNumber = Setting::get('last_invoice_number', 0);
        $newNumber = $lastNumber + 1;
        
        Setting::set('last_invoice_number', $newNumber);
        
        return sprintf('%s-%s%s-%05d', $prefix, $year, $month, $newNumber);
    }

    public function getAllTaxRates()
    {
        return $this->taxRates;
    }
}
