<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once __DIR__ . '/_common.php';

$desde  = date_or_null($_GET['desde'] ?? '') ?: date('Y-m-01');
$hasta  = date_or_null($_GET['hasta'] ?? '') ?: date('Y-m-t');
$pto    = trim($_GET['punto_venta'] ?? '');
$tipo   = trim($_GET['cbte_tipo'] ?? '');
$export = trim($_GET['export'] ?? ''); // csv | arca | ''

$wh = ["afi.fecha_cbte BETWEEN :desde AND :hasta", "afi.resultado = 'A'"];
$params = [':desde' => $desde, ':hasta' => $hasta];

if ($pto !== '')  { $wh[] = "afi.punto_venta = :pto"; $params[':pto'] = (int)$pto; }
if ($tipo !== '') { $wh[] = "afi.cbte_tipo = :tipo"; $params[':tipo'] = (int)$tipo; }

list($where, $params) = build_query_range($wh, $params);

$sql = "
SELECT
  afi.id AS factura_afip_id,
  afi.fecha_cbte,
  afi.cbte_tipo,
  afi.cbte_letra,
  afi.punto_venta,
  afi.cbte_numero,
  c.customer_name AS cliente,
  c.customer_cuit AS cuit,
  c.customer_iva_cond AS condicion,
  afi.doc_tipo,
  afi.doc_nro,
  afi.mon_id,
  afi.mon_cotiz,
  afi.imp_neto,
  afi.imp_iva,
  afi.imp_trib,
  afi.imp_op_ex,
  afi.imp_tot_conc,
  afi.imp_total,
  afi.cae,
  afi.cae_vto,

  COALESCE(SUM(CASE WHEN it.iva_porcentaje = 21.00  THEN it.importe_iva ELSE 0 END),0) AS iva_21,
  COALESCE(SUM(CASE WHEN it.iva_porcentaje = 10.50 THEN it.importe_iva ELSE 0 END),0) AS iva_105,
  COALESCE(SUM(CASE WHEN it.iva_porcentaje = 27.00  THEN it.importe_iva ELSE 0 END),0) AS iva_27
FROM facturas_afip_info afi
LEFT JOIN customers c ON c.customer_id = afi.customer_id
LEFT JOIN facturas_afip_items it ON it.factura_afip_id = afi.id
$where
GROUP BY afi.id
ORDER BY afi.fecha_cbte ASC, afi.punto_venta ASC, afi.cbte_tipo ASC, afi.cbte_numero ASC
";

try {
  $pdo = db();
  $stmt = $pdo->prepare($sql);
  $stmt->execute($params);
  $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
  http_response_code(500);
  echo "<pre style='padding:12px;background:#fff3cd;border:1px solid #ffeeba'>ERROR SQL/PHP:\n"
     . htmlspecialchars($e->getMessage()) . "\n\nSQL:\n" . htmlspecialchars($sql) . "</pre>";
  exit;
}

/**
 * ====== SIGNO por tipo de comprobante ======
 * NC => -1 | ND/Factura => +1
 */
function is_nc_venta(array $r): bool {
  $tc = (int)($r['cbte_tipo'] ?? 0);
  return in_array($tc, [3,8,13], true);
}
function is_nd_venta(array $r): bool {
  $tc = (int)($r['cbte_tipo'] ?? 0);
  return in_array($tc, [2,7,12], true);
}
function sign_venta(array $r): int {
  return is_nc_venta($r) ? -1 : 1;
}
function badge_tipo_venta(array $r): array {
  if (is_nc_venta($r)) return ['NC', 'badge-nc'];
  if (is_nd_venta($r)) return ['ND', 'badge-nd'];
  return ['FC', 'badge-fc'];
}

/**
 * ✅ EXPORT ARCA (ZIP) — antes de imprimir HTML o CSV
 */
if ($export === 'arca') {
  export_arca_zip_ventas($pdo, $desde, $hasta, $pto, $tipo);
  exit;
}

/**
 * ✅ EXPORT CSV (con signo para NC)
 */
