<?php
// cierre_ventas.php
// Corregido: Rango de fechas inclusivo para capturar todas las ventas
// UN SOLO CIERRE consolidado para múltiples surtidores

session_start();

// --- Leer .env (si existe) ---
function load_dotenv($path) {
    if (!file_exists($path)) return;
    $lines = file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ($lines as $line) {
        $line = trim($line);
        if ($line === '' || $line[0] === '#') continue;
        if (strpos($line, '=') === false) continue;
        list($key, $val) = explode('=', $line, 2);
        $key = trim($key);
        $val = trim($val);
        if ((substr($val,0,1) === '"' && substr($val,-1) === '"') || (substr($val,0,1) === "'" && substr($val,-1) === "'")) {
            $val = substr($val,1,-1);
        }
        putenv("$key=$val");
        $_ENV[$key] = $val;
    }
}
load_dotenv(__DIR__ . '/.env');

// timezone
$tz = getenv('APP_TZ') ?: (getenv('TZ') ?: 'America/Santo_Domingo');
if (@date_default_timezone_set($tz) === false) {
    date_default_timezone_set('UTC');
}

// DB
$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()));
}

// CSRF
if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(16));
}
$csrf = $_SESSION['csrf_token'];

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

// Load pumps and recent closures
$stmt = $pdo->query("SELECT id, name FROM pumps ORDER BY id");
$pumps = $stmt->fetchAll();

$stmtRecent = $pdo->query("SELECT id, pump_name, start_dt, end_dt, total_amount, transactions, created_at FROM sales_closures ORDER BY created_at DESC LIMIT 50");
$recentClosures = $stmtRecent->fetchAll();

// Defaults
$today = date('Y-m-d');
$default_time_from = '00:00';
$default_time_to = date('H:i');

$errors = [];
$info = null;
$result = null;
$overlaps = [];
$closure_id = null;

