<?php
// closure_print.php - Versión mejorada con diseño profesional
// ✅ USAR CONFIG.PHP para la conexión
$config = require __DIR__ . '/config.php';

try {
    $pdo = new PDO(
        "mysql:host={$config->db_host};dbname={$config->db_name};charset=utf8mb4",
        $config->db_user,
        $config->db_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 >= :start_dt AND s.created_at <= :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 >= :start_dt AND s.created_at <= :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];
}

// ✅ CORREGIDO: Usar tabla 'stations' (plural con 's')
$station = $pdo->query("SELECT * FROM stations LIMIT 1")->fetch();

?>
<!doctype html>
<html lang="es">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Cierre de Ventas #<?=h($row['id'])?></title>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    
    body {
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
      line-height: 1.6;
      color: #2c3e50;
      background: #f8f9fa;
      padding: 20px;
    }
    
    .container {
      max-width: 1000px;
      margin: 0 auto;
      background: white;
      padding: 40px;
      box-shadow: 0 4px 20px rgba(0,0,0,0.1);
      border-radius: 12px;
    }
    
    /* Header Section */
    .header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      padding-bottom: 20px;
      border-bottom: 3px solid #3498db;
      margin-bottom: 30px;
    }
    
    .header-left {
      flex: 1;
    }
    
    .header-left h1 {
      font-size: 28px;
      color: #2c3e50;
      margin-bottom: 8px;
      font-weight: 700;
    }
    
    .header-info {
      font-size: 13px;
      color: #7f8c8d;
      line-height: 1.8;
    }
    
    .header-right {
      text-align: right;
    }
    
    .header-right img {
      max-height: 80px;
      max-width: 150px;
      border-radius: 8px;
      object-fit: contain;
    }
    
    /* Title Section */
    .report-title {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      padding: 20px 25px;
      border-radius: 10px;
      margin-bottom: 25px;
      box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
    }
    
    .report-title h2 {
      font-size: 22px;
      font-weight: 600;
      margin-bottom: 8px;
    }
    
    .report-id {
      font-size: 14px;
      opacity: 0.95;
      font-weight: 500;
    }
    
    /* Info Box */
    .info-box {
      background: #f8f9fa;
      border-left: 4px solid #3498db;
      padding: 15px 20px;
      margin-bottom: 25px;
      border-radius: 6px;
    }
    
    .info-row {
      display: flex;
      gap: 30px;
      flex-wrap: wrap;
      margin-bottom: 8px;
    }
    
    .info-item {
      font-size: 14px;
    }
    
    .info-label {
      font-weight: 600;
      color: #34495e;
      margin-right: 6px;
    }
    
    .info-value {
      color: #555;
    }
    
    /* Summary Cards */
    .summary-cards {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
      gap: 20px;
      margin-bottom: 30px;
    }
    
    .summary-card {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      padding: 20px;
      border-radius: 10px;
      text-align: center;
      box-shadow: 0 4px 15px rgba(0,0,0,0.1);
    }
    
    .summary-card.green {
      background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
    }
    
    .summary-card.orange {
      background: linear-gradient(135deg, #ee0979 0%, #ff6a00 100%);
    }
    
    .summary-card.blue {
      background: linear-gradient(135deg, #2193b0 0%, #6dd5ed 100%);
    }
    
    .summary-label {
      font-size: 12px;
      text-transform: uppercase;
      letter-spacing: 1px;
      opacity: 0.9;
      margin-bottom: 8px;
    }
    
    .summary-value {
      font-size: 28px;
      font-weight: 700;
      margin-bottom: 5px;
    }
    
    .summary-unit {
      font-size: 13px;
      opacity: 0.85;
    }
    
    /* Tables */
    .section-title {
      font-size: 18px;
      font-weight: 600;
      color: #2c3e50;
      margin: 30px 0 15px 0;
      padding-bottom: 8px;
      border-bottom: 2px solid #e0e0e0;
    }
    
    table {
      width: 100%;
      border-collapse: collapse;
      margin-bottom: 25px;
      background: white;
      box-shadow: 0 2px 8px rgba(0,0,0,0.05);
      border-radius: 8px;
      overflow: hidden;
    }
    
    thead {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
    }
    
    th {
      padding: 14px 12px;
      text-align: left;
      font-weight: 600;
      font-size: 13px;
      text-transform: uppercase;
      letter-spacing: 0.5px;
    }
    
    td {
      padding: 12px;
      border-bottom: 1px solid #f0f0f0;
      font-size: 14px;
    }
    
    tbody tr:hover {
      background: #f8f9fa;
    }
    
    tbody tr:last-child td {
      border-bottom: none;
    }
    
    .right {
      text-align: right;
    }
    
    tfoot {
      background: #f8f9fa;
      font-weight: 700;
      border-top: 3px solid #3498db;
    }
    
    tfoot td {
      padding: 14px 12px;
      font-size: 15px;
      color: #2c3e50;
    }
    
    /* Pump Detail Section */
    .pump-detail {
      background: #f8f9fa;
      padding: 20px;
      border-radius: 10px;
      margin-bottom: 20px;
      border-left: 5px solid #3498db;
    }
    
    .pump-detail-header {
      font-size: 16px;
      font-weight: 600;
      color: #2c3e50;
      margin-bottom: 15px;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .pump-detail-amount {
      color: #27ae60;
      font-size: 18px;
    }
    
    .no-sales {
      text-align: center;
      padding: 20px;
      color: #95a5a6;
      font-style: italic;
      background: #ecf0f1;
      border-radius: 6px;
    }
    
    /* Footer Section */
    .signatures {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 40px;
      margin-top: 50px;
      padding-top: 30px;
      border-top: 2px solid #e0e0e0;
    }
    
    .signature-box {
      text-align: center;
    }
    
    .signature-line {
      border-top: 2px solid #333;
      margin-bottom: 8px;
      padding-top: 5px;
    }
    
    .signature-label {
      font-size: 13px;
      color: #7f8c8d;
      font-weight: 600;
    }
    
    /* Sale IDs */
    .sale-ids {
      background: #ecf0f1;
      padding: 12px;
      border-radius: 6px;
      font-size: 11px;
      color: #555;
      margin-top: 20px;
      word-wrap: break-word;
    }
    
    /* Action Buttons */
    .actions {
      text-align: center;
      margin-bottom: 25px;
    }
    
    .btn {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      border: none;
      padding: 12px 30px;
      font-size: 14px;
      font-weight: 600;
      border-radius: 8px;
      cursor: pointer;
      margin: 0 8px;
      transition: all 0.3s ease;
      box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
    }
    
    .btn:hover {
      transform: translateY(-2px);
      box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
    }
    
    .btn-secondary {
      background: linear-gradient(135deg, #bdc3c7 0%, #95a5a6 100%);
    }
    
    /* Print Styles */
    @media print {
      body {
        background: white;
        padding: 0;
      }
      
      .container {
        box-shadow: none;
        padding: 20px;
      }
      
      .no-print {
        display: none !important;
      }
      
      .summary-cards {
        page-break-inside: avoid;
      }
      
      .pump-detail {
        page-break-inside: avoid;
      }
      
      table {
        page-break-inside: auto;
      }
      
      tr {
        page-break-inside: avoid;
        page-break-after: auto;
      }
      
      thead {
        display: table-header-group;
      }
    }
    
    @media (max-width: 768px) {
      .container {
        padding: 20px;
      }
      
      .header {
        flex-direction: column;
        gap: 20px;
      }
      
      .summary-cards {
        grid-template-columns: 1fr;
      }
      
      .signatures {
        grid-template-columns: 1fr;
        gap: 30px;
      }
    }
  </style>
</head>
<body>

<div class="container">
  <!-- Action Buttons -->
  <div class="actions no-print">
    <button class="btn" onclick="window.print()">🖨️ Imprimir</button>
    <button class="btn btn-secondary" onclick="window.close()">✕ Cerrar</button>
  </div>

  <!-- Header -->
  <div class="header">
    <div class="header-left">
      <h1><?= h($station['nombre'] ?? 'Estación de Servicio') ?></h1>
      <div class="header-info">
        <?php if (!empty($station['direccion'])): ?>
          📍 <?= h($station['direccion']) ?><br>
        <?php endif; ?>
        <?php if (!empty($station['telefono'])): ?>
          ☎️ <?= h($station['telefono']) ?>
        <?php endif; ?>
        <?php if (!empty($station['rnc'])): ?>
          <br>🏢 RNC: <?= h($station['rnc']) ?>
        <?php endif; ?>
      </div>
    </div>
    <div class="header-right">
      <?php if (!empty($station['logo'])): ?>
        <img src="<?=h($station['logo'])?>" alt="Logo">
      <?php endif; ?>
    </div>
  </div>

  <!-- Report Title -->
  <div class="report-title">
    <h2>📊 Informe de Cierre de Ventas</h2>
    <div class="report-id">Cierre ID: #<?=h($row['id'])?> | <?=h($row['pump_name'] ?: 'TODOS LOS SURTIDORES')?></div>
  </div>

  <!-- Info Box -->
  <div class="info-box">
    <div class="info-row">
      <div class="info-item">
        <span class="info-label">📅 Periodo:</span>
        <span class="info-value"><?=date('d/m/Y H:i', strtotime($row['start_dt']))?> → <?=date('d/m/Y H:i', strtotime($row['end_dt']))?></span>
      </div>
      <div class="info-item">
        <span class="info-label">👤 Generado por:</span>
        <span class="info-value"><?=h($row['created_by'] ?: 'Sistema')?></span>
      </div>
    </div>
    <div class="info-row">
      <div class="info-item">
        <span class="info-label">🕐 Fecha de creación:</span>
        <span class="info-value"><?=date('d/m/Y H:i:s', strtotime($row['created_at']))?></span>
      </div>
    </div>
    <?php if (!empty($row['notes'])): ?>
      <div class="info-row" style="margin-top:8px;">
        <div class="info-item">
          <span class="info-label">📝 Notas:</span>
          <span class="info-value"><?=h($row['notes'])?></span>
        </div>
      </div>
    <?php endif; ?>
  </div>

  <!-- Summary Cards -->
  <?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);
  }
  ?>
  
  <div class="summary-cards">
    <div class="summary-card green">
      <div class="summary-label">💰 Total Ventas</div>
      <div class="summary-value">$<?=number_format($grand_amount, 2)?></div>
      <div class="summary-unit">Pesos</div>
    </div>
    
    <div class="summary-card blue">
      <div class="summary-label">⛽ Volumen Total</div>
      <div class="summary-value"><?=number_format($grand_vol, 3)?></div>
      <div class="summary-unit">Galones</div>
    </div>
    
    <div class="summary-card orange">
      <div class="summary-label">🧾 Transacciones</div>
      <div class="summary-value"><?=number_format($grand_tx)?></div>
      <div class="summary-unit">Ventas realizadas</div>
    </div>
  </div>

  <!-- Summary Table -->
  <h3 class="section-title">📋 Resumen por Bomba</h3>
  <table>
    <thead>
      <tr>
        <th>ID</th>
        <th>Bomba</th>
        <th class="right">Monto ($)</th>
        <th class="right">Volumen (Gal)</th>
        <th class="right">Transacciones</th>
      </tr>
    </thead>
    <tbody>
      <?php foreach ($details['per_pump'] as $pp): ?>
      <tr>
        <td><strong><?=h($pp['pump_id'])?></strong></td>
        <td><?=h($pp['pump_name'])?></td>
        <td class="right"><strong>$<?=number_format($pp['total_amount'], 2)?></strong></td>
        <td class="right"><?=number_format($pp['total_volume'], 3)?></td>
        <td class="right"><?=h($pp['transactions'] ?? 0)?></td>
      </tr>
      <?php endforeach; ?>
    </tbody>
    <tfoot>
      <tr>
        <td colspan="2"><strong>TOTAL GENERAL</strong></td>
        <td class="right"><strong>$<?=number_format($grand_amount, 2)?></strong></td>
        <td class="right"><strong><?=number_format($grand_vol, 3)?></strong></td>
        <td class="right"><strong><?=number_format($grand_tx)?></strong></td>
      </tr>
    </tfoot>
  </table>

  <!-- Pump Details -->
  <h3 class="section-title">🔍 Detalle por Bomba</h3>
  
  <?php foreach ($details['per_pump'] as $pp): ?>
    <div class="pump-detail">
      <div class="pump-detail-header">
        <span>🏭 Bomba <?=h($pp['pump_id'])?> — <?=h($pp['pump_name'])?></span>
        <span class="pump-detail-amount">$<?=number_format($pp['total_amount'], 2)?></span>
      </div>
      
      <?php if (!empty($pp['products'])): ?>
        <table>
          <thead>
            <tr>
              <th>Producto</th>
              <th class="right">Volumen (Gal)</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"><strong>$<?=number_format($pd['total'], 2)?></strong></td>
            </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      <?php else: ?>
        <div class="no-sales">
          No hay ventas registradas para esta bomba en el periodo seleccionado.
        </div>
      <?php endif; ?>
    </div>
  <?php endforeach; ?>

  <!-- Sale IDs -->
  <?php if (!empty($row['sale_ids'])): ?>
    <div class="sale-ids">
      <strong>🔢 IDs de ventas incluidas:</strong> <?= h($row['sale_ids']) ?>
    </div>
  <?php endif; ?>

  <!-- Signatures -->
  <div class="signatures">
    <div class="signature-box">
      <div style="height:60px;"></div>
      <div class="signature-line">Firma del Operador</div>
      <div class="signature-label"><?=h($row['created_by'] ?: 'Operador')?></div>
    </div>
    
    <div class="signature-box">
      <div style="height:60px;"></div>
      <div class="signature-line">Firma del Supervisor</div>
      <div class="signature-label">Supervisor de Turno</div>
    </div>
  </div>

  <!-- Footer Actions -->
  <div class="actions no-print" style="margin-top:30px;">
    <button class="btn" onclick="window.print()">🖨️ Imprimir</button>
    <button class="btn btn-secondary" onclick="window.close()">✕ Cerrar</button>
  </div>
</div>

<script>
  // Auto-print on load (optional, comment out if not needed)
  // window.addEventListener('load', function() {
  //   setTimeout(() => window.print(), 500);
  // });
</script>

</body>
</html>