<?php
require_once __DIR__ . '/../bootstrap.php';

use Gestoreasy\Core\Tenant\TenantAdmin;
use Gestoreasy\Core\Tenant\ConnectionManager;
use Gestoreasy\Core\Fiscal\Sped\SpedFiscalGenerator;
use Gestoreasy\Core\Fiscal\Sped\Period as SpedPeriod;
use Gestoreasy\Core\Fiscal\Sped\Validation\SpedValidator;

function assertTrue($c,$m){ if(!$c){ echo "FAIL: $m\n"; exit(1);} }
function assertContainsLinePrefix(array $lines, string $prefix, string $msg){ foreach ($lines as $l){ if (str_starts_with($l, $prefix)) { echo "$msg\n"; return; } } echo "FAIL: $msg\n"; exit(1); }

$tenant = $argv[1] ?? 'default';
TenantAdmin::runMigrations($tenant);
$pdo = ConnectionManager::forTenant($tenant);

// Seed minimal company, product, client
$pdo->exec("INSERT INTO empresas (nome, razao_social, cnpj, ie, email, telefone, estado, cep, logradouro, numero, bairro, cidade, created_at)
    SELECT 'Empresa Demo', 'Empresa Demo Ltda', '12.345.678/0001-99', '123456789', 'contato@demo.com', '(21)3333-3333', 'RJ', '20000000', 'Rua Demo', '100', 'Centro', 'Rio de Janeiro', NOW()
    WHERE NOT EXISTS (SELECT 1 FROM empresas)");
$pdo->exec("INSERT INTO products (codigo, descricao, ean, unidade, ncm) VALUES ('SKU-C190','Produto C190','7890000000000','UN','00000000')");
$pdo->exec("INSERT INTO clients (nome, cnpj) VALUES ('Cliente C190','20.222.333/0001-44')");

// Create a sales order with two items to test per-document aggregation
$pdo->exec("INSERT INTO sales_orders (numero, cliente_id, valor_total, status, created_at) VALUES ('SO-C190-001', (SELECT id FROM clients ORDER BY id DESC LIMIT 1), 150.00, 'aberto', DATE(NOW()))");
$orderId = (int)$pdo->query("SELECT id FROM sales_orders WHERE numero='SO-C190-001'")->fetch()['id'];
$productId = (int)$pdo->query("SELECT id FROM products WHERE codigo='SKU-C190'")->fetch()['id'];
$pdo->exec("INSERT INTO sales_order_items (order_id, product_id, quantidade, preco, total) VALUES ($orderId, $productId, 1.000, 50.00, 50.00)");
$pdo->exec("INSERT INTO sales_order_items (order_id, product_id, quantidade, preco, total) VALUES ($orderId, $productId, 2.000, 50.00, 100.00)");

$gen = new SpedFiscalGenerator($pdo);
$period = new SpedPeriod((int)date('Y'), (int)date('n'));
$lines = $gen->generate($period, ['perfil' => 'A', 'ind_ativ' => 1]);

assertTrue(in_array('|C001|0|', $lines, true), 'Bloco C aberto');
assertContainsLinePrefix($lines, '|C100|', 'Possui C100 do documento');
assertContainsLinePrefix($lines, '|C170|', 'Possui itens C170');
assertContainsLinePrefix($lines, '|C190|', 'Possui consolidação C190');

// Compute per-document sums of VL_ITEM by (CST,CFOP) and compare to C190 VL_OPR
$inDoc = false; $agg = []; $checked = false;
foreach ($lines as $l){
  if (str_starts_with($l, '|C100|')) { $inDoc = true; $agg = []; continue; }
  if ($inDoc && str_starts_with($l, '|C170|')) {
    $p = explode('|', $l);
    $cst = (string)($p[9] ?? '');
    $cfop = (string)($p[10] ?? '');
    $vl_item = (float)($p[7] ?? 0);
    $key = $cst.'|'.$cfop;
    if (!isset($agg[$key])) $agg[$key] = 0.0;
    $agg[$key] += $vl_item;
  }
  if ($inDoc && str_starts_with($l, '|C190|')) {
    $p = explode('|', $l);
    $cst = (string)($p[2] ?? '');
    $cfop = (string)($p[3] ?? '');
    $vl_opr = (float)($p[5] ?? 0);
    $key = $cst.'|'.$cfop;
    $sum = (float)($agg[$key] ?? 0);
    assertTrue(abs($vl_opr - $sum) <= 0.02, 'C190 VL_OPR confere com soma de VL_ITEM do documento');
    $checked = true;
  }
}
assertTrue($checked, 'Ao menos um C190 foi verificado');

// Run validator, expect no issues for C190 aggregation
$issues = SpedValidator::validateSpedLines($lines);
foreach ($issues as $i){ if (str_contains($i, 'C190 VL_OPR')){ echo "FAIL: Validador encontrou problema em C190 VL_OPR: $i\n"; exit(1);} }

echo "OK: C190 por documento consolida VL_OPR corretamente e valida sem issues\n";