<?php
include('conexion.php');
include_once('nomina_helpers.php');
include_once('nomina_legal_helpers.php');
include_once('nomina_prestaciones_helpers.php');
include_once('nomina_prestaciones_master_helpers.php');
if (session_status() !== PHP_SESSION_ACTIVE) { session_start(); }
if (!isset($_SESSION['usuario'])) { header('Location: login.php'); exit; }
nomina_ensure_cargos_schema($conexion);
nomina_ensure_prestaciones_schema($conexion);
nomina_pm_ensure_schema($conexion);

$fechaCorte = nomina_date_to_iso($_GET['fecha_corte'] ?? date('Y-m-d')) ?: date('Y-m-d');
$tasaRef = nomina_normalize_decimal($_GET['tasa_bcv_ref'] ?? 0, 0);
$bcvInfo = nomina_bcv_auto_refresh($conexion, false);
$bcvLatest = $bcvInfo['latest'] ?? null;
if ($tasaRef <= 0 && $bcvLatest && isset($bcvLatest['rate_value'])) { $tasaRef = (float)$bcvLatest['rate_value']; }
if ($tasaRef <= 0) { $tasaRef = 1; }
$utilidadesDiasRef = nomina_normalize_decimal($_GET['utilidades_dias_ref'] ?? 30, 30);
$personas = nomina_fetch_active_people($conexion);
$personaId = isset($_GET['persona_id']) ? (int)$_GET['persona_id'] : 0;
if ($personaId <= 0 && $personas) { $personaId = (int)$personas[0]['id']; }
$persona = nomina_prestaciones_find_persona($personas, $personaId);
$balance = $persona ? nomina_prestaciones_calculate_balance($conexion, $persona, $fechaCorte, $tasaRef, $utilidadesDiasRef) : null;
$events = $persona ? nomina_prestaciones_fetch_person_events($conexion, $personaId, 100) : [];
$interests = $persona ? nomina_pm_fetch_interests($conexion, $personaId, 100) : [];
$salaryHistory = $persona ? nomina_pm_fetch_salary_history($conexion, $personaId, 60) : [];
$sumInterests = $persona ? nomina_pm_sum_interests($conexion, $personaId) : 0.0;
$sumAdvances = $persona ? nomina_pm_sum_advances($conexion, $personaId) : 0.0;
$baseFavorable = $balance ? (float)$balance['favorable_base_bs'] : 0.0;
$capitalRegistered = $balance ? (float)$balance['guarantee_registered_bs'] : 0.0;
$saldoEstimado = max($baseFavorable, $capitalRegistered) + $sumInterests - $sumAdvances;
?>
<!doctype html>
<html lang="es">
<head>
<meta charset="utf-8">
<title>Reporte legal por trabajador</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<style>
body{font-family:Arial,Helvetica,sans-serif;background:#f2f5f9;color:#243b53;margin:0}.wrap{max-width:1260px;margin:0 auto;padding:24px}.card{background:#fff;border:1px solid #d9e2ec;border-radius:18px;padding:20px;margin-bottom:18px;box-shadow:0 8px 24px rgba(15,23,42,.05)}.top{display:flex;justify-content:space-between;gap:14px;align-items:flex-start;flex-wrap:wrap}.top h1{margin:0;font-size:22px}.muted,.mini{color:#6b7c93}.mini{font-size:12px}.btn{display:inline-block;background:#1f4aa8;color:#fff;text-decoration:none;border:none;border-radius:14px;padding:12px 18px;font-weight:700;cursor:pointer}.btn.secondary{background:#fff;color:#1f4aa8;border:1px solid #b7c6e3}.btn.ghost{background:#eef3ff;color:#1f4aa8}.filters,.stats{display:grid;gap:14px}.filters{grid-template-columns:1.5fr .7fr .7fr .7fr auto}.stats{grid-template-columns:repeat(5,1fr)}.field label{display:block;font-weight:700;margin-bottom:6px}.field input,.field select{width:100%;box-sizing:border-box;border:1px solid #cbd5e1;border-radius:12px;padding:11px 12px;font-size:15px}.table-wrap{overflow:auto}.table{width:100%;border-collapse:separate;border-spacing:0}.table th,.table td{padding:11px 10px;border-bottom:1px solid #e5edf5;text-align:left;vertical-align:top}.table th{background:#f8fafc;font-size:13px}.stat{border:1px solid #d9e2ec;border-radius:14px;padding:14px}.stat .v{font-size:24px;font-weight:800;margin-bottom:6px}.tot{font-weight:800}.note{padding:12px 14px;border-radius:12px;background:#f8fafc;border:1px dashed #cbd5e1;color:#486581}.warn{color:#92400e}.good{color:#166534}@media(max-width:1000px){.filters,.stats{grid-template-columns:1fr}}@media print{.no-print{display:none}.wrap{max-width:none;padding:0}.card{box-shadow:none;break-inside:avoid}}
</style>
</head>
<body>
<div class="wrap">
  <div class="card top">
    <div>
      <h1>Reporte legal por trabajador</h1>
      <div class="muted">Resumen auditor de salario histórico, prestaciones, intereses, anticipos y saldo estimado. No sustituye la liquidación final; sirve como soporte de control laboral.</div>
    </div>
    <div class="no-print">
      <a class="btn secondary" href="nomina_prestaciones.php">Prestaciones</a>
      <a class="btn ghost" href="nomina_tasas_interes_bcv.php">Tasas BCV</a>
      <button class="btn" onclick="window.print()">Imprimir</button>
    </div>
  </div>

  <div class="card no-print">
    <form method="get" class="filters">
      <div class="field"><label>Trabajador</label><select name="persona_id">
        <?php foreach ($personas as $p): ?><option value="<?php echo (int)$p['id']; ?>" <?php echo (int)$p['id'] === $personaId ? 'selected' : ''; ?>><?php echo h(trim(($p['apellido'] ?? '') . ' ' . ($p['nombre'] ?? '')) . ' - ' . ($p['cedula'] ?? '')); ?></option><?php endforeach; ?>
      </select></div>
      <div class="field"><label>Fecha corte</label><input type="date" name="fecha_corte" value="<?php echo h($fechaCorte); ?>"></div>
      <div class="field"><label>Tasa BCV ref.</label><input name="tasa_bcv_ref" value="<?php echo h(number_format($tasaRef, 4, '.', '')); ?>"></div>
      <div class="field"><label>Utilidades días</label><input name="utilidades_dias_ref" type="number" value="<?php echo h((string)$utilidadesDiasRef); ?>"></div>
      <div class="field"><label>&nbsp;</label><button class="btn" type="submit">Actualizar</button></div>
    </form>
  </div>

  <?php if (!$persona || !$balance): ?>
    <div class="card"><div class="note">No hay trabajador seleccionado o no se pudo calcular el reporte.</div></div>
  <?php else: $srv = $balance['service']; $ri = $balance['ref']; ?>
    <div class="card">
      <h2 style="margin-top:0;"><?php echo h(trim(($persona['nombre'] ?? '') . ' ' . ($persona['apellido'] ?? ''))); ?></h2>
      <div class="muted">CI: <b><?php echo h($persona['cedula'] ?? ''); ?></b> · Cargo: <b><?php echo h($persona['cargo'] ?? ''); ?></b> · Ingreso: <b><?php echo h($persona['fecha_ingreso'] ?? ''); ?></b> · Antigüedad al corte: <b><?php echo (int)$srv['years']; ?> años, <?php echo (int)$srv['months']; ?> meses, <?php echo (int)$srv['days']; ?> días</b>.</div>
    </div>

    <div class="card">
      <h2 style="margin-top:0;">Resumen económico</h2>
      <div class="stats">
        <div class="stat"><div class="v"><?php echo h(number_format((float)$ri['monthly_normal_bs'], 2, ',', '.')); ?></div><div class="mini">Salario normal mensual Bs</div></div>
        <div class="stat"><div class="v"><?php echo h(number_format((float)$ri['integral_daily_bs'], 2, ',', '.')); ?></div><div class="mini">Salario integral diario ref.</div></div>
        <div class="stat"><div class="v"><?php echo h(number_format($baseFavorable, 2, ',', '.')); ?></div><div class="mini">Base más favorable Bs</div></div>
        <div class="stat"><div class="v"><?php echo h(number_format($sumInterests, 2, ',', '.')); ?></div><div class="mini">Intereses registrados Bs</div></div>
        <div class="stat"><div class="v"><?php echo h(number_format($saldoEstimado, 2, ',', '.')); ?></div><div class="mini">Saldo estimado Bs</div></div>
      </div>
      <div class="note" style="margin-top:14px;">Saldo estimado = mayor entre garantía / Art. 142(c) + intereses registrados - anticipos registrados. Anticipos registrados: <b><?php echo h(number_format($sumAdvances, 2, ',', '.')); ?></b> Bs.</div>
    </div>

    <div class="card">
      <h2 style="margin-top:0;">Historial salarial real</h2>
      <?php if ($salaryHistory): ?><div class="table-wrap"><table class="table"><thead><tr><th>Vigencia</th><th>Origen</th><th>Salario original</th><th>BCV</th><th>Mensual Bs</th><th>Normal Bs</th><th>Integral Bs</th><th>Referencia</th></tr></thead><tbody>
        <?php foreach ($salaryHistory as $row): ?><tr>
          <td><?php echo h($row['fecha_desde']); ?> → <?php echo h($row['fecha_hasta'] ?? ''); ?></td>
          <td><?php echo h($row['salario_origen']); ?></td>
          <td><?php echo h($row['salario_moneda'] . ' ' . number_format((float)$row['salario_monto_original'], 2, ',', '.')); ?></td>
          <td><?php echo h(number_format((float)$row['tasa_bcv_usada'], 4, ',', '.')); ?></td>
          <td class="tot"><?php echo h(number_format((float)$row['salario_mensual_bs'], 2, ',', '.')); ?></td>
          <td><?php echo h(number_format((float)$row['salario_normal_mensual_bs'], 2, ',', '.')); ?></td>
          <td><?php echo h(number_format((float)$row['salario_integral_mensual_bs'], 2, ',', '.')); ?></td>
          <td><?php echo h($row['origen']); ?> #<?php echo h($row['referencia_corrida_id']); ?></td>
        </tr><?php endforeach; ?>
      </tbody></table></div><?php else: ?><div class="note">No hay historial salarial sincronizado. En prestaciones puedes usar “Sincronizar historial salarial desde corridas cerradas”.</div><?php endif; ?>
    </div>

    <div class="card">
      <h2 style="margin-top:0;">Eventos de prestaciones</h2>
      <?php if ($events): ?><div class="table-wrap"><table class="table"><thead><tr><th>Fecha</th><th>Tipo</th><th>Referencia</th><th>Días</th><th>Integral día Bs</th><th>Monto Bs</th><th>Observación</th></tr></thead><tbody>
        <?php foreach ($events as $ev): ?><tr>
          <td><?php echo h($ev['fecha_evento']); ?></td>
          <td><?php echo h(nomina_prestaciones_event_type_label($ev['tipo'])); ?></td>
          <td><?php echo h($ev['periodo_ref']); ?></td>
          <td><?php echo h(number_format((float)$ev['dias'], 2, ',', '.')); ?></td>
          <td><?php echo h(number_format((float)$ev['salario_integral_diario_bs'], 2, ',', '.')); ?></td>
          <td class="tot"><?php echo h(number_format((float)$ev['monto_bs'], 2, ',', '.')); ?></td>
          <td><?php echo h($ev['observacion'] ?? ''); ?></td>
        </tr><?php endforeach; ?>
      </tbody></table></div><?php else: ?><div class="note">No existen eventos de prestaciones para este trabajador.</div><?php endif; ?>
    </div>

    <div class="card">
      <h2 style="margin-top:0;">Intereses sobre prestaciones</h2>
      <?php if ($interests): ?><div class="table-wrap"><table class="table"><thead><tr><th>Mes</th><th>Método</th><th>Capital Bs</th><th>Tasa anual %</th><th>Interés Bs</th><th>Fuente</th></tr></thead><tbody>
        <?php foreach ($interests as $in): ?><tr>
          <td><?php echo h($in['periodo_ym']); ?></td>
          <td><?php echo h($in['metodo']); ?></td>
          <td><?php echo h(number_format((float)$in['capital_base_bs'], 2, ',', '.')); ?></td>
          <td><?php echo h(number_format((float)$in['tasa_anual'], 4, ',', '.')); ?></td>
          <td class="tot"><?php echo h(number_format((float)$in['interes_bs'], 2, ',', '.')); ?></td>
          <td><?php echo h($in['fuente_url'] ?? ''); ?></td>
        </tr><?php endforeach; ?>
      </tbody></table></div><?php else: ?><div class="note">No hay intereses calculados. Carga tasas BCV y genera intereses desde prestaciones.</div><?php endif; ?>
    </div>
  <?php endif; ?>
</div>
</body>
</html>
