<?php
header("Content-Type: application/pdf");
header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache");
header("Expires: 0");

require_once dirname(__DIR__) . '/vendor/tcpdf/tcpdf.php';
require_once dirname(__DIR__) . '/config/database.php';

$database = new Database();
$db = $database->getConnection();

$session_id = isset($_GET['session_id']) ? (int)$_GET['session_id'] : 0;
if ($session_id <= 0) die('Caja invalida');

$conf = [];
try {
    $rs = $db->query("SELECT clave, valor FROM configuracion");
    if ($rs) while ($r = $rs->fetch(PDO::FETCH_ASSOC)) $conf[$r['clave']] = $r['valor'];
} catch (Exception $e) {}

date_default_timezone_set($conf['zona_horaria'] ?? 'America/Puerto_Rico');
$empresa = [
    'nombre' => $conf['empresa_nombre'] ?? 'Lavanderia y Sastreria PR',
    'telefono' => $conf['empresa_telefono'] ?? '(787) 555-0000',
    'email' => $conf['empresa_email'] ?? 'contacto@laundryapp.com',
    'direccion' => $conf['empresa_direccion'] ?? 'Calle 34 #7534, Puerto Rico',
];
$moneda = $conf['moneda'] ?? 'USD';

function h($v) { return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }
function fmtM($v, $m) { return ($m === 'EUR' ? 'EUR ' : '$') . number_format((float)$v, 2); }
function fmtDT($v) { $t = strtotime((string)$v); return $t ? date('m/d/Y h:i A', $t) : '-'; }

$stmt = $db->prepare("
    SELECT s.*,
           COALESCE(opened_user.full_name, opened_user.username) AS opened_user,
           COALESCE(closed_user.full_name, closed_user.username) AS closed_user
    FROM cash_register_sessions s
    LEFT JOIN users opened_user ON opened_user.id = s.opened_by
    LEFT JOIN users closed_user ON closed_user.id = s.closed_by
    WHERE s.id = ?
");
$stmt->execute([$session_id]);
$session = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$session) die('Caja no encontrada');

$breakdown = [];
if (!empty($session['close_breakdown'])) {
    $decoded = json_decode($session['close_breakdown'], true);
    if (is_array($decoded)) $breakdown = $decoded;
}

$cash = $breakdown['cash'] ?? [];
$denominations = $cash['denominations'] ?? [];
$nonCash = $breakdown['nonCash'] ?? [];
$totals = $breakdown['totals'] ?? [];

$pdf = new TCPDF('L', 'mm', 'LETTER', true, 'UTF-8', false);
$pdf->SetCreator('Laundry App');
$pdf->SetTitle('Cuadre de Caja');
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
$pdf->SetMargins(10, 10, 10);
$pdf->AddPage();
$pdf->SetFont('helvetica', '', 9);

