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

require '../conexion.php';
date_default_timezone_set('America/Argentina/Buenos_Aires');

$desde = $_GET['desde'] ?? date('Y-m-01');
$hasta = $_GET['hasta'] ?? date('Y-m-d');

function obtenerCaja($con, $tabla) {
  global $desde, $hasta;
  $sql = "SELECT * FROM {$tabla} WHERE fecha BETWEEN '$desde' AND '$hasta' ORDER BY fecha DESC, hora DESC";
  $res = mysqli_query($con, $sql);
  $datos = [];
  $total_efectivo = 0;
  $total_transferencia = 0;

  while ($row = mysqli_fetch_assoc($res)) {
    $datos[] = $row;
    $total_efectivo += floatval($row['efectivo']);
    $total_transferencia += floatval($row['transferencia']);
  }
  return [$datos, $total_efectivo, $total_transferencia];
}

list($caja_sala, $total_efectivo_sala, $total_transferencia_sala) = obtenerCaja($con, 'caja_sala');
list($caja_mesa, $total_efectivo_mesa, $total_transferencia_mesa) = obtenerCaja($con, 'caja_mesa');
?>

<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8">
  <title>Administrar Caja</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body class="p-4">
  <div class="container">
    <h2 class="mb-4">💵 Administración de Caja</h2>

    <form method="get" class="row g-3 mb-4">
      <div class="col-auto">
        <label>Desde</label>
        <input type="date" name="desde" class="form-control" value="<?= htmlspecialchars($desde) ?>">
      </div>
      <div class="col-auto">
        <label>Hasta</label>
        <input type="date" name="hasta" class="form-control" value="<?= htmlspecialchars($hasta) ?>">
      </div>
      <div class="col-auto mt-4">
        <button type="submit" class="btn btn-primary">Filtrar</button>
      </div>
    </form>

    <ul class="nav nav-tabs mb-3" id="cajaTabs" role="tablist">
      <li class="nav-item" role="presentation">
        <button class="nav-link active" id="sala-tab" data-bs-toggle="tab" data-bs-target="#sala" type="button" role="tab">Caja Salas</button>
      </li>
      <li class="nav-item" role="presentation">
        <button class="nav-link" id="mesa-tab" data-bs-toggle="tab" data-bs-target="#mesa" type="button" role="tab">Caja Mesas</button>
      </li>
    </ul>

    <div class="tab-content" id="cajaTabsContent">
      <div class="tab-pane fade show active" id="sala" role="tabpanel">
        <h5>Totales Salas</h5>
        <p>Efectivo: <strong>$<?= number_format($total_efectivo_sala, 2) ?></strong></p>
        <p>Transferencia: <strong>$<?= number_format($total_transferencia_sala, 2) ?></strong></p>
        <p>Total: <strong>$<?= number_format($total_efectivo_sala + $total_transferencia_sala, 2) ?></strong></p>

        
<div class="mb-3">
  <button class="btn btn-success me-2" onclick="abrirModal('sala')">➕ Ingreso/Egreso Sala</button>
  <button class="btn btn-danger" onclick="reiniciarCaja('sala')">🔄 Reiniciar Caja Sala</button>
</div>
<div class="accordion" id="acordeonSala">
          <?php foreach ($caja_sala as $i => $mov): ?>
          <div class="accordion-item">
            <h2 class="accordion-header" id="headingSala<?= $i ?>">
              <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseSala<?= $i ?>">
                <?= $mov['fecha'] ?> <?= $mov['hora'] ?> - <?= $mov['cliente'] ?: 'Sin cliente' ?> - $<?= number_format($mov['total'], 2) ?> (<?= $mov['forma_pago'] ?>)
              </button>
            </h2>
            <div id="collapseSala<?= $i ?>" class="accordion-collapse collapse" data-bs-parent="#acordeonSala">
              <div class="accordion-body">
                <p><strong>Comentario:</strong> <?= nl2br(htmlspecialchars($mov['comentario'])) ?></p>
                <?php if (!empty($mov['ticket_html'])): ?>
                  <div class="border p-2"><?= $mov['ticket_html'] ?></div>
                  <a href="../ver_ticket_sala.php?id=<?= $mov['id'] ?>" target="_blank" class="btn btn-sm btn-outline-secondary mt-2">Ver ticket completo</a>
                <?php endif; ?>
              </div>
            </div>
          </div>
          <?php endforeach; ?>
        </div>
      </div>

      <div class="tab-pane fade" id="mesa" role="tabpanel">
        <h5>Totales Mesas</h5>
        <p>Efectivo: <strong>$<?= number_format($total_efectivo_mesa, 2) ?></strong></p>
        <p>Transferencia: <strong>$<?= number_format($total_transferencia_mesa, 2) ?></strong></p>
        <p>Total: <strong>$<?= number_format($total_efectivo_mesa + $total_transferencia_mesa, 2) ?></strong></p>

        
