<?php
namespace App\Services;
use App\Models\Setting;
use App\Models\TaxRate;
class GhanaTaxService {
    public static function rate(string $code, float $fallback): float {
        $row = TaxRate::where('code', $code)->where('is_active', true)->first();
        if ($row) return (float) $row->rate_percent;
        return (float) Setting::get('tax.'.strtolower($code), $fallback);
    }
    /** Ghana VAT regime: NHIL + GETFund + COVID levies on the VAT-exclusive base, then 15% VAT on (base + levies). */
    public static function salesTax(float $base): array {
        $nhil = round($base * self::rate('NHIL', 2.5) / 100, 2);
        $getfund = round($base * self::rate('GETFUND', 2.5) / 100, 2);
        $covid = round($base * self::rate('COVID', 1.0) / 100, 2);
        $vat = round(($base + $nhil + $getfund + $covid) * self::rate('VAT', 15) / 100, 2);
        return ['nhil' => $nhil, 'getfund' => $getfund, 'covid' => $covid, 'vat' => $vat, 'total_tax' => round($nhil + $getfund + $covid + $vat, 2), 'grand' => round($base + $nhil + $getfund + $covid + $vat, 2)];
    }
    public static function withholding(float $base, string $type = 'goods'): float {
        $code = $type === 'services' ? 'WHT-SERVICES' : 'WHT-GOODS';
        $fb = $type === 'services' ? 7.5 : 3.0;
        return round($base * self::rate($code, $fb) / 100, 2);
    }
}
