<?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();

$shift_id = isset($_GET['shift_id']) ? (int)$_GET['shift_id'] : 0;
if ($shift_id <= 0) die('Turno invalido');

$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 sh.*, s.business_date, u1.username AS opened_user, u2.username AS closed_user
    FROM cash_register_shifts sh
    JOIN cash_register_sessions s ON s.id = sh.session_id
    LEFT JOIN users u1 ON u1.id = sh.opened_by
    LEFT JOIN users u2 ON u2.id = sh.closed_by
    WHERE sh.id = ?
");
$stmt->execute([$shift_id]);
$shift = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$shift) die('Turno no encontrado');

$start_at = $shift['opened_at'];
$end_at = $shift['closed_at'] ?: date('Y-m-d H:i:s');

$stmt = $db->prepare("
    SELECT p.method, COALESCE(pm.name, p.method) AS method_name, COUNT(*) AS count, COALESCE(SUM(p.amount), 0) AS amount
    FROM payments p
    LEFT JOIN payment_methods pm ON pm.code = p.method
    WHERE p.paid_at BETWEEN ? AND ?
    GROUP BY p.method, pm.name
    ORDER BY amount DESC
");
$stmt->execute([$start_at, $end_at]);
$payments = $stmt->fetchAll(PDO::FETCH_ASSOC);

$stmt = $db->prepare("
    SELECT *
    FROM cash_register_movements
    WHERE session_id = ? AND created_at BETWEEN ? AND ?
    ORDER BY created_at ASC, id ASC
");
$stmt->execute([$shift['session_id'], $start_at, $end_at]);
$movements = $stmt->fetchAll(PDO::FETCH_ASSOC);

$stmt = $db->prepare("
    SELECT o.order_number, c.full_name AS customer_name, p.method, p.amount, p.paid_at
    FROM payments p
    JOIN orders o ON o.id = p.order_id
    JOIN customers c ON c.id = o.customer_id
    WHERE p.paid_at BETWEEN ? AND ?
    ORDER BY p.paid_at ASC, p.id ASC
");
$stmt->execute([$start_at, $end_at]);
$orders = $stmt->fetchAll(PDO::FETCH_ASSOC);

$cash_payments = 0; $total_payments = 0;
foreach ($payments as $p) {
    $total_payments += (float)$p['amount'];
    if ($p['method'] === 'cash' || stripos((string)$p['method_name'], 'efectivo') !== false) $cash_payments += (float)$p['amount'];
}
$movement_in = 0; $movement_out = 0;
foreach ($movements as $m) {
    if ($m['type'] === 'in') $movement_in += (float)$m['amount'];
    else $movement_out += (float)$m['amount'];
}
$expected = (float)$shift['opening_amount'] + $cash_payments + $movement_in - $movement_out;
$counted = $shift['closing_amount'] === null ? 0 : (float)$shift['closing_amount'];
$difference = $shift['status'] === 'closed' ? $counted - $expected : 0;

$pdf = new TCPDF('L', 'mm', 'LETTER', true, 'UTF-8', false);
$pdf->SetCreator('Laundry App');
$pdf->SetTitle('Reporte de Turno 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; }
  .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; }
</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">
      REPORTE DE TURNO<br>
      <span class="muted" style="font-size:11px;">Turno #'.(int)$shift['shift_number'].' | '.h(strtoupper($shift['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($shift['opening_amount'], $moneda).'</div></td>
    <td><div class="label">Cash cobrado</div><div class="value">'.fmtM($cash_payments, $moneda).'</div></td>
    <td><div class="label">Esperado</div><div class="value">'.fmtM($expected, $moneda).'</div></td>
    <td><div class="label">Contado</div><div class="value">'.($shift['status'] === 'closed' ? fmtM($counted, $moneda) : 'Abierto').'</div></td>
    <td><div class="label">Diferencia</div><div class="value">'.($shift['status'] === 'closed' ? fmtM($difference, $moneda) : '-').'</div></td>
  </tr>
</table>
<table width="100%" cellpadding="4">
  <tr>
    <td><b>Abierto:</b> '.fmtDT($shift['opened_at']).' por '.h($shift['opened_user'] ?? '-').'</td>
    <td><b>Cerrado:</b> '.fmtDT($shift['closed_at']).' por '.h($shift['closed_user'] ?? '-').'</td>
  </tr>
</table>

<h3>Pagos por metodo</h3>
<table class="grid" cellpadding="0" cellspacing="0">
  <tr><th>Metodo</th><th width="18%">Transacciones</th><th width="22%">Monto</th></tr>';
foreach ($payments as $p) {
    $html .= '<tr><td>'.h($p['method_name']).'</td><td align="right">'.(int)$p['count'].'</td><td align="right">'.fmtM($p['amount'], $moneda).'</td></tr>';
}
if (!$payments) $html .= '<tr><td colspan="3" align="center">Sin pagos en este turno</td></tr>';
$html .= '</table>

<h3>Ordenes cobradas</h3>
<table class="grid" cellpadding="0" cellspacing="0">
  <tr><th width="18%">Hora</th><th width="20%">Orden</th><th>Cliente</th><th width="18%">Metodo</th><th width="18%">Monto</th></tr>';
foreach ($orders as $o) {
    $html .= '<tr><td>'.fmtDT($o['paid_at']).'</td><td>'.h($o['order_number']).'</td><td>'.h($o['customer_name']).'</td><td>'.h($o['method']).'</td><td align="right">'.fmtM($o['amount'], $moneda).'</td></tr>';
}
if (!$orders) $html .= '<tr><td colspan="5" align="center">Sin ordenes cobradas en este turno</td></tr>';
$html .= '</table>

<h3>Movimientos manuales</h3>
<table class="grid" cellpadding="0" cellspacing="0">
  <tr><th width="18%">Hora</th><th width="14%">Tipo</th><th>Concepto</th><th width="18%">Monto</th></tr>';
foreach ($movements as $m) {
    $html .= '<tr><td>'.fmtDT($m['created_at']).'</td><td>'.($m['type'] === 'in' ? 'Entrada' : 'Salida').'</td><td>'.h($m['concept']).'</td><td align="right">'.fmtM($m['amount'], $moneda).'</td></tr>';
}
if (!$movements) $html .= '<tr><td colspan="4" align="center">Sin movimientos manuales</td></tr>';
$html .= '</table>';

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