<?php
require __DIR__ . '/../init.php';
require_login();
$pdo = pdo();

// filtros por defecto
$from_date = $_GET['from_date'] ?? date('Y-m-d', strtotime('-7 days'));
$from_time = $_GET['from_time'] ?? '00:00';
$to_date   = $_GET['to_date']   ?? date('Y-m-d');
$to_time   = $_GET['to_time']   ?? '23:59';
$pump_mode = $_GET['pump_mode'] ?? 'all'; // 'all', 'single', 'range'
$pump_single = isset($_GET['pump_single']) ? (int)$_GET['pump_single'] : 0;
$pump_from = isset($_GET['pump_from']) ? (int)$_GET['pump_from'] : 0;
$pump_to = isset($_GET['pump_to']) ? (int)$_GET['pump_to'] : 0;
$product_id= isset($_GET['product_id']) ? (int)$_GET['product_id'] : 0;
$payment_method = isset($_GET['payment_method']) ? trim($_GET['payment_method']) : ''; // ✅ NUEVO
$export    = isset($_GET['export']) ? $_GET['export'] : '';

// construir datetimes
$from_dt = $from_date . ' ' . $from_time . ':00';
$to_dt   = $to_date . ' ' . $to_time . ':59';

// obtener listas para selects
$products = $pdo->query("SELECT id,name FROM products ORDER BY name")->fetchAll();
$pumps = $pdo->query("SELECT id,name FROM pumps ORDER BY id")->fetchAll();

// ✅ OBTENER MÉTODOS DE PAGO DISPONIBLES
$paymentTypes = [];
try {
    $stmt = $pdo->query("SELECT DISTINCT type FROM payment_types ORDER BY type ASC");
    $paymentTypes = $stmt->fetchAll(PDO::FETCH_COLUMN);
} catch (Exception $e) {
    // Fallback si no existe la tabla
    $paymentTypes = ['cash', 'card', 'external', 'transfer'];
}

// ✅ Determinar qué bombas procesar según el modo
$pumpsToProcess = [];
$pumpHoseIds = [];

if ($pump_mode === 'all') {
    $pumpsToProcess = $pumps;
} elseif ($pump_mode === 'single' && $pump_single > 0) {
    foreach ($pumps as $p) {
        if ($p['id'] == $pump_single) {
            $pumpsToProcess[] = $p;
            break;
        }
    }
} elseif ($pump_mode === 'range' && $pump_from > 0 && $pump_to > 0) {
    foreach ($pumps as $p) {
        $pid = (int)$p['id'];
        if ($pid >= $pump_from && $pid <= $pump_to) {
            $pumpsToProcess[] = $p;
        }
    }
}

// Obtener todos los hose_ids de las bombas seleccionadas
if (count($pumpsToProcess) > 0) {
    $pumpIds = array_column($pumpsToProcess, 'id');
    $placeholders_pumps = implode(',', array_fill(0, count($pumpIds), '?'));
    $stmt = $pdo->prepare("SELECT id FROM hoses WHERE pump_id IN ($placeholders_pumps)");
    $stmt->execute($pumpIds);
    $pumpHoseIds = array_column($stmt->fetchAll(), 'id');
}

// construir condiciones y parámetros
$conditions = ["s.created_at BETWEEN ? AND ?"];
$params = [$from_dt, $to_dt];

// ✅ Filtrar por hose_id cuando se seleccionan bombas
if ($pump_mode !== 'all' && count($pumpHoseIds) > 0) {
    $placeholders = implode(',', array_fill(0, count($pumpHoseIds), '?'));
    $conditions[] = "si.hose_id IN ($placeholders)";
    foreach ($pumpHoseIds as $hid) $params[] = $hid;
}

// Filtro por producto
if ($product_id) {
    $conditions[] = "si.product_id = ?";
    $params[] = $product_id;
}

// ✅ FILTRO POR MÉTODO DE PAGO
if ($payment_method !== '') {
    $conditions[] = "s.payment_method = ?";
    $params[] = $payment_method;
}

