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

$id = intval($_GET['id'] ?? 0);
$autoPrint = isset($_GET['print']);

if ($id <= 0) {
  echo "❌ ID inválido.";
  exit;
}

$sql = "SELECT cs.*, s.nombre AS sala_nombre
        FROM caja_sala cs
        LEFT JOIN salas s ON cs.sala_id = s.id
        WHERE cs.id = {$id} LIMIT 1";
$res = mysqli_query($con, $sql);
if (!$res || mysqli_num_rows($res) === 0) {
  echo "❌ Ticket no encontrado.";
  exit;
}

$ticket = mysqli_fetch_assoc($res);
$detalles = json_decode($ticket['detalles_json'] ?? '', true);
if (isset($_GET['modal'])) {
  echo "<pre style='font-family: monospace; font-size: 13px'>";
  echo "🎫 Ticket #{$ticket['id']}\n";
  echo "Cliente: " . ($ticket['cliente'] ?: '-') . "\n";
  echo "Sala: " . ($ticket['sala_nombre'] ?: '-') . "\n";
  echo "Fecha: {$ticket['fecha']} {$ticket['hora']}\n";
  echo "Total: $" . number_format($ticket['total'], 2) . "\n";
  echo "Pago: {$ticket['forma_pago']}\n";
  echo "-------------------------\n";

  $detalles = json_decode($ticket['detalles_json'] ?? '', true);
  if ($detalles) {
    echo "Inicio: " . ($detalles['hora_inicio'] ?? '-') . "\n";
    echo "Duración: " . ($detalles['duracion'] ?? '-') . " min\n";
    echo "Precio sala: $" . number_format($detalles['precio_sala'] ?? 0, 2) . "\n";

    foreach (($detalles['productos'] ?? []) as $p) {
      echo "- Producto: {$p['nombre']} ($" . number_format($p['precio'], 2) . ")\n";
    }

    foreach (($detalles['alquileres'] ?? []) as $a) {
      echo "- Alquiler: {$a['nombre']} ($" . number_format($a['precio'], 2) . ")\n";
    }

    echo "Descuento: $" . number_format($detalles['descuento'] ?? 0, 2) . "\n";
  }

  echo "</pre>";
  exit;
}