$html = '
<style>
  .header { background-color:#0B1B3F; color:#ffffff; padding:18px 20px; }
  .muted { color:#AAB4C6; }
  .title { font-size:24px; font-weight:bold; text-align:right; }
  .brand { font-size:22px; font-weight:bold; }
  .kpis td { background-color:#EAF4FF; border-left:4px solid #0877FF; padding:10px; font-size:13px; text-align:center; }
  .label { color:#5B6680; font-size:10px; font-weight:bold; text-transform:uppercase; }
  .value { font-size:16px; font-weight:bold; color:#0B1B3F; }
  table.grid { border-collapse:collapse; width:100%; }
  table.grid th { background-color:#0B1B3F; color:#ffffff; font-weight:bold; padding:7px; }
  table.grid td { border-bottom:1px solid #D9E3F0; padding:7px; }
  h3 { color:#0B1B3F; font-size:14px; margin:16px 0 6px; }
  .notes { border:1px solid #D9E3F0; padding:8px; min-height:26px; }
</style>
<table class="header" width="100%" cellpadding="0" cellspacing="0">
  <tr>
    <td width="55%">
      <div class="brand">'.h($empresa['nombre']).'</div>
      <div class="muted">'.h($empresa['direccion']).'<br>Tel: '.h($empresa['telefono']).' | '.h($empresa['email']).'</div>
    </td>
    <td width="45%" class="title">
      CUADRE DE CAJA<br>
      <span class="muted" style="font-size:11px;">Caja #'.(int)$session['id'].' | '.h(strtoupper($session['status'])).'</span>
    </td>
  </tr>
</table>
<br>
<table class="kpis" width="100%" cellpadding="0" cellspacing="8">
  <tr>
    <td><div class="label">Apertura</div><div class="value">'.fmtM($session['opening_amount'], $moneda).'</div></td>
    <td><div class="label">Efectivo esperado</div><div class="value">'.fmtM($session['expected_cash'], $moneda).'</div></td>
    <td><div class="label">Efectivo contado</div><div class="value">'.fmtM($session['closing_amount'], $moneda).'</div></td>
    <td><div class="label">No cash contado</div><div class="value">'.fmtM($totals['countedNonCash'] ?? 0, $moneda).'</div></td>
    <td><div class="label">Diferencia</div><div class="value">'.fmtM($session['difference_amount'], $moneda).'</div></td>
  </tr>
</table>
<table width="100%" cellpadding="4">
  <tr>
    <td><b>Abierta:</b> '.fmtDT($session['opened_at']).' por '.h($session['opened_user'] ?? '-').'</td>
    <td><b>Cerrada:</b> '.fmtDT($session['closed_at']).' por '.h($session['closed_user'] ?? '-').'</td>
  </tr>
</table>

<h3>Conteo de efectivo por denominacion</h3>
<table class="grid" cellpadding="0" cellspacing="0">
  <tr><th>Denominacion</th><th width="18%">Cantidad</th><th width="22%">Total</th></tr>';
foreach ($denominations as $row) {
    $html .= '<tr><td>'.h($row['label'] ?? '').'</td><td align="right">'.h($row['quantity'] ?? 0).'</td><td align="right">'.fmtM($row['total'] ?? 0, $moneda).'</td></tr>';
}
if (!$denominations) $html .= '<tr><td colspan="3" align="center">Sin detalle de denominaciones guardado</td></tr>';
$html .= '</table>

<h3>Metodos no cash</h3>
<table class="grid" cellpadding="0" cellspacing="0">
  <tr><th>Metodo</th><th width="18%">Esperado</th><th width="18%">Contado</th><th width="18%">Diferencia</th></tr>';
foreach ($nonCash as $row) {
    $html .= '<tr><td>'.h($row['methodName'] ?? $row['method'] ?? '').'</td><td align="right">'.fmtM($row['expected'] ?? 0, $moneda).'</td><td align="right">'.fmtM($row['counted'] ?? 0, $moneda).'</td><td align="right">'.fmtM($row['difference'] ?? 0, $moneda).'</td></tr>';
}
if (!$nonCash) $html .= '<tr><td colspan="4" align="center">Sin metodos no cash para confirmar</td></tr>';
$html .= '</table>

<h3>Resumen del cuadre</h3>
<table class="grid" cellpadding="0" cellspacing="0">
  <tr><th>Concepto</th><th width="22%">Esperado</th><th width="22%">Contado</th><th width="22%">Diferencia</th></tr>
  <tr><td>Efectivo</td><td align="right">'.fmtM($cash['expected'] ?? $session['expected_cash'], $moneda).'</td><td align="right">'.fmtM($cash['counted'] ?? $session['closing_amount'], $moneda).'</td><td align="right">'.fmtM($cash['difference'] ?? $session['difference_amount'], $moneda).'</td></tr>
  <tr><td>No cash</td><td align="right">'.fmtM($totals['expectedNonCash'] ?? 0, $moneda).'</td><td align="right">'.fmtM($totals['countedNonCash'] ?? 0, $moneda).'</td><td align="right">'.fmtM(($totals['countedNonCash'] ?? 0) - ($totals['expectedNonCash'] ?? 0), $moneda).'</td></tr>
</table>

<h3>Notas</h3>
<div class="notes">'.h($session['notes'] ?: 'Sin notas').'</div>';

$pdf->writeHTML($html, true, false, true, false, '');
$pdf->Output('cuadre_caja_'.$session_id.'.pdf', 'I');
?>