// Query principal
$sql = "SELECT 
    s.id as sale_id,
    s.sale_code,
    s.created_at,
    s.payment_method,
    u.username,
    si.product_id,
    p.name as product_name,
    si.qty,
    si.unit_price,
    si.total,
    si.hose_id,
    h.name as hose_name,
    pm.id as pump_id,
    pm.name as pump_name
    FROM sale_items si
    JOIN sales s ON s.id = si.sale_id
    JOIN products p ON p.id = si.product_id
    LEFT JOIN users u ON u.id = s.user_id
    LEFT JOIN hoses h ON h.id = si.hose_id
    LEFT JOIN pumps pm ON pm.id = h.pump_id
    WHERE " . implode(' AND ', $conditions) . "
    ORDER BY s.created_at DESC
    LIMIT 5000";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$rows = $stmt->fetchAll();

// Totales agregados
$total_sum = 0;
$total_volume = 0;
$count_items = count($rows);
foreach ($rows as $r) {
    $total_sum += (float)$r['total'];
    $total_volume += (float)$r['qty'];
}

// Export CSV
if ($export === 'csv') {
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="sales_report_' . date('Ymd_His') . '.csv"');
    $out = fopen('php://output', 'w');
    fputcsv($out, ['Sale ID','Sale Code','Fecha','Usuario','Producto','Qty','Precio Unit','Total','Metodo Pago','Hose ID','Hose Name','Pump ID','Pump Name']);
    foreach ($rows as $r) {
        fputcsv($out, [
            $r['sale_id'],
            $r['sale_code'],
            $r['created_at'],
            $r['username'],
            $r['product_name'],
            $r['qty'],
            number_format($r['unit_price'],4,'.',''),
            number_format($r['total'],2,'.',''),
            $r['payment_method'],
            $r['hose_id'] ?? '',
            $r['hose_name'] ?? '',
            $r['pump_id'] ?? '',
            $r['pump_name'] ?? ''
        ]);
    }
    fclose($out);
    exit;
}

$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>Reportes - Ventas</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css">
  <style>
    body {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      min-height: 100vh;
    }
    
    .main-container {
      background: white;
      border-radius: 20px;
      margin: 30px auto;
      padding: 30px;
      box-shadow: 0 20px 60px rgba(0,0,0,0.3);
    }
    
    .page-header {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      padding: 25px;
      border-radius: 15px;
      margin-bottom: 30px;
    }
    
    .page-header h3 {
      margin: 0;
      font-weight: 700;
    }
    
    .filter-summary {
      background: #f8f9fa;
      padding: 15px;
      border-radius: 10px;
      margin-bottom: 20px;
      border-left: 4px solid #667eea;
    }
    
    .filter-summary strong {
      color: #667eea;
    }
    
    .summary-bar {
      background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
      border-left: 5px solid #2196f3;
      padding: 20px;
      border-radius: 15px;
      box-shadow: 0 5px 15px rgba(0,0,0,0.1);
      margin-bottom: 25px;
    }
    
    .summary-item {
      display: flex;
      align-items: center;
      gap: 10px;
    }
    
    .summary-label {
      font-weight: 700;
      color: #1976d2;
      font-size: 15px;
    }
    
    .summary-value {
      font-size: 24px;
      font-weight: 800;
      color: #0d47a1;
    }
    
    .summary-value.volume {
      color: #1565c0;
    }
    
    .summary-value.money {
      color: #2e7d32;
    }
    
    .pump-mode-selector { 
      display: flex; 
      gap: 12px; 
      margin-top: 10px; 
      flex-wrap: wrap; 
    }
    
    .pump-mode-option { 
      padding: 12px 18px; 
      border: 2px solid #ddd; 
      border-radius: 10px; 
      cursor: pointer; 
      transition: all 0.3s ease;
      background: #fff;
      font-size: 14px;
      font-weight: 500;
    }
    
    .pump-mode-option:hover { 
      border-color: #667eea; 
      background: #f0f7ff; 
    }
    
    .pump-mode-option.active { 
      border-color: #667eea; 
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      font-weight: 700; 
    }
    
    .pump-mode-option input[type="radio"] { 
      margin-right: 8px; 
    }
    
    .pump-config { 
      margin-top: 15px; 
      padding: 18px; 
      background: #f8f9fa; 
      border-radius: 10px; 
    }
    
    .pump-config.hidden { 
      display: none; 
    }
    
    .inline-group { 
      display: flex; 
      gap: 15px; 
      align-items: center; 
    }
    
    .inline-group > div { 
      flex: 1; 
    }
    
    .table {
      box-shadow: 0 5px 15px rgba(0,0,0,0.08);
      border-radius: 10px;
      overflow: hidden;
    }
    
    .table thead th {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      border: none;
      padding: 15px 12px;
      font-weight: 600;
      text-transform: uppercase;
      font-size: 13px;
    }
    
    .table tbody tr {
      transition: all 0.3s ease;
    }
    
    .table tbody tr:hover {
      background: #f8f9fa;
      transform: scale(1.005);
    }
    
    .table tbody td {
      padding: 12px;
      vertical-align: middle;
    }
    
    .badge {
      padding: 6px 12px;
      border-radius: 8px;
      font-weight: 600;
      font-size: 12px;
    }
    
    .btn {
      border-radius: 10px;
      padding: 10px 20px;
      font-weight: 600;
      transition: all 0.3s ease;
    }
    
    .btn:hover {
      transform: translateY(-2px);
    }
    
    .btn-primary {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      border: none;
    }
    
    .navbar {
      background: white !important;
      box-shadow: 0 4px 20px rgba(0,0,0,0.1);
    }
    
    @media print {
      .no-print {
        display: none !important;
      }
      body {
        background: white;
        padding: 0;
      }
      .main-container {
        box-shadow: none;
        padding: 10mm;
      }
      .summary-bar {
        background: #f0f0f0 !important;
        -webkit-print-color-adjust: exact;
        print-color-adjust: exact;
      }
      table {
        page-break-inside: auto;
      }
      tr {
        page-break-inside: avoid;
      }
      thead {
        display: table-header-group;
      }
    }
  </style>
