<?php
// closure_print.php (impresión con amounts 2 dec, volumes 3 dec)
$config = require __DIR__ . '/db.php';
try {
    $dsn = "mysql:host={$config['host']};port={$config['port']};dbname={$config['dbname']};charset={$config['charset']}";
    $pdo = new PDO($dsn, $config['user'], $config['pass'], [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]);
} catch (Exception $e) {
    die("Error de conexión: " . htmlspecialchars($e->getMessage()));
}

function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if (!$id) { http_response_code(400); exit('ID de cierre inválido.'); }

$stmt = $pdo->prepare("SELECT * FROM sales_closures WHERE id = :id");
$stmt->execute([':id'=>$id]);
$row = $stmt->fetch();
if (!$row) { http_response_code(404); exit('Cierre no encontrado.'); }

$details = null;
if (!empty($row['details'])) {
    $decoded = json_decode($row['details'], true);
    if ($decoded !== null) $details = $decoded;
}

if (!$details) {
    $start_dt = $row['start_dt'];
    $end_dt = $row['end_dt'];
    $stmtPP = $pdo->prepare("
        SELECT p.id AS pump_id, p.name AS pump_name,
          IFNULL(SUM(si.total),0) AS total_amount,
          IFNULL(SUM(si.qty),0) AS total_volume,
          COUNT(DISTINCT si.sale_id) AS transactions
        FROM pumps p
        LEFT JOIN hoses h ON h.pump_id = p.id
        LEFT JOIN sale_items si ON si.hose_id = h.id
        LEFT JOIN sales s ON s.id = si.sale_id AND s.created_at BETWEEN :start_dt AND :end_dt
        GROUP BY p.id, p.name ORDER BY p.id
    ");
    $stmtPP->execute([':start_dt'=>$start_dt, ':end_dt'=>$end_dt]);
    $perPumpRows = $stmtPP->fetchAll();

    $per_pump = [];
    foreach ($perPumpRows as $pr) {
        $pid = (int)$pr['pump_id'];
        $stmtPD = $pdo->prepare("
            SELECT p.id AS product_id, p.name AS product_name,
                   IFNULL(SUM(si.qty),0) AS qty, IFNULL(SUM(si.total),0) AS total
            FROM sale_items si
            JOIN sales s ON s.id = si.sale_id
            JOIN products p ON p.id = si.product_id
            JOIN hoses h ON h.id = si.hose_id
            WHERE h.pump_id = :pid AND s.created_at BETWEEN :start_dt AND :end_dt
            GROUP BY p.id, p.name ORDER BY p.name
        ");
        $stmtPD->execute([':pid'=>$pid, ':start_dt'=>$start_dt, ':end_dt'=>$end_dt]);
        $pumpProducts = $stmtPD->fetchAll();

        foreach ($pumpProducts as &$pd) {
            $pd['qty'] = round((float)$pd['qty'], 3);
            $pd['total'] = round((float)$pd['total'], 2);
        }

        $per_pump[] = [
            'pump_id' => $pid,
            'pump_name' => $pr['pump_name'],
            'total_amount' => round((float)$pr['total_amount'], 2),
            'total_volume' => round((float)$pr['total_volume'], 3),
            'transactions' => (int)$pr['transactions'],
            'products' => $pumpProducts
        ];
    }

    $details = ['overall_products' => [], 'per_pump' => $per_pump];
}

// station info
$station = $pdo->query("SELECT * FROM estacion LIMIT 1")->fetch();

?>
<!doctype html>
<html lang="es">
<head>
  <meta charset="utf-8">
  <title>Imprimir Cierre #<?=h($row['id'])?></title>
  <style>
    body{font-family:Arial, sans-serif;margin:20px;color:#111}
    header{display:flex;align-items:center;justify-content:space-between;margin-bottom:10px}
    header .left{max-width:70%}
    header img{max-height:60px}
    h1{font-size:18px;margin:2px 0}
    table{width:100%;border-collapse:collapse;margin-top:8px}
    table th, table td{border:1px solid #333;padding:6px;text-align:left}
    .right{text-align:right}
    .small{font-size:12px;color:#333}
    .actions{margin-top:10px;margin-bottom:10px}
    @media print { .no-print{display:none} body{margin:10mm} }
  </style>
  <script> function doPrint(){ window.print(); } </script>
</head>
<body>
  <div class="no-print actions">
    <button onclick="doPrint()">Imprimir</button>
    <button onclick="window.close()">Cerrar</button>
  </div>

  <header>
    <div class="left">
      <h1><?= h($station['nombre'] ?? 'Mi Estación') ?></h1>
      <div class="small">
        <?= h($station['direccion'] ?? '') ?><br>
        <?= h($station['telefono'] ?? '') ?> <?= $station['rnc'] ? ' - ' . h($station['rnc']) : '' ?>
      </div>
    </div>
    <div class="right">
      <?php if (!empty($station['logo_filename'])): ?>
        <img src="<?=h($station['logo_filename'])?>" alt="logo">
      <?php endif; ?>
    </div>
  </header>

  <h2>Informe de cierre — ID <?=h($row['id'])?></h2>
  <div class="small">
    Periodo: <strong><?=h($row['start_dt'])?> → <?=h($row['end_dt'])?></strong><br>
    Generado por: <?=h($row['created_by'] ?? '')?> — Fecha creación: <?=h($row['created_at'])?><br>
    Notas: <?=h($row['notes'] ?? '')?>
  </div>

  <h3>Resumen por bomba</h3>
  <table>
    <thead>
      <tr><th>Bomba ID</th><th>Nombre</th><th class="right">Monto</th><th class="right">Volumen</th><th class="right">Transacciones</th></tr>
    </thead>
    <tbody>
      <?php
      $grand_amount = 0.0;
      $grand_vol = 0.0;
      $grand_tx = 0;
      foreach ($details['per_pump'] as $pp):
          $grand_amount += (float)$pp['total_amount'];
          $grand_vol += (float)($pp['total_volume'] ?? 0);
          $grand_tx += (int)($pp['transactions'] ?? 0);
      ?>
      <tr>
        <td><?=h($pp['pump_id'])?></td>
        <td><?=h($pp['pump_name'])?></td>
        <td class="right"><?=number_format($pp['total_amount'],2)?></td>
        <td class="right"><?=number_format($pp['total_volume'],3)?></td>
        <td class="right"><?=h($pp['transactions'] ?? 0)?></td>
      </tr>
      <?php endforeach; ?>
      <tr>
        <th colspan="2">TOTAL</th>
        <th class="right"><?=number_format($grand_amount,2)?></th>
        <th class="right"><?=number_format($grand_vol,3)?></th>
        <th class="right"><?=h($grand_tx)?></th>
      </tr>
    </tbody>
  </table>

  <?php foreach ($details['per_pump'] as $pp): ?>
    <h4 style="margin-top:14px">Bomba <?=h($pp['pump_id'])?> — <?=h($pp['pump_name'])?> (Monto <?=number_format($pp['total_amount'],2)?>)</h4>
    <?php if (!empty($pp['products'])): ?>
      <table>
        <thead><tr><th>Producto</th><th class="right">Volumen</th><th class="right">Total</th></tr></thead>
        <tbody>
          <?php foreach ($pp['products'] as $pd): ?>
            <tr>
              <td><?=h($pd['product_name'])?></td>
              <td class="right"><?=number_format($pd['qty'],3)?></td>
              <td class="right"><?=number_format($pd['total'],2)?></td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    <?php else: ?>
      <div class="small">No hay ventas registradas para esta bomba en el periodo.</div>
    <?php endif; ?>
  <?php endforeach; ?>

  <div style="margin-top:18px;font-size:12px;color:#444">
    Sales IDs incluidas: <?= h($row['sale_ids'] ?? 'N/A') ?>
  </div>

  <div style="margin-top:24px" class="small">
    Firma operador: _________________________
    <br><br>
    Firma supervisor: _______________________
  </div>

  <div class="no-print" style="margin-top:20px">
    <button onclick="doPrint()">Imprimir</button>
    <button onclick="window.close()">Cerrar</button>
  </div>

</body>
</html>