<?php
include('conexion.php');
include_once('nomina_helpers.php');
include_once('nomina_vacaciones_master_helpers.php');
if (session_status() !== PHP_SESSION_ACTIVE) { session_start(); }
if (!isset($_SESSION['usuario'])) { header('Location: login.php'); exit; }
nomina_vac_v8_ensure_schema($conexion);
$fechaCorte = nomina_vac_v8_iso($_GET['fecha_corte'] ?? date('Y-m-d')) ?: date('Y-m-d');
$tasaRef = nomina_vac_v8_decimal($_GET['tasa_bcv_ref'] ?? 1, 1);
$people = nomina_vac_v8_fetch_people($conexion);
$stats = nomina_vac_v8_stats($conexion, $people, $fechaCorte, $tasaRef);
$invalid = nomina_vac_v8_invalid_people($people, $fechaCorte);
$summary = nomina_vac_v8_summary($conexion);
$rows = [];
foreach ($people as $p) {
    if (!nomina_vac_v8_valid_date($p['fecha_ingreso'] ?? '')) { continue; }
    $b = nomina_vac_v8_balance($conexion, $p, $fechaCorte, $tasaRef, $summary[(int)$p['id']] ?? []);
    if ($b['pending_days'] > 0 || $b['pending_bonus_days'] > 0 || $b['salary']['fuente'] !== 'HISTORIAL_CORRIDA') {
        $rows[] = ['persona'=>$p,'balance'=>$b];
    }
}
$res = mysqli_query($conexion, "SELECT COUNT(*) AS total FROM nomina_vacaciones_eventos WHERE estado='REGISTRADO' AND (fuente_salario IS NULL OR fuente_salario='')");
$sinFuente = ($res && mysqli_num_rows($res)) ? (int)mysqli_fetch_assoc($res)['total'] : 0;
$res = mysqli_query($conexion, "SELECT COUNT(*) AS total FROM nomina_vacaciones_eventos WHERE estado='REGISTRADO' AND IFNULL(snapshot_json,'')='' ");
$sinSnapshot = ($res && mysqli_num_rows($res)) ? (int)mysqli_fetch_assoc($res)['total'] : 0;

$res = mysqli_query($conexion, "SELECT COUNT(*) AS total FROM nomina_vacaciones_eventos WHERE estado='REGISTRADO' AND (salario_moneda IS NULL OR salario_moneda='' OR salario_moneda='0')");
$monedaMala = ($res && mysqli_num_rows($res)) ? (int)mysqli_fetch_assoc($res)['total'] : 0;
$res = mysqli_query($conexion, "SELECT COUNT(*) AS total FROM nomina_vacaciones_eventos WHERE estado='REGISTRADO' AND (origen_registro IS NULL OR origen_registro='' OR origen_registro='0')");
$origenMalo = ($res && mysqli_num_rows($res)) ? (int)mysqli_fetch_assoc($res)['total'] : 0;
$res = mysqli_query($conexion, "SELECT COUNT(*) AS total FROM nomina_vacaciones_eventos WHERE estado='REGISTRADO' AND (soporte_referencia IS NULL OR LENGTH(TRIM(soporte_referencia)) < 12)");
$soporteDebil = ($res && mysqli_num_rows($res)) ? (int)mysqli_fetch_assoc($res)['total'] : 0;