</head>
<body>

<nav class="navbar navbar-light no-print">
  <div class="container-fluid">
    <a class="navbar-brand fw-bold" href="<?= site('/index.php') ?>">
      <i class="bi bi-graph-up-arrow"></i> Reportes de Ventas
    </a>
    <a href="<?= site('/index.php') ?>" class="btn btn-outline-secondary btn-sm">
      <i class="bi bi-arrow-left"></i> Volver
    </a>
  </div>
</nav>

<div class="container-fluid">
  <div class="main-container">
    
    <div class="page-header">
      <h3><i class="bi bi-file-earmark-bar-graph-fill"></i> Reportes de Ventas</h3>
      <p class="mb-0 mt-2" style="opacity:0.9">Analiza las ventas por periodo, bomba, producto y método de pago</p>
    </div>

    <!-- ENCABEZADO PARA IMPRESIÓN -->
    <div class="d-none" id="print-header">
      <div style="text-align:center; margin-bottom:20px;">
        <h2><?= htmlspecialchars($station['nombre'] ?? 'Estación de Servicio') ?></h2>
        <p style="margin:2px 0;"><?= htmlspecialchars($station['direccion'] ?? '') ?></p>
        <p style="margin:2px 0;"><?= htmlspecialchars($station['telefono'] ?? '') ?></p>
        <?php if (!empty($station['rnc'])): ?>
          <p style="margin:2px 0;">RNC: <?= htmlspecialchars($station['rnc']) ?></p>
        <?php endif; ?>
        <hr>
        <h4>Reporte de Ventas</h4>
        <p>Desde: <?= htmlspecialchars($from_date . ' ' . $from_time) ?> - Hasta: <?= htmlspecialchars($to_date . ' ' . $to_time) ?></p>
        <p><small>Generado: <?= date('d/m/Y H:i:s') ?></small></p>
      </div>
    </div>

    <!-- FORMULARIO DE FILTROS -->
    <form method="get" class="row g-3 mb-4 p-4 border rounded bg-light no-print">
      
      <!-- RANGO DE FECHAS -->
      <div class="col-md-3">
        <label class="form-label fw-bold"><i class="bi bi-calendar3"></i> Desde (fecha)</label>
        <input type="date" name="from_date" class="form-control" value="<?= htmlspecialchars($from_date) ?>" required>
      </div>
      <div class="col-md-2">
        <label class="form-label fw-bold"><i class="bi bi-clock"></i> Desde (hora)</label>
        <input type="time" name="from_time" class="form-control" value="<?= htmlspecialchars($from_time) ?>" required>
      </div>
      <div class="col-md-3">
        <label class="form-label fw-bold"><i class="bi bi-calendar3"></i> Hasta (fecha)</label>
        <input type="date" name="to_date" class="form-control" value="<?= htmlspecialchars($to_date) ?>" required>
      </div>
      <div class="col-md-2">
        <label class="form-label fw-bold"><i class="bi bi-clock"></i> Hasta (hora)</label>
        <input type="time" name="to_time" class="form-control" value="<?= htmlspecialchars($to_time) ?>" required>
      </div>

      <!-- SELECTOR DE BOMBAS -->
      <div class="col-md-12">
        <label class="form-label fw-bold"><i class="bi bi-fuel-pump-fill"></i> Seleccionar Bombas</label>
        <div class="pump-mode-selector">
          <label class="pump-mode-option" for="mode-all">
            <input type="radio" name="pump_mode" id="mode-all" value="all" <?= $pump_mode==='all' ? 'checked' : '' ?>>
            Todas las bombas
          </label>
          <label class="pump-mode-option" for="mode-single">
            <input type="radio" name="pump_mode" id="mode-single" value="single" <?= $pump_mode==='single' ? 'checked' : '' ?>>
            Una bomba específica
          </label>
          <label class="pump-mode-option" for="mode-range">
            <input type="radio" name="pump_mode" id="mode-range" value="range" <?= $pump_mode==='range' ? 'checked' : '' ?>>
            Rango de bombas
          </label>
        </div>

        <div id="config-single" class="pump-config hidden">
          <label for="pump_single" class="form-label">Seleccionar bomba:</label>
          <select name="pump_single" id="pump_single" class="form-select">
            <option value="0">-- Selecciona una bomba --</option>
            <?php foreach($pumps as $p): ?>
              <option value="<?= $p['id'] ?>" <?= $pump_single==$p['id']?'selected':'' ?>>
                <?= htmlspecialchars($p['name']) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>

        <div id="config-range" class="pump-config hidden">
          <div class="inline-group">
            <div>
              <label for="pump_from" class="form-label">Desde bomba:</label>
              <select name="pump_from" id="pump_from" class="form-select">
                <option value="0">-- Desde --</option>
                <?php foreach($pumps as $p): ?>
                  <option value="<?= $p['id'] ?>" <?= $pump_from==$p['id']?'selected':'' ?>>
                    <?= htmlspecialchars($p['name']) ?>
                  </option>
                <?php endforeach; ?>
              </select>
            </div>
            <div>
              <label for="pump_to" class="form-label">Hasta bomba:</label>
              <select name="pump_to" id="pump_to" class="form-select">
                <option value="0">-- Hasta --</option>
                <?php foreach($pumps as $p): ?>
                  <option value="<?= $p['id'] ?>" <?= $pump_to==$p['id']?'selected':'' ?>>
                    <?= htmlspecialchars($p['name']) ?>
                  </option>
                <?php endforeach; ?>
              </select>
            </div>
          </div>
        </div>
      </div>
      
      <!-- FILTROS ADICIONALES -->
      <div class="col-md-6">
        <label class="form-label fw-bold"><i class="bi bi-droplet-fill"></i> Tipo de Combustible</label>
        <select name="product_id" class="form-select">
          <option value="0">-- Todos los productos --</option>
          <?php foreach($products as $p): ?>
            <option value="<?= $p['id'] ?>" <?= $product_id==$p['id']?'selected':'' ?>>
              <?= htmlspecialchars($p['name']) ?>
            </option>
          <?php endforeach; ?>
        </select>
      </div>

      <!-- ✅ NUEVO: FILTRO POR MÉTODO DE PAGO -->
      <div class="col-md-6">
        <label class="form-label fw-bold"><i class="bi bi-credit-card-fill"></i> Método de Pago</label>
        <select name="payment_method" class="form-select">
          <option value="">-- Todos los métodos --</option>
          <?php foreach($paymentTypes as $pt): ?>
            <option value="<?= htmlspecialchars($pt) ?>" <?= $payment_method===$pt?'selected':'' ?>>
              <?= htmlspecialchars(ucfirst($pt)) ?>
            </option>
          <?php endforeach; ?>
        </select>
      </div>

      <!-- BOTONES DE ACCIÓN -->
      <div class="col-12 d-flex gap-2 flex-wrap">
        <button class="btn btn-primary" type="submit">
          <i class="bi bi-funnel-fill"></i> Filtrar
        </button>
        <a class="btn btn-outline-secondary" href="<?= site('admin/reports.php') ?>">
          <i class="bi bi-arrow-clockwise"></i> Limpiar
        </a>
        <?php
          $qs = $_GET;
          $qs['export'] = 'csv';
          $exportUrl = site('admin/reports.php') . '?' . http_build_query($qs);
        ?>
        <a class="btn btn-success" href="<?= $exportUrl ?>">
          <i class="bi bi-file-earmark-excel"></i> Exportar CSV
        </a>
        <button type="button" class="btn btn-info" onclick="printReport()">
          <i class="bi bi-printer-fill"></i> Imprimir
        </button>
      </div>
    </form>

    <!-- FILTROS ACTIVOS -->
    <?php if ($pump_mode !== 'all' || $product_id || $payment_method !== ''): ?>
      <div class="filter-summary">
        <strong><i class="bi bi-funnel"></i> Filtros activos:</strong>
        
        <?php if ($pump_mode === 'single' && $pump_single): 
          $selected_pump = array_filter($pumps, fn($p) => $p['id'] == $pump_single);
          $selected_pump = reset($selected_pump);
        ?>
          <span class="badge bg-primary">
            Bomba: <?= htmlspecialchars($selected_pump['name'] ?? 'N/A') ?>
          </span>
        <?php elseif ($pump_mode === 'range' && $pump_from && $pump_to): 
          $pump_from_name = '';
          $pump_to_name = '';
          foreach($pumps as $p) {
            if ($p['id'] == $pump_from) $pump_from_name = $p['name'];
            if ($p['id'] == $pump_to) $pump_to_name = $p['name'];
          }
        ?>
          <span class="badge bg-primary">
            Rango: <?= htmlspecialchars($pump_from_name) ?> → <?= htmlspecialchars($pump_to_name) ?>
          </span>
        <?php endif; ?>
        
        <?php if ($product_id): 
          $selected_product = array_filter($products, fn($p) => $p['id'] == $product_id);
          $selected_product = reset($selected_product);
        ?>
          <span class="badge bg-info">
            Combustible: <?= htmlspecialchars($selected_product['name'] ?? 'N/A') ?>
          </span>
        <?php endif; ?>
        
        <?php if ($payment_method !== ''): ?>
          <span class="badge bg-success">
            Pago: <?= htmlspecialchars(ucfirst($payment_method)) ?>
          </span>
        <?php endif; ?>
      </div>
    <?php endif; ?>

    <!-- RESUMEN GENERAL -->
    <div class="summary-bar d-flex justify-content-between align-items-center flex-wrap gap-3">
      <div class="summary-item">
        <span class="summary-label"><i class="bi bi-list-ol"></i> Resultados:</span>
        <span class="summary-value"><?= number_format($count_items) ?></span>
        <span class="text-muted">filas</span>
      </div>
      
      <div class="summary-item">
        <span class="summary-label"><i class="bi bi-droplet"></i> Volumen Total:</span>
        <span class="summary-value volume"><?= number_format($total_volume, 3) ?></span>
        <span class="text-muted">Gal</span>
      </div>
      
      <div class="summary-item">
        <span class="summary-label"><i class="bi bi-cash-stack"></i> Total:</span>
        <span class="summary-value money">$<?= number_format($total_sum, 2) ?></span>
      </div>
    </div>

    <!-- TABLA DE RESULTADOS -->
    <div class="table-responsive">
      <table class="table table-hover">
        <thead>
          <tr>
            <th><i class="bi bi-calendar3"></i> Fecha</th>
            <th><i class="bi bi-receipt"></i> Venta</th>
            <th><i class="bi bi-person"></i> Usuario</th>
            <th><i class="bi bi-droplet"></i> Producto</th>
            <th class="text-end"><i class="bi bi-speedometer"></i> Qty</th>
            <th class="text-end"><i class="bi bi-currency-dollar"></i> Precio</th>
            <th class="text-end"><i class="bi bi-cash-stack"></i> Total</th>
            <th><i class="bi bi-credit-card"></i> Método</th>
            <th><i class="bi bi-fuel-pump"></i> Isla</th>
          </tr>
        </thead>
        <tbody>
          <?php if (count($rows) === 0): ?>
            <tr>
              <td colspan="9" class="text-center text-muted py-5">
                <i class="bi bi-inbox" style="font-size:48px;opacity:0.3"></i>
                <p class="mt-2">No se encontraron resultados para los filtros seleccionados.</p>
              </td>
            </tr>
          <?php else: ?>
            <?php foreach($rows as $r): ?>
            <tr>
              <td><?= date('d/m/Y H:i', strtotime($r['created_at'])) ?></td>
              <td><strong><?= htmlspecialchars($r['sale_code']) ?></strong></td>
              <td><?= htmlspecialchars($r['username'] ?: 'Sistema') ?></td>
              <td><?= htmlspecialchars($r['product_name']) ?></td>
              <td class="text-end"><?= number_format($r['qty'], 3) ?></td>
              <td class="text-end">$<?= number_format($r['unit_price'],2) ?></td>
              <td class="text-end fw-bold">$<?= number_format($r['total'],2) ?></td>
              <td>
                <?php 
                  $method = htmlspecialchars($r['payment_method']);
                  $badge_class = 'bg-secondary';
                  if ($method === 'cash' || $method === 'Efectivo') $badge_class = 'bg-success';
                  elseif ($method === 'card') $badge_class = 'bg-primary';
                  elseif ($method === 'external') $badge_class = 'bg-warning';
                  elseif ($method === 'transfer') $badge_class = 'bg-info';
                ?>
                <span class="badge <?= $badge_class ?>"><?= $method ?></span>
              </td>
              <td>
                <?php if ($r['pump_name']): ?>
                  <strong><?= htmlspecialchars($r['pump_name']) ?></strong>
                <?php elseif ($r['hose_name']): ?>
                  <small class="text-muted">Manguera: <?= htmlspecialchars($r['hose_name']) ?></small>
                <?php else: ?>
                  <span class="text-muted">—</span>
                <?php endif; ?>
              </td>
            </tr>
            <?php endforeach; ?>
          <?php endif; ?>
        </tbody>
      </table>
    </div>

    <?php if ($count_items >= 5000): ?>
      <div class="alert alert-warning mt-3 no-print">
        <i class="bi bi-exclamation-triangle-fill"></i>
        <strong>Límite alcanzado:</strong> Se muestran los primeros 5,000 registros. 
        Utiliza filtros más específicos para refinar los resultados.
      </div>
    <?php endif; ?>

  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
  function updatePumpMode() {
    const mode = document.querySelector('input[name="pump_mode"]:checked').value;
    document.querySelectorAll('.pump-config').forEach(el => el.classList.add('hidden'));
    document.querySelectorAll('.pump-mode-option').forEach(el => el.classList.remove('active'));
    
    if (mode === 'single') {
      document.getElementById('config-single').classList.remove('hidden');
    } else if (mode === 'range') {
      document.getElementById('config-range').classList.remove('hidden');
    }
    
    document.querySelector(`label[for="mode-${mode}"]`).classList.add('active');
  }
  
  function printReport() {
    const printHeader = document.getElementById('print-header');
    printHeader.classList.remove('d-none');
    window.print();
    setTimeout(() => {
      printHeader.classList.add('d-none');
    }, 500);
  }
  
  document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('input[name="pump_mode"]').forEach(el => {
      el.addEventListener('change', updatePumpMode);
    });
    updatePumpMode();
  });
</script>
</body>
</html>