// Form values
$form_date_from = $_POST['date_from'] ?? $today;
$form_time_from = $_POST['time_from'] ?? $default_time_from;
$form_date_to = $_POST['date_to'] ?? $today;
$form_time_to = $_POST['time_to'] ?? $default_time_to;
$form_pump_mode = $_POST['pump_mode'] ?? 'all';
$form_pump_single = $_POST['pump_single'] ?? '';
$form_pump_from = $_POST['pump_from'] ?? '';
$form_pump_to = $_POST['pump_to'] ?? '';
$form_created_by = $_POST['created_by'] ?? ($_SESSION['username'] ?? '');
$form_notes = $_POST['notes'] ?? '';
$force = true;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Sanitize inputs
    $form_pump_mode = $_POST['pump_mode'] ?? 'all';
    $form_pump_single = trim($_POST['pump_single'] ?? '');
    $form_pump_from = trim($_POST['pump_from'] ?? '');
    $form_pump_to = trim($_POST['pump_to'] ?? '');
    $form_date_from = $_POST['date_from'] ?? $today;
    $form_time_from = $_POST['time_from'] ?? $default_time_from;
    $form_date_to = $_POST['date_to'] ?? $today;
    $form_time_to = $_POST['time_to'] ?? $default_time_to;
    $form_created_by = trim($_POST['created_by'] ?? ($_SESSION['username'] ?? ''));
    $form_notes = trim($_POST['notes'] ?? '');
    $force = true;

    // CSRF check
    if (!isset($_POST['csrf']) || $_POST['csrf'] !== $csrf) {
        $errors[] = "Token inválido. Refresca la página e intenta de nuevo.";
    }

    // Validations
    if ($form_date_from === '' || $form_date_to === '' || $form_time_from === '' || $form_time_to === '') {
        $errors[] = "Fecha y hora inicial y final son obligatorias.";
    }
    
    if ($form_pump_mode === 'single' && $form_pump_single === '') {
        $errors[] = "Debes seleccionar un surtidor.";
    }
    
    if ($form_pump_mode === 'range') {
        if ($form_pump_from === '' || $form_pump_to === '') {
            $errors[] = "Debes seleccionar el rango de surtidores (desde y hasta).";
        } elseif ((int)$form_pump_from > (int)$form_pump_to) {
            $errors[] = "El surtidor 'desde' no puede ser mayor que 'hasta'.";
        }
    }
    
    if ($form_created_by === '') {
        $errors[] = "El campo 'Usuario que realiza el cierre' es obligatorio.";
    }

    if (empty($errors)) {
        // ✅ CORREGIDO: Parse DateTimes con segundos incluidos
        try {
            $start = new DateTime($form_date_from . ' ' . $form_time_from . ':00');
            $end   = new DateTime($form_date_to . ' ' . $form_time_to . ':59');
            
            // Si la hora final es menor que la inicial, cruzó medianoche
            if ($end < $start) {
                $end->modify('+1 day');
            }
            
            $start_dt = $start->format('Y-m-d H:i:s');
            $end_dt   = $end->format('Y-m-d H:i:s');
        } catch (Exception $e) {
            $errors[] = "Formato de fecha/hora inválido.";
        }
    }

    if (empty($errors)) {
        // Determine which pumps to process
        $pumpsToProcess = [];
        
        if ($form_pump_mode === 'all') {
            $pumpsToProcess = $pumps;
        } elseif ($form_pump_mode === 'single') {
            foreach ($pumps as $p) {
                if ($p['id'] == $form_pump_single) {
                    $pumpsToProcess[] = $p;
                    break;
                }
            }
        } elseif ($form_pump_mode === 'range') {
            $from_id = (int)$form_pump_from;
            $to_id = (int)$form_pump_to;
            foreach ($pumps as $p) {
                $pid = (int)$p['id'];
                if ($pid >= $from_id && $pid <= $to_id) {
                    $pumpsToProcess[] = $p;
                }
            }
        }

        if (empty($pumpsToProcess)) {
            $errors[] = "No se encontraron surtidores para procesar.";
        }
    }

    if (empty($errors)) {
        try {
            $pdo->beginTransaction();
            
            // ✅ CONSOLIDADO: Acumular datos de todos los surtidores
            $all_hose_ids = [];
            $per_pump_data = [];
            $pump_names = [];
            $all_pump_ids = [];
            
            foreach ($pumpsToProcess as $pump) {
                $pump_id = $pump['id'];
                $pump_name = $pump['name'];
                $pump_names[] = $pump_name;
                $all_pump_ids[] = $pump_id;
                
                // Get hoses for this pump
                $stmtH = $pdo->prepare("SELECT id FROM hoses WHERE pump_id = :pid");
                $stmtH->execute([':pid' => $pump_id]);
                $hoseIds = $stmtH->fetchAll(PDO::FETCH_COLUMN);

                if (empty($hoseIds)) {
                    $per_pump_data[] = [
                        'pump_id' => $pump_id,
                        'pump_name' => $pump_name,
                        'total_amount' => 0.00,
                        'total_volume' => 0.000,
                        'transactions' => 0,
                        'sale_ids' => [],
                        'products' => []
                    ];
                    continue;
                }
                
                $all_hose_ids = array_merge($all_hose_ids, $hoseIds);

                $placeholders = implode(',', array_fill(0, count($hoseIds), '?'));
                $params = array_merge($hoseIds, [$start_dt, $end_dt]);

                // ✅ CRÍTICO: Obtener sale_ids ÚNICOS primero con >= y <=
                $stmtSaleIds = $pdo->prepare("
                    SELECT DISTINCT s.id
                    FROM sales s
                    INNER JOIN sale_items si ON si.sale_id = s.id
                    WHERE si.hose_id IN ($placeholders)
                      AND s.created_at >= ?
                      AND s.created_at <= ?
                    ORDER BY s.id
                ");
                $stmtSaleIds->execute($params);
                $saleIds = array_map('intval', $stmtSaleIds->fetchAll(PDO::FETCH_COLUMN));
                
                $transaction_count = count($saleIds);

                // ✅ Calcular totales basados en los sale_ids encontrados
                if ($transaction_count > 0) {
                    $sale_placeholders = implode(',', array_fill(0, count($saleIds), '?'));
                    
                    $stmtT = $pdo->prepare("
                        SELECT 
                            IFNULL(SUM(si.total),0) AS total_amount,
                            IFNULL(SUM(si.qty),0) AS total_volume
                        FROM sale_items si
                        INNER JOIN sales s ON s.id = si.sale_id
                        WHERE si.hose_id IN ($placeholders)
                          AND s.id IN ($sale_placeholders)
                    ");
                    $stmtT->execute(array_merge($hoseIds, $saleIds));
                    $totals = $stmtT->fetch();
                    
                    // Get product breakdown
                    $stmtD = $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
                        INNER JOIN sales s ON s.id = si.sale_id
                        INNER JOIN products p ON p.id = si.product_id
                        WHERE si.hose_id IN ($placeholders)
                          AND s.id IN ($sale_placeholders)
                        GROUP BY p.id, p.name 
                        ORDER BY p.name
                    ");
                    $stmtD->execute(array_merge($hoseIds, $saleIds));
                    $detailsRows = $stmtD->fetchAll();
                } else {
                    $totals = ['total_amount' => 0, 'total_volume' => 0];
                    $detailsRows = [];
                }

                $products = array_map(function($r){ 
                    return [
                        'product_id' => (int)$r['product_id'],
                        'product_name' => $r['product_name'],
                        'qty' => round((float)$r['qty'], 3),
                        'total' => round((float)$r['total'], 2)
                    ]; 
                }, $detailsRows);

                $per_pump_data[] = [
                    'pump_id' => $pump_id,
                    'pump_name' => $pump_name,
                    'total_amount' => round((float)($totals['total_amount'] ?? 0), 2),
                    'total_volume' => round((float)($totals['total_volume'] ?? 0), 3),
                    'transactions' => $transaction_count,
                    'sale_ids' => $saleIds,
                    'products' => $products
                ];
            }

            if (empty($all_hose_ids)) {
                $pdo->rollBack();
                $errors[] = "No se encontraron mangueras para los surtidores seleccionados.";
            } else {
                // ✅ Calcular totales consolidados (sale_ids únicos globales)
                $placeholders_all = implode(',', array_fill(0, count($all_hose_ids), '?'));
                $params_all = array_merge($all_hose_ids, [$start_dt, $end_dt]);

                $stmtAllSaleIds = $pdo->prepare("
                    SELECT DISTINCT s.id
                    FROM sales s
                    INNER JOIN sale_items si ON si.sale_id = s.id
                    WHERE si.hose_id IN ($placeholders_all)
                      AND s.created_at >= ?
                      AND s.created_at <= ?
                    ORDER BY s.id
                ");
                $stmtAllSaleIds->execute($params_all);
                $all_sale_ids = array_map('intval', $stmtAllSaleIds->fetchAll(PDO::FETCH_COLUMN));
                
                $total_transactions = count($all_sale_ids);

                // Calcular totales consolidados
                if ($total_transactions > 0) {
                    $all_sale_placeholders = implode(',', array_fill(0, count($all_sale_ids), '?'));
                    
                    $stmtTotal = $pdo->prepare("
                        SELECT 
                            IFNULL(SUM(si.total),0) AS total_amount,
                            IFNULL(SUM(si.qty),0) AS total_volume
                        FROM sale_items si
                        INNER JOIN sales s ON s.id = si.sale_id
                        WHERE si.hose_id IN ($placeholders_all)
                          AND s.id IN ($all_sale_placeholders)
                    ");
                    $stmtTotal->execute(array_merge($all_hose_ids, $all_sale_ids));
                    $grand_totals = $stmtTotal->fetch();

                    // Get overall product breakdown
                    $stmtOverall = $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
                        INNER JOIN sales s ON s.id = si.sale_id
                        INNER JOIN products p ON p.id = si.product_id
                        WHERE si.hose_id IN ($placeholders_all)
                          AND s.id IN ($all_sale_placeholders)
                        GROUP BY p.id, p.name 
                        ORDER BY p.name
                    ");
                    $stmtOverall->execute(array_merge($all_hose_ids, $all_sale_ids));
                    $overall_products = array_map(function($r){ 
                        return [
                            'product_id' => (int)$r['product_id'],
                            'product_name' => $r['product_name'],
                            'qty' => round((float)$r['qty'], 3),
                            'total' => round((float)$r['total'], 2)
                        ]; 
                    }, $stmtOverall->fetchAll());
                } else {
                    $grand_totals = ['total_amount' => 0, 'total_volume' => 0];
                    $overall_products = [];
                }

                $total_amount = round((float)($grand_totals['total_amount'] ?? 0), 2);
                $total_volume = round((float)($grand_totals['total_volume'] ?? 0), 3);

                // ✅ Nombre consolidado
                $pump_label = count($pumpsToProcess) === count($pumps) 
                    ? 'TODOS' 
                    : implode(', ', $pump_names);

                $detailsPayload = [
                    'overall_products' => $overall_products,
                    'per_pump' => $per_pump_data
                ];

                $detailsJson = json_encode($detailsPayload, JSON_UNESCAPED_UNICODE);
                $saleIdsJson = json_encode(array_values($all_sale_ids));

                // ✅ UN SOLO INSERT
                $insertSql = "INSERT INTO sales_closures
                    (pump_id, pump_name, start_dt, end_dt, total_amount, total_volume, transactions, created_by, notes, details, sale_ids)
                    VALUES
                    (:pump_id, :pump_name, :start_dt, :end_dt, :total_amount, :total_volume, :transactions, :created_by, :notes, :details, :sale_ids)";
                
                $stmtIns = $pdo->prepare($insertSql);
                $stmtIns->execute([
                    ':pump_id' => null,
                    ':pump_name' => $pump_label,
                    ':start_dt' => $start_dt,
                    ':end_dt' => $end_dt,
                    ':total_amount' => $total_amount,
                    ':total_volume' => $total_volume,
                    ':transactions' => $total_transactions,
                    ':created_by' => $form_created_by ?: null,
                    ':notes' => $form_notes ?: null,
                    ':details' => $detailsJson ?: null,
                    ':sale_ids' => $saleIdsJson ?: null
                ]);

                $closure_id = $pdo->lastInsertId();
                $pdo->commit();

                $info = "Cierre consolidado creado exitosamente (ID: $closure_id) - $pump_label - $" . number_format($total_amount, 2) . " ($total_transactions transacciones)";

                // Reset form
                $form_date_from = $today;
                $form_time_from = $default_time_from;
                $form_date_to = $today;
                $form_time_to = $default_time_to;
                $form_pump_mode = 'all';
                $form_pump_single = '';
                $form_pump_from = '';
                $form_pump_to = '';
                $form_created_by = $_SESSION['username'] ?? '';
                $form_notes = '';

                // Refresh recent closures
                $stmtRecent = $pdo->query("SELECT id, pump_name, start_dt, end_dt, total_amount, transactions, created_at FROM sales_closures ORDER BY created_at DESC LIMIT 50");
                $recentClosures = $stmtRecent->fetchAll();
            }

        } catch (Exception $e) {
            if ($pdo->inTransaction()) $pdo->rollBack();
            $errors[] = "Error al calcular/guardar el cierre: " . $e->getMessage();
        }
    }
}
?>
<!doctype html>
<html lang="es">
<head>
  <meta charset="utf-8">
  <title>Cierre de Ventas</title>
  <style>
    body{font-family:Arial, sans-serif;margin:16px;background:#f5f5f5}
    .container{max-width:1200px;margin:0 auto;background:#fff;padding:24px;border-radius:8px;box-shadow:0 2px 8px rgba(0,0,0,0.1)}
    label{display:block;margin-top:12px;font-weight:600;color:#333}
    .row{margin-bottom:16px}
    input[type="date"], input[type="time"], input[type="text"], textarea, select{
      width:100%;padding:8px;border:1px solid #ddd;border-radius:4px;font-size:14px;box-sizing:border-box
    }
    table{border-collapse:collapse;width:100%;margin-top:16px}
    table td, table th{border:1px solid #ddd;padding:8px;text-align:left}
    table th{background:#f8f9fa;font-weight:600}
    .right{text-align:right}
    .btn-home { 
      display:inline-block; 
      background: linear-gradient(180deg,#2b8aef,#1166d6); 
      color:#fff; 
      padding:10px 16px; 
      border-radius:6px; 
      text-decoration:none; 
      font-weight:600; 
      box-shadow: 0 3px 0 rgba(0,0,0,0.12); 
      border: 1px solid rgba(0,0,0,0.08); 
      transition: transform 0.08s ease, box-shadow 0.08s ease; 
    }
    .btn-home:hover { transform: translateY(-1px); box-shadow:0 6px 18px rgba(0,0,0,0.12); }
    .title { font-size:24px; font-weight:700; color:#333; }
    .required { color: #dc3545; margin-left:4px; font-weight:700; }
    .btn-submit { 
      background: linear-gradient(180deg,#28a745,#218838); 
      color:#fff; 
      padding:12px 24px; 
      border-radius:6px; 
      border: none; 
      font-weight:700; 
      font-size:16px;
      cursor:pointer; 
      box-shadow: 0 3px 0 rgba(0,0,0,0.15);
      transition: all 0.08s ease;
    }
    .btn-submit:hover { transform: translateY(-1px); box-shadow:0 6px 18px rgba(0,0,0,0.15); }
    .force-wrap { display:flex; align-items:center; gap:8px; font-size:14px; color:#333; background:#f8f9fa; padding:12px; border-radius:4px; }
    .force-note { font-size:12px; color:#666; margin-top:4px; }
    .errors { color:#dc3545; margin-bottom:16px; background:#ffe6e6; padding:12px; border-radius:4px; border-left:4px solid #dc3545; }
    .info { color:#28a745; margin-bottom:16px; background:#e6ffe6; padding:12px; border-radius:4px; border-left:4px solid #28a745; font-weight:600; }
    .pump-mode-selector { display:flex; gap:16px; margin-top:8px; flex-wrap:wrap; }
    .pump-mode-option { 
      padding:12px 16px; 
      border:2px solid #ddd; 
      border-radius:6px; 
      cursor:pointer; 
      transition:all 0.2s ease;
      background:#fff;
    }
    .pump-mode-option:hover { border-color:#2b8aef; background:#f0f7ff; }
    .pump-mode-option.active { border-color:#2b8aef; background:#e3f2fd; font-weight:600; }
    .pump-mode-option input[type="radio"] { margin-right:8px; }
    .pump-config { margin-top:12px; padding:16px; background:#f8f9fa; border-radius:6px; }
    .pump-config.hidden { display:none; }
    .inline-group { display:flex; gap:12px; align-items:center; }
    .inline-group > div { flex:1; }
  </style>
  <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');
    }
    
    window.addEventListener('DOMContentLoaded', function() {
      document.querySelectorAll('input[name="pump_mode"]').forEach(el => {
        el.addEventListener('change', updatePumpMode);
      });
      updatePumpMode();
    });
  </script>
</head>
<body>
  <div class="container">
    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:24px">
      <div class="title">Cierre de ventas consolidado</div>
      <div><a class="btn-home" href="index.php" title="Ir al inicio">← Ir a inicio</a></div>
    </div>

    <?php if (!empty($errors)): ?>
      <div class="errors"><strong>⚠️ Errores:</strong><ul><?php foreach($errors as $e) echo '<li>'.h($e).'</li>'; ?></ul></div>
    <?php endif; ?>

    <?php if ($info): ?>
      <div class="info">
        ✅ <?=h($info)?>
        <br>
        <a href="closure_print.php?id=<?=h($closure_id)?>" target="_blank" style="color:#155724;text-decoration:underline">
          📄 Ver/Imprimir cierre consolidado
        </a>
      </div>
    <?php endif; ?>

    <form method="post" action="">
      <input type="hidden" name="csrf" value="<?=h($csrf)?>">
      
      <div class="row">
        <label>Seleccionar surtidores:</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" <?= $form_pump_mode==='all' ? 'checked' : '' ?>>
            Todos los surtidores
          </label>
          <label class="pump-mode-option" for="mode-single">
            <input type="radio" name="pump_mode" id="mode-single" value="single" <?= $form_pump_mode==='single' ? 'checked' : '' ?>>
            Un surtidor específico
          </label>
          <label class="pump-mode-option" for="mode-range">
            <input type="radio" name="pump_mode" id="mode-range" value="range" <?= $form_pump_mode==='range' ? 'checked' : '' ?>>
            Rango de surtidores
          </label>
        </div>

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

        <div id="config-range" class="pump-config hidden">
          <div class="inline-group">
            <div>
              <label for="pump_from">Desde surtidor:</label>
              <select name="pump_from" id="pump_from">
                <option value="">-- Desde --</option>
                <?php foreach ($pumps as $p): ?>
                  <option value="<?=h($p['id'])?>" <?= $form_pump_from == $p['id'] ? 'selected' : '' ?>>
                    <?=h($p['name'])?>
                  </option>
                <?php endforeach; ?>
              </select>
            </div>
            <div>
              <label for="pump_to">Hasta surtidor:</label>
              <select name="pump_to" id="pump_to">
                <option value="">-- Hasta --</option>
                <?php foreach ($pumps as $p): ?>
                  <option value="<?=h($p['id'])?>" <?= $form_pump_to == $p['id'] ? 'selected' : '' ?>>
                    <?=h($p['name'])?>
                  </option>
                <?php endforeach; ?>
              </select>
            </div>
          </div>
        </div>
      </div>

      <div class="row">
        <label>Fecha/Hora inicial:</label>
        <div class="inline-group">
          <div><input type="date" name="date_from" value="<?=h($form_date_from)?>" required></div>
          <div><input type="time" name="time_from" value="<?=h($form_time_from)?>" required></div>
        </div>
      </div>

      <div class="row">
        <label>Fecha/Hora final:</label>
        <div class="inline-group">
          <div><input type="date" name="date_to" value="<?=h($form_date_to)?>" required></div>
          <div><input type="time" name="time_to" value="<?=h($form_time_to)?>" required></div>
        </div>
        <div style="font-size:0.9em;color:#666;margin-top:4px">
          Si la hora final es menor que la inicial se interpretará que el turno cruzó a la madrugada siguiente.
        </div>
      </div>

      <div class="row">
        <label>Usuario que realiza el cierre: <span class="required">*</span></label>
        <input type="text" name="created_by" required value="<?=h($form_created_by)?>" placeholder="Nombre del usuario">
      </div>

      <div class="row">
        <label>Notas (opcional):</label>
        <textarea name="notes" rows="3" placeholder="Observaciones o comentarios sobre este cierre..."><?=h($form_notes)?></textarea>
      </div>

      <div class="row">
        <div class="force-wrap">
          <input type="checkbox" checked disabled aria-disabled="true">
          <div>
            <div><strong>Forzar creación aun con cierres solapados</strong></div>
            <div class="force-note">Esta opción está activada por defecto. El sistema insertará el cierre incluso si el periodo se solapa con cierres previos.</div>
          </div>
        </div>
        <input type="hidden" name="force" value="1">
      </div>

      <div class="row" style="margin-top:24px">
        <button type="submit" class="btn-submit">🔒 Generar cierre consolidado</button>
      </div>
    </form>

    <hr style="margin:32px 0;border:none;border-top:2px solid #eee">
    
    <h3 style="color:#333;margin-bottom:16px">📋 Últimos 50 cierres</h3>
    <table>
      <tr>
        <th>ID</th>
        <th>Surtidor(es)</th>
        <th>Periodo</th>
        <th class="right">Total</th>
        <th>Tx</th>
        <th>Fecha</th>
        <th>Acciones</th>
      </tr>
      <?php foreach ($recentClosures as $c): ?>
        <tr>
          <td><?=h($c['id'])?></td>
          <td><strong><?=h($c['pump_name'] ?: 'TODOS')?></strong></td>
          <td style="font-size:12px"><?=h($c['start_dt'])?> → <?=h($c['end_dt'])?></td>
          <td class="right"><strong>$<?=number_format((float)$c['total_amount'],2)?></strong></td>
          <td><?=h($c['transactions'])?></td>
          <td style="font-size:12px"><?=h($c['created_at'])?></td>
          <td>
            <a href="closure_print.php?id=<?=h($c['id'])?>" target="_blank" style="color:#2b8aef;text-decoration:none">📄 Ver/Imprimir</a>
          </td>
        </tr>
      <?php endforeach; ?>
    </table>
  </div>
</body>
</html>