<?php
namespace Gestoreasy\Core\Fiscal;

// Calculadora fiscal mínima para preview (RJ homolog)
// NOTA: valores ilustrativos, não substituir validação fiscal oficial.
class Calculator {
    public function previewNfceRJ(array $items, array $opts = []): array {
        $env = $opts['environment'] ?? 'homolog';
        $normalized = [];
        $subtotal = 0.0;
        $totalImpostos = 0.0;
        foreach ($items as $i) {
            $q = (float)($i['quantidade'] ?? $i['qtd'] ?? 1);
            $p = (float)($i['preco'] ?? $i['unit'] ?? 0);
            $ncm = (string)($i['ncm'] ?? '00000000');
            $cfop = (string)($i['cfop'] ?? '5102');
            $csosn = (string)($i['csosn'] ?? '102');
            $pisCst = (string)($i['csts']['pis'] ?? $i['pis_cst'] ?? '01');
            $cofCst = (string)($i['csts']['cofins'] ?? $i['cofins_cst'] ?? '01');
            $total = $q * $p;
            // Heurística SN 102: ICMS com crédito zero; aplicar PIS/COFINS padrão 1.65%/7.6% (ilustrativo)
            $pis = round($total * 0.0165, 2);
            $cof = round($total * 0.076, 2);
            $icms = 0.00;
            $tributos = $pis + $cof + $icms;
            $normalized[] = [
                'descricao' => (string)($i['descricao'] ?? $i['nome'] ?? 'Item'),
                'quantidade' => $q,
                'preco' => $p,
                'total' => $total,
                'ncm' => $ncm,
                'cfop' => $cfop,
                'csosn' => $csosn,
                'pis' => ['cst' => $pisCst, 'valor' => $pis],
                'cofins' => ['cst' => $cofCst, 'valor' => $cof],
                'icms' => ['csosn' => $csosn, 'valor' => $icms],
            ];
            $subtotal += $total;
            $totalImpostos += $tributos;
        }
        $desconto = 0.00;
        $totalNota = $subtotal - $desconto;
        return [
            'environment' => $env,
            'items' => $normalized,
            'totals' => [
                'subtotal' => round($subtotal, 2),
                'desconto' => round($desconto, 2),
                'impostos' => round($totalImpostos, 2),
                'total' => round($totalNota, 2),
            ],
            'observacoes' => 'Pré-visualização de NFC-e (RJ homolog - mock).',
        ];
    }
}