$recentAudit = [];
$res = mysqli_query($conexion, "SELECT * FROM nomina_vacaciones_auditoria ORDER BY fecha_evento DESC, id DESC LIMIT 30");
if ($res) { while ($r = mysqli_fetch_assoc($res)) { $recentAudit[] = $r; } }
?>
<!doctype html><html lang="es"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Auditoría vacaciones v8.1</title><style>
body{font-family:Arial,Helvetica,sans-serif;background:#f3f6fa;color:#14233b;margin:0}.wrap{max-width:1400px;margin:0 auto;padding:24px}.card{background:#fff;border:1px solid #dbe5f1;border-radius:18px;padding:20px;margin-bottom:18px;box-shadow:0 8px 24px rgba(15,23,42,.05)}.btn{display:inline-block;background:#fff;color:#173f9f;border:1px solid #b7c6e3;text-decoration:none;border-radius:13px;padding:10px 14px;font-weight:700}.stats{display:grid;grid-template-columns:repeat(6,1fr);gap:12px}.stat{border:1px solid #dbe5f1;border-radius:14px;padding:14px}.stat .v{font-size:26px;font-weight:800}.table{width:100%;border-collapse:collapse}.table th,.table td{padding:10px;border-bottom:1px solid #e5edf5;text-align:left;vertical-align:top}.table th{background:#f8fafc}.badge{display:inline-block;border-radius:999px;background:#eef2ff;color:#1e3a8a;font-weight:700;font-size:12px;padding:4px 9px}.bad{color:#991b1b}.good{color:#166534}@media(max-width:1000px){.stats{grid-template-columns:1fr}}
</style></head><body><div class="wrap"><div class="card"><h1>Auditoría vacaciones v8.1</h1><p>Revisión de saldos, trabajadores sin fecha de ingreso, fuente salarial histórica y eventos con evidencia congelada.</p><a class="btn" href="nomina_vacaciones.php">Volver a vacaciones</a> <a class="btn" href="index.php">Dashboard</a></div><div class="card stats"><div class="stat"><div class="v"><?php echo (int)$stats['trabajadores']; ?></div><div>Activos</div></div><div class="stat"><div class="v bad"><?php echo (int)$stats['invalidos']; ?></div><div>Sin fecha ingreso</div></div><div class="stat"><div class="v"><?php echo (int)$stats['pendientes_trabajadores']; ?></div><div>Con saldo pendiente</div></div><div class="stat"><div class="v good"><?php echo (int)$stats['fuente_historial']; ?></div><div>Fuente historial</div></div><div class="stat"><div class="v bad"><?php echo (int)$stats['fuente_fallback']; ?></div><div>Fuente fallback</div></div><div class="stat"><div class="v"><?php echo (int)$stats['eventos']; ?></div><div>Eventos registrados</div></div></div><div class="card stats"><div class="stat"><div class="v bad"><?php echo (int)$sinFuente; ?></div><div>Eventos sin fuente salarial</div></div><div class="stat"><div class="v bad"><?php echo (int)$sinSnapshot; ?></div><div>Eventos sin snapshot</div></div><div class="stat"><div class="v"><?php echo number_format($stats['pendientes_dias'],2,',','.'); ?></div><div>Días disfrute pendientes</div></div><div class="stat"><div class="v"><?php echo number_format($stats['pendientes_bono'],2,',','.'); ?></div><div>Días bono pendientes</div></div><div class="stat"><div class="v bad"><?php echo (int)$monedaMala; ?></div><div>Moneda inválida</div></div><div class="stat"><div class="v bad"><?php echo (int)$origenMalo; ?></div><div>Origen inválido</div></div><div class="stat"><div class="v bad"><?php echo (int)$soporteDebil; ?></div><div>Soporte débil</div></div></div><?php if($invalid): ?><div class="card"><h2>Trabajadores bloqueados por fecha de ingreso</h2><table class="table"><thead><tr><th>Trabajador</th><th>Cédula</th><th>Cargo</th></tr></thead><tbody><?php foreach($invalid as $p): ?><tr><td><?php echo h(trim(($p['apellido']??'').' '.($p['nombre']??''))); ?></td><td><?php echo h($p['cedula']??''); ?></td><td><?php echo h($p['cargo']??''); ?></td></tr><?php endforeach; ?></tbody></table></div><?php endif; ?><div class="card"><h2>Trabajadores con saldo pendiente o fuente no histórica</h2><table class="table"><thead><tr><th>Trabajador</th><th>Ingreso</th><th>Años</th><th>Fuente</th><th>Días pendientes</th><th>Bono pendiente</th><th>Saldo Bs</th></tr></thead><tbody><?php foreach($rows as $r): $p=$r['persona']; $b=$r['balance']; ?><tr><td><?php echo h(trim(($p['apellido']??'').' '.($p['nombre']??''))); ?></td><td><?php echo h($p['fecha_ingreso']??''); ?></td><td><?php echo (int)$b['completed_years']; ?></td><td><span class="badge"><?php echo h($b['salary']['fuente']); ?></span></td><td><?php echo number_format($b['pending_days'],2,',','.'); ?></td><td><?php echo number_format($b['pending_bonus_days'],2,',','.'); ?></td><td><?php echo number_format($b['pending_total_bs'],2,',','.'); ?></td></tr><?php endforeach; ?></tbody></table></div><div class="card"><h2>Última auditoría</h2><table class="table"><thead><tr><th>Fecha</th><th>Usuario</th><th>Acción</th><th>Persona</th><th>Evento</th><th>Detalle</th></tr></thead><tbody><?php foreach($recentAudit as $a): ?><tr><td><?php echo h($a['fecha_evento']); ?></td><td><?php echo h($a['usuario']); ?></td><td><?php echo h($a['accion']); ?></td><td><?php echo h($a['persona_id']); ?></td><td><?php echo h($a['vacaciones_evento_id']); ?></td><td><?php echo h($a['detalle']); ?></td></tr><?php endforeach; ?></tbody></table></div></div></body></html>