if ($export === 'csv') {
  header('Content-Type: text/csv; charset=UTF-8');
  header('Content-Disposition: attachment; filename="libro_iva_ventas_'.$desde.'_a_'.$hasta.'.csv"');

  $out = fopen('php://output', 'w');
  // BOM UTF-8 (Excel)
  fprintf($out, chr(0xEF).chr(0xBB).chr(0xBF));

  fputcsv($out, [
    'Fecha','Tipo','Letra','PtoVta','Nro','Cliente','CUIT','Cond IVA','DocTipo','DocNro',
    'Mon','Cotiz',
    'Neto grav (ARS)','IVA (ARS)','IVA21 (ARS)','IVA10.5 (ARS)','IVA27 (ARS)',
    'Exento (ARS)','No grav (ARS)','Otros (ARS)','Total (ARS)',
    'CAE','Vto CAE','SIGNO'
  ], ';');

  foreach ($rows as $r) {
    $sign = sign_venta($r);

    $cot = (float)($r['mon_cotiz'] ?? 1);
    if (!$cot) $cot = 1;

    $ivaCalc = (float)$r['iva_21'] + (float)$r['iva_105'] + (float)$r['iva_27'];
    if ($ivaCalc <= 0) $ivaCalc = (float)$r['imp_iva'];

    fputcsv($out, [
      $r['fecha_cbte'], $r['cbte_tipo'], $r['cbte_letra'], $r['punto_venta'], $r['cbte_numero'],
      $r['cliente'], $r['cuit'], $r['condicion'], $r['doc_tipo'], $r['doc_nro'],
      $r['mon_id'], $r['mon_cotiz'],

      numcsv($sign * (float)$r['imp_neto'] * $cot),
      numcsv($sign * $ivaCalc * $cot),
      numcsv($sign * (float)$r['iva_21'] * $cot),
      numcsv($sign * (float)$r['iva_105'] * $cot),
      numcsv($sign * (float)$r['iva_27'] * $cot),
      numcsv($sign * (float)$r['imp_op_ex'] * $cot),
      numcsv($sign * (float)$r['imp_tot_conc'] * $cot),
      numcsv($sign * (float)$r['imp_trib'] * $cot),
      numcsv($sign * (float)$r['imp_total'] * $cot),

      $r['cae'], $r['cae_vto'],
      ($sign < 0 ? '-1' : '1')
    ], ';');
  }
  fclose($out);
  exit;
}

/**
 * ✅ KPI (ARS) con signo (NC resta)
 */
$sum = [
  'neto_gravado' => 0,
  'iva'          => 0,
  'otros'        => 0,
  'exento'       => 0,
  'no_gravado'   => 0,
  'total'        => 0,
];

foreach ($rows as $r) {
  $sign = sign_venta($r);

  $cot = (float)($r['mon_cotiz'] ?? 1);
  if (!$cot) $cot = 1;

  $ivaCalc = (float)$r['iva_21'] + (float)$r['iva_105'] + (float)$r['iva_27'];
  if ($ivaCalc <= 0) $ivaCalc = (float)$r['imp_iva'];

  $sum['neto_gravado'] += $sign * ((float)$r['imp_neto'] * $cot);
  $sum['iva']          += $sign * ($ivaCalc * $cot);
  $sum['otros']        += $sign * ((float)$r['imp_trib'] * $cot);
  $sum['exento']       += $sign * ((float)$r['imp_op_ex'] * $cot);
  $sum['no_gravado']   += $sign * ((float)$r['imp_tot_conc'] * $cot);
  $sum['total']        += $sign * ((float)$r['imp_total'] * $cot);
}

$title = "Libro IVA Ventas";
ob_start();
?>

<style>
:root{
  --fs-base: 13.5px;  /* general */
  --fs-table: 13px;   /* tabla */
}

.conta-wrap { font-size: var(--fs-base); }