<div class="mb-3">
  <button class="btn btn-success me-2" onclick="abrirModal('mesa')">➕ Ingreso/Egreso Mesa</button>
  <button class="btn btn-danger" onclick="reiniciarCaja('mesa')">🔄 Reiniciar Caja Mesa</button>
</div>
<div class="accordion" id="acordeonMesa">
          <?php foreach ($caja_mesa as $i => $mov): ?>
          <div class="accordion-item">
            <h2 class="accordion-header" id="headingMesa<?= $i ?>">
              <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseMesa<?= $i ?>">
                <?php
                $importe = floatval($mov['efectivo']) + floatval($mov['transferencia']);
                ?>
                <?= $mov['fecha'] ?> <?= $mov['hora'] ?> - <?= $mov['cliente'] ?: 'Sin cliente' ?> - $<?= number_format($importe, 2) ?> (<?= $mov['forma_pago'] ?>)
              </button>
            </h2>
            <div id="collapseMesa<?= $i ?>" class="accordion-collapse collapse" data-bs-parent="#acordeonMesa">
              <div class="accordion-body">
                  <a href="../ver_ticket_mesa.php?id=<?= $mov['id'] ?>" target="_blank" class="btn btn-sm btn-outline-secondary mt-2">Ver ticket completo</a>
                <?php if (!empty($mov['ticket_html'])): ?>
                  <div class="border p-2"><?= $mov['ticket_html'] ?></div>
                  <a href="../ver_ticket_mesa.php?id=<?= $mov['id'] ?>" target="_blank" class="btn btn-sm btn-outline-secondary mt-2">Ver ticket completo</a>
                <?php endif; ?>
              </div>
            </div>
          </div>
          <?php endforeach; ?>
        </div>
      </div>
    </div>
  </div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

<!-- Modal Movimiento Manual -->
<div class="modal fade" id="modalMovimiento" tabindex="-1">
  <div class="modal-dialog">
    <form method="post" action="guardar_movimiento_manual.php" class="modal-content">
      <input type="hidden" name="origen" id="inputOrigen">
      <div class="modal-header"><h5 class="modal-title">➕ Movimiento Manual</h5></div>
      <div class="modal-body">
        <label>Monto</label>
        <input type="number" name="monto" class="form-control mb-2" step="0.01" required>
        <label>Tipo</label>
        <select name="tipo" class="form-select mb-2">
          <option value="ingreso">Ingreso</option>
          <option value="egreso">Egreso</option>
        </select>
        <label>Forma de pago</label>
        <select name="forma_pago" class="form-select mb-2">
          <option value="efectivo">Efectivo</option>
          <option value="transferencia">Transferencia</option>
        </select>
        <label>Comentario</label>
        <textarea name="comentario" class="form-control"></textarea>
      </div>
      <div class="modal-footer">
        <button type="submit" class="btn btn-success">Guardar</button>
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
      </div>
    </form>
  </div>
</div>

<script>
  function abrirModal(origen) {
    document.getElementById('inputOrigen').value = origen;
    new bootstrap.Modal(document.getElementById('modalMovimiento')).show();
  }

  function reiniciarCaja(origen) {
    if (confirm("¿Seguro que querés reiniciar la caja de " + origen + "? Esto agregará un ajuste negativo pero no borra los tickets.")) {
      fetch("reiniciar_caja.php?origen=" + origen, { method: "POST" })
        .then(r => r.text())
        .then(txt => {
          alert("Caja reiniciada correctamente");
          location.reload();
        });
    }
  }
</script>

</body>
</html>