?>
<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Ticket Sala #<?= htmlspecialchars($ticket['id']) ?></title>
  <style>
    /* Estilo optimizado para impresoras térmicas de 80mm */
    body {
      font-family: 'Courier New', monospace;
      font-size: 12px;
      width: 80mm;
      margin: 0;
      padding: 2mm;
      line-height: 1.2;
    }
    .header {
      text-align: center;
      margin-bottom: 3mm;
      border-bottom: 1px dashed #000;
      padding-bottom: 2mm;
    }
    .header h1 {
      margin: 0;
      font-size: 14px;
      font-weight: bold;
      text-transform: uppercase;
    }
    .header p {
      margin: 1mm 0;
      font-size: 10px;
    }
    .info {
      margin-bottom: 3mm;
    }
    .info-row {
      display: flex;
      margin-bottom: 1mm;
    }
    .info-label {
      flex: 1;
      font-weight: bold;
    }
    .info-value {
      flex: 2;
    }
    .divider {
      border-top: 1px dashed #000;
      margin: 3mm 0;
    }
    .section-title {
      font-weight: bold;
      margin-bottom: 2mm;
      text-align: center;
    }
    .item-row {
      display: flex;
      justify-content: space-between;
      margin-bottom: 1mm;
    }
    .item-name {
      flex: 2;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    .item-price {
      flex: 1;
      text-align: right;
    }
    .totals {
      margin-top: 3mm;
    }
    .total-row {
      display: flex;
      justify-content: space-between;
      margin-bottom: 1mm;
    }
    .grand-total {
      font-weight: bold;
      border-top: 1px dashed #000;
      border-bottom: 1px double #000;
      padding: 1mm 0;
    }
    .footer {
      text-align: center;
      margin-top: 5mm;
      font-size: 10px;
    }
    .no-print {
      display: none;
    }
    @media print {
      .no-print {
        display: none !important;
      }
      body {
        padding: 0;
      }
    }
  </style>
</head>
<body>

<div class="header">
  <h1>HUM CLUB DE MÚSICA</h1>
  <p>Bs As 1064 - Tel: tu viej4</p>
  <p>CUIT: tu viej0</p>
</div>

<div class="info">
  <div class="info-row">
    <span class="info-label">Ticket #:</span>
    <span class="info-value"><?= htmlspecialchars($ticket['id']) ?></span>
  </div>
  <div class="info-row">
    <span class="info-label">Fecha:</span>
    <span class="info-value"><?= htmlspecialchars($ticket['fecha']) ?> <?= htmlspecialchars($ticket['hora']) ?></span>
  </div>
  <div class="info-row">
    <span class="info-label">Sala:</span>
    <span class="info-value"><?= htmlspecialchars($ticket['sala_nombre'] ?: $ticket['sala_id']) ?></span>
  </div>
  <div class="info-row">
    <span class="info-label">Cliente:</span>
    <span class="info-value"><?= htmlspecialchars($ticket['cliente'] ?: '-') ?></span>
  </div>
  <div class="info-row">
    <span class="info-label">Pago:</span>
    <span class="info-value">
      <?= htmlspecialchars($ticket['forma_pago']) ?>
      <?php if($ticket['forma_pago'] === 'dividido'): ?>
        (Efectivo $<?= number_format($ticket['efectivo'],2,',','.') ?> / Transf. $<?= number_format($ticket['transferencia'],2,',','.') ?>)
      <?php elseif($ticket['forma_pago'] === 'efectivo'): ?>
        - $<?= number_format($ticket['efectivo'],2,',','.') ?>
      <?php elseif($ticket['forma_pago'] === 'transferencia'): ?>
        - $<?= number_format($ticket['transferencia'],2,',','.') ?>
      <?php endif; ?>
    </span>
  </div>
</div>

<?php if($detalles): ?>
  <?php
    $precioSala = floatval($detalles['precio_sala'] ?? 0);
    $productos  = $detalles['productos'] ?? [];
    $alquileres = $detalles['alquileres'] ?? [];
    $descuento  = floatval($detalles['descuento'] ?? 0);
  ?>
  
  <div class="divider"></div>
  
  <div class="section-title">RESUMEN DE TURNO</div>
  
  <div class="info-row">
    <span class="info-label">Hora inicio:</span>
    <span class="info-value"><?= htmlspecialchars($detalles['hora_inicio'] ?? '-') ?></span>
  </div>
  <div class="info-row">
    <span class="info-label">Hora fin:</span>
    <span class="info-value"><?= htmlspecialchars($detalles['hora_fin'] ?? '-') ?></span>
  </div>
  <div class="info-row">
    <span class="info-label">Duración:</span>
    <span class="info-value">
      <?php
        $dur = $detalles['duracion'] ?? '';
        if(is_numeric($dur)){
          $h = floor($dur/60);
          $m = $dur % 60;
          echo ($h ? $h.'h ' : '').$m.'m';
        } else {
          echo htmlspecialchars($dur ?: '-');
        }
      ?>
    </span>
  </div>
  <div class="info-row">
    <span class="info-label">Precio Sala:</span>
    <span class="info-value">$<?= number_format($precioSala,2,',','.') ?></span>
  </div>

  <?php if($productos): ?>
    <div class="divider"></div>
    <div class="section-title">PRODUCTOS</div>
    <?php foreach($productos as $p): ?>
      <div class="item-row">
        <span class="item-name"><?= htmlspecialchars($p['nombre']) ?></span>
        <span class="item-price">$<?= number_format($p['precio'] ?? 0,2,',','.') ?></span>
      </div>
    <?php endforeach; ?>
  <?php endif; ?>

  <?php if($alquileres): ?>
    <div class="divider"></div>
    <div class="section-title">ALQUILERES</div>
    <?php foreach($alquileres as $a): ?>
      <div class="item-row">
        <span class="item-name"><?= htmlspecialchars($a['nombre']) ?></span>
        <span class="item-price">$<?= number_format($a['precio'] ?? 0,2,',','.') ?></span>
      </div>
    <?php endforeach; ?>
  <?php endif; ?>

  <div class="divider"></div>
  
  <div class="totals">
    <?php
      $sub = $precioSala;
      foreach($productos as $p){ $sub += floatval($p['precio'] ?? 0); }
      foreach($alquileres as $a){ $sub += floatval($a['precio'] ?? 0); }
    ?>
    <div class="total-row">
      <span>Subtotal:</span>
      <span>$<?= number_format($sub,2,',','.') ?></span>
    </div>
    <div class="total-row">
      <span>Descuento:</span>
      <span>- $<?= number_format($descuento,2,',','.') ?></span>
    </div>
    <div class="total-row grand-total">
      <span>TOTAL:</span>
      <span>$<?= number_format(floatval($ticket['total']), 2, ',', '.') ?></span>
    </div>
  </div>
<?php else: ?>
  <div class="divider"></div>
  <div style="text-align: center; font-style: italic;">Este ticket no contiene detalle JSON</div>
<?php endif; ?>

<div class="footer">
  <div>¡Gracias por tu visita!</div>
  <div>www.humclubdemusica.com.ar</div>
</div>

<div class="no-print" style="margin-top: 5mm; text-align: center;">
  <button onclick="window.print()" style="padding: 3mm 5mm; font-size: 12px;">
    Imprimir Ticket
  </button>
</div>

<?php if($autoPrint): ?>
<script> window.print(); </script>
<?php endif; ?>
</body>
</html>