.conta-wrap .form-label { font-size: calc(var(--fs-base) - 1.2px); margin-bottom:.25rem; color:#1f3b64; font-weight:700; }
.conta-wrap .form-control,
.conta-wrap .form-select { font-size: var(--fs-base); padding:.40rem .55rem; border-radius:.65rem; }

.conta-wrap .card { border-radius: 14px; }
.conta-wrap .btn { border-radius: .70rem; }

.btn-corp{
  background:#0b5ed7;
  border-color:#0b5ed7;
  color:#fff;
  box-shadow: 0 6px 18px rgba(13,110,253,.12);
}
.btn-corp:hover{ filter: brightness(.97); color:#fff; }

.btn-soft{
  border-color: rgba(13,110,253,.35);
  color:#0b5ed7;
  background: rgba(13,110,253,.07);
}
.btn-soft:hover{ background: rgba(13,110,253,.11); color:#0b5ed7; }

.kpi { padding:.75rem .9rem; }
.kpi small { display:block; font-size: calc(var(--fs-base) - 1.3px); color:#5c6f91; letter-spacing:.2px; }
.kpi .kpi-val { font-size: calc(var(--fs-base) + 3.0px); font-weight: 800; color:#0b2f5b; }

.conta-table{ font-size: var(--fs-table); }
.conta-table th{
  font-size: calc(var(--fs-table) - 1.0px);
  color:#264a7a;
  letter-spacing:.2px;
  white-space: nowrap;
}
.conta-table td{ white-space: nowrap; }
.conta-table thead.table-light{ background:#f2f7ff; }
.conta-table tbody tr:hover{ background: rgba(13,110,253,.04); }
.conta-table.table-sm > :not(caption) > * > * { padding:.36rem .45rem; }

.text-mono{
  font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
}

/* Badges */
.badge-fc{
  background: rgba(13,110,253,.10);
  color:#0b5ed7;
  border:1px solid rgba(13,110,253,.22);
  font-weight:800;
}
.badge-nd{
  background: rgba(25,135,84,.10);
  color:#146c43;
  border:1px solid rgba(25,135,84,.22);
  font-weight:800;
}
.badge-nc{
  background: rgba(220,53,69,.12);
  color:#b02a37;
  border:1px solid rgba(220,53,69,.25);
  font-weight:800;
}
.neg{ color:#b02a37; font-weight:700; }
</style>

<div class="conta-wrap">

<div class="card shadow-sm border-0 mb-3">
  <div class="card-body">
    <form class="row g-2 align-items-end" method="get">
      <div class="col-12 col-md-3">
        <label class="form-label">Desde</label>
        <input type="date" name="desde" value="<?= h($desde) ?>" class="form-control">
      </div>
      <div class="col-12 col-md-3">
        <label class="form-label">Hasta</label>
        <input type="date" name="hasta" value="<?= h($hasta) ?>" class="form-control">
      </div>
      <div class="col-12 col-md-2">
        <label class="form-label">Punto de venta</label>
        <input type="number" name="punto_venta" value="<?= h($pto) ?>" class="form-control" placeholder="1">
      </div>
      <div class="col-12 col-md-2">
        <label class="form-label">Cbte tipo</label>
        <input type="number" name="cbte_tipo" value="<?= h($tipo) ?>" class="form-control" placeholder="1 / 6 / 11 / 3 / 8 / 13">
      </div>
      <div class="col-12 col-md-2 d-flex gap-2">
        <button class="btn btn-corp w-100" type="submit">Filtrar</button>

        <a class="btn btn-soft w-100"
           href="?desde=<?= h($desde) ?>&hasta=<?= h($hasta) ?>&punto_venta=<?= urlencode($pto) ?>&cbte_tipo=<?= urlencode($tipo) ?>&export=arca">
          ARCA
        </a>

        <a class="btn btn-outline-secondary w-100"
           href="?desde=<?= h($desde) ?>&hasta=<?= h($hasta) ?>&punto_venta=<?= urlencode($pto) ?>&cbte_tipo=<?= urlencode($tipo) ?>&export=csv">
          CSV
        </a>
      </div>
    </form>
  </div>
</div>

<div class="row g-3 mb-3">
  <div class="col-6 col-lg-3"><div class="card border-0 shadow-sm"><div class="card-body kpi"><small>Neto (ARS)</small><div class="kpi-val">$ <?= money($sum['neto_gravado']) ?></div></div></div></div>
  <div class="col-6 col-lg-3"><div class="card border-0 shadow-sm"><div class="card-body kpi"><small>IVA (ARS)</small><div class="kpi-val">$ <?= money($sum['iva']) ?></div></div></div></div>
  <div class="col-6 col-lg-3"><div class="card border-0 shadow-sm"><div class="card-body kpi"><small>Otros (ARS)</small><div class="kpi-val">$ <?= money($sum['otros']) ?></div></div></div></div>
  <div class="col-6 col-lg-3"><div class="card border-0 shadow-sm"><div class="card-body kpi"><small>Total (ARS)</small><div class="kpi-val">$ <?= money($sum['total']) ?></div></div></div></div>
</div>

<div class="card shadow-sm border-0">
  <div class="card-body">
    <div class="table-responsive">
      <table class="table table-sm table-hover align-middle conta-table">
        <thead class="table-light">
          <tr>
            <th>Fecha</th><th>Tipo</th><th>Letra</th><th>PtoVta</th><th>Nro</th>
            <th>Cliente</th><th>CUIT</th><th>Cond IVA</th><th>Moneda</th>
            <th class="text-end">Neto</th><th class="text-end">IVA</th>
            <th class="text-end">IVA21</th><th class="text-end">IVA10.5</th><th class="text-end">IVA27</th>
            <th class="text-end">Exento</th><th class="text-end">No grav.</th><th class="text-end">Otros</th>
            <th class="text-end">Total</th>
          </tr>
        </thead>
        <tbody>
        <?php if (!$rows): ?>
          <tr><td colspan="18" class="text-center text-muted py-4">Sin resultados.</td></tr>
        <?php endif; ?>

        <?php foreach ($rows as $r):
          $sign = sign_venta($r);
          [$badgeTxt, $badgeCls] = badge_tipo_venta($r);

          $cot = (float)($r['mon_cotiz'] ?? 1); if (!$cot) $cot = 1;
          $ivaCalc = (float)$r['iva_21'] + (float)$r['iva_105'] + (float)$r['iva_27'];
          if ($ivaCalc <= 0) $ivaCalc = (float)$r['imp_iva'];

          $neto = $sign * (float)$r['imp_neto'] * $cot;
          $iva  = $sign * $ivaCalc * $cot;
          $iva21  = $sign * (float)$r['iva_21'] * $cot;
          $iva105 = $sign * (float)$r['iva_105'] * $cot;
          $iva27  = $sign * (float)$r['iva_27'] * $cot;
          $exento = $sign * (float)$r['imp_op_ex'] * $cot;
          $nog    = $sign * (float)$r['imp_tot_conc'] * $cot;
          $otros  = $sign * (float)$r['imp_trib'] * $cot;
          $total  = $sign * (float)$r['imp_total'] * $cot;
        ?>
          <tr>
            <td><?= h($r['fecha_cbte']) ?></td>
            <td>
              <?= h($r['cbte_tipo']) ?>
              <span class="ms-1 badge <?= h($badgeCls) ?>"><?= h($badgeTxt) ?></span>
            </td>
            <td><?= h($r['cbte_letra']) ?></td>
            <td><?= h($r['punto_venta']) ?></td>
            <td class="text-mono"><?= h($r['cbte_numero']) ?></td>
            <td><?= h($r['cliente']) ?></td>
            <td class="text-mono"><?= h($r['cuit']) ?></td>
            <td class="text-mono"><?= h($r['condicion']) ?></td>
            <td><?= h($r['mon_id']) ?> @<?= h($r['mon_cotiz']) ?></td>

            <td class="text-end <?= ($neto<0?'neg':'') ?>">$ <?= money($neto) ?></td>
            <td class="text-end <?= ($iva<0?'neg':'') ?>">$ <?= money($iva) ?></td>
            <td class="text-end <?= ($iva21<0?'neg':'') ?>">$ <?= money($iva21) ?></td>
            <td class="text-end <?= ($iva105<0?'neg':'') ?>">$ <?= money($iva105) ?></td>
            <td class="text-end <?= ($iva27<0?'neg':'') ?>">$ <?= money($iva27) ?></td>
            <td class="text-end <?= ($exento<0?'neg':'') ?>">$ <?= money($exento) ?></td>
            <td class="text-end <?= ($nog<0?'neg':'') ?>">$ <?= money($nog) ?></td>
            <td class="text-end <?= ($otros<0?'neg':'') ?>">$ <?= money($otros) ?></td>
            <td class="text-end fw-semibold <?= ($total<0?'neg':'') ?>">$ <?= money($total) ?></td>
          </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>

    <div class="small text-muted">
      Incluye solo comprobantes aprobados (<span class="text-mono">facturas_afip_info.resultado='A'</span>).
      • Ajuste tamaño: editá <span class="text-mono">--fs-base</span> y <span class="text-mono">--fs-table</span>.
      • NC se muestra en negativo; ND permanece positivo.
    </div>
  </div>
</div>

</div><!-- /conta-wrap -->

<?php
/* ==========================================================
   =============== EXPORT ARCA (ZIP) VENTAS ==================
   ========================================================== */

function export_arca_zip_ventas(PDO $pdo, string $desde, string $hasta, string $pto, string $tipo): void
{
  if (!class_exists('ZipArchive')) {
    throw new RuntimeException("ZipArchive no disponible. Instalá php-zip.");
  }
  if (headers_sent($file, $line)) {
    throw new RuntimeException("Headers ya enviados en $file:$line. No se puede descargar ZIP.");
  }

  $wh = ["f.fecha_cbte BETWEEN :d AND :h", "f.resultado='A'"];
  $pa = [':d'=>$desde, ':h'=>$hasta];

  if ($pto !== '')  { $wh[] = "f.punto_venta = :pv"; $pa[':pv'] = (int)$pto; }
  if ($tipo !== '') { $wh[] = "f.cbte_tipo = :tc"; $pa[':tc'] = (int)$tipo; }

  // Cabeceras
  $sqlCbte = "
    SELECT
      f.id, f.fecha_cbte, f.cbte_tipo, f.punto_venta, f.cbte_numero,
      f.doc_tipo, f.doc_nro,
      f.imp_total, f.imp_tot_conc, f.imp_op_ex, f.imp_trib,
      f.mon_id, f.mon_cotiz, f.cae_vto
    FROM facturas_afip_info f
    WHERE ".implode(" AND ", $wh)."
    ORDER BY f.fecha_cbte, f.punto_venta, f.cbte_tipo, f.cbte_numero
  ";
  $st = $pdo->prepare($sqlCbte);
  $st->execute($pa);
  $cab = $st->fetchAll(PDO::FETCH_ASSOC);

  // Alícuotas agrupadas desde items
  $sqlAli = "
    SELECT
      f.id AS factura_id,
      f.cbte_tipo, f.punto_venta, f.cbte_numero,
      i.iva_porcentaje,
      SUM(i.importe_neto) AS base_imp,
      SUM(i.importe_iva)  AS imp_iva
    FROM facturas_afip_info f
    JOIN facturas_afip_items i ON i.factura_afip_id = f.id
    WHERE ".implode(" AND ", $wh)."
    GROUP BY f.id, f.cbte_tipo, f.punto_venta, f.cbte_numero, i.iva_porcentaje
  ";
  $st2 = $pdo->prepare($sqlAli);
  $st2->execute($pa);

  $alics = [];
  while ($r = $st2->fetch(PDO::FETCH_ASSOC)) {
    $alics[(int)$r['factura_id']][] = $r;
  }

  // sign por id (NC negativo)
  $signById = [];
  foreach ($cab as $r) {
    $tc = (int)($r['cbte_tipo'] ?? 0);
    $signById[(int)$r['id']] = in_array($tc, [3,8,13], true) ? -1 : 1;
  }

  // TXT CBTE
  $cbteLines = [];
  foreach ($cab as $r) {
    $id = (int)$r['id'];
    $sign = $signById[$id] ?? 1;
    $cant = isset($alics[$id]) ? count($alics[$id]) : 0;

    $cbteLines[] = implode(';', [
      ymd($r['fecha_cbte']),
      padl((string)$r['cbte_tipo'], 3, '0'),
      padl((string)$r['punto_venta'], 5, '0'),
      padl((string)$r['cbte_numero'], 20, '0'),
      padl((string)$r['doc_tipo'], 2, '0'),
      padl(preg_replace('/\D+/', '', (string)$r['doc_nro']), 20, '0'),

      // ✅ importes con signo (NC negativo)
      amt15($sign * (float)$r['imp_total']),
      amt15($sign * (float)$r['imp_tot_conc']),
      amt15($sign * (float)$r['imp_op_ex']),
      amt15($sign * (float)$r['imp_trib']),

      substr((string)$r['mon_id'], 0, 3),
      tc10($r['mon_cotiz']),
      (string)$cant,
      ($r['cae_vto'] ? ymd($r['cae_vto']) : '00000000')
    ]);
  }

  // TXT ALICUOTAS
  $aliLines = [];
  foreach ($alics as $factId => $arr) {
    $sign = $signById[(int)$factId] ?? 1;

    foreach ($arr as $a) {
      $aliCode = iva_code_from_percent((float)$a['iva_porcentaje']);
      if ($aliCode === '0000') continue;

      $aliLines[] = implode(';', [
        padl((string)$a['cbte_tipo'], 3, '0'),
        padl((string)$a['punto_venta'], 5, '0'),
        padl((string)$a['cbte_numero'], 20, '0'),
        amt15($sign * (float)$a['base_imp']),
        $aliCode,
        amt15($sign * (float)$a['imp_iva'])
      ]);
    }
  }

  // ZIP
  $tmpDir = sys_get_temp_dir().'/arca_'.uniqid();
  @mkdir($tmpDir, 0777, true);

  $f1 = $tmpDir.'/LIBRO_IVA_DIGITAL_VENTAS_CBTE.txt';
  $f2 = $tmpDir.'/LIBRO_IVA_DIGITAL_VENTAS_ALICUOTAS.txt';
  file_put_contents($f1, implode("\r\n", $cbteLines)."\r\n");
  file_put_contents($f2, implode("\r\n", $aliLines)."\r\n");

  $zipPath = $tmpDir.'/LIBRO_IVA_DIGITAL_VENTAS_'.date('Ymd_His').'.zip';
  $zip = new ZipArchive();
  if ($zip->open($zipPath, ZipArchive::CREATE|ZipArchive::OVERWRITE) !== true) {
    throw new RuntimeException("No se pudo crear el ZIP.");
  }
  $zip->addFile($f1, basename($f1));
  $zip->addFile($f2, basename($f2));
  $zip->close();

  header('Content-Type: application/zip');
  header('Content-Disposition: attachment; filename="'.basename($zipPath).'"');
  header('Content-Length: '.filesize($zipPath));
  readfile($zipPath);
  exit;
}

function iva_code_from_percent(float $p): string {
  if (abs($p - 10.5) < 0.01) return '0004';
  if (abs($p - 21.0) < 0.01) return '0005';
  if (abs($p - 27.0) < 0.01) return '0006';
  return '0000';
}

function ymd($d): string {
  if (!$d) return '00000000';
  $ts = strtotime((string)$d);
  return $ts ? date('Ymd', $ts) : '00000000';
}

function padl(string $s, int $len, string $ch='0'): string {
  $s = preg_replace('/\s+/', '', $s);
  if (strlen($s) > $len) $s = substr($s, -$len);
  return str_pad($s, $len, $ch, STR_PAD_LEFT);
}

/**
 * 15 chars, 2 decimales implícitos, soporta negativo.
 * -123.45 => "-000000000001234" (mantiene 15)
 */
function amt15($v): string {
  $n = (float)$v;
  $neg = $n < 0;
  $n = abs($n);
  $cents = (int)round($n * 100, 0);
  $s = str_pad((string)$cents, 15, '0', STR_PAD_LEFT);
  return $neg ? ('-'.substr($s, 1)) : $s;
}

/**
 * TC 10 (6 decimales implícitos)
 */
function tc10($v): string {
  $n = (float)$v;
  if ($n <= 0) $n = 1;
  $scaled = (int)round($n * 1000000, 0);
  return str_pad((string)$scaled, 10, '0', STR_PAD_LEFT);
}

function numcsv($n): string {
  return number_format((float)$n, 2, '.', '');
}

$content = ob_get_clean();
require __DIR__ . '/_layout.php';
