<?php
include('conexion.php');
if (session_status() !== PHP_SESSION_ACTIVE) { session_start(); }
if (!isset($_SESSION['usuario'])) { header('Location: login.php'); exit; }

$resetMsg = '';
if (isset($_GET['reset_opcache']) && $_GET['reset_opcache'] === '1') {
    if (function_exists('opcache_reset')) {
        $ok = @opcache_reset();
        $resetMsg = $ok ? 'OPcache reiniciado correctamente.' : 'Se intentó reiniciar OPcache, pero PHP no confirmó éxito.';
    } else {
        $resetMsg = 'OPcache no está disponible o la función opcache_reset() está deshabilitada.';
    }
}

function ndc_h($s) { return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
function ndc_scan_file($file) {
    $txt = @file_get_contents($file);
    if ($txt === false) { return []; }
    $bad = [];
    $lines = preg_split('/\R/', $txt);
    foreach ($lines as $i => $line) {
        // Patrón literal usado por la variante no compatible del UPSERT moderno.
        if (preg_match('/AS\s+nuevo/i', $line) || preg_match('/ON\s+DUPLICATE\s+KEY\s+UPDATE/i', $line)) {
            $bad[] = ['line' => $i + 1, 'text' => trim($line)];
        }
    }
    return $bad;
}

$root = __DIR__;
$mainFiles = [
    'novedades_periodo.php',
    'nomina_legal_master.php',
    'nomina_calcular_actualizado.php',
    'nomina_parametros_legales.php',
    'nomina_helpers.php',
    'nomina_corrida_resumen.php',
    'nomina_auditoria_corrida.php',
    'nomina_reversos_ajustes.php',
    'nomina_recibo.php',
    'nomina_recibos_lote.php',
    'index.php',
    'conceptos_nomina.php',
    'login.php',
];
$scanRows = [];
foreach ($mainFiles as $f) {
    $path = $root . DIRECTORY_SEPARATOR . $f;
    $exists = is_file($path);
    $scanRows[] = [
        'file' => $f,
        'exists' => $exists,
        'mtime' => $exists ? date('Y-m-d H:i:s', filemtime($path)) : '',
        'sha1' => $exists ? sha1_file($path) : '',
        'bad' => $exists ? ndc_scan_file($path) : [],
    ];
}

$allPhpBad = [];
foreach (glob($root . DIRECTORY_SEPARATOR . '*.php') ?: [] as $path) {
    $bad = ndc_scan_file($path);
    if ($bad) { $allPhpBad[basename($path)] = $bad; }
}

$schema = [];
$res = @mysqli_query($conexion, "SHOW COLUMNS FROM novedades_periodo");
if ($res) { while ($r = mysqli_fetch_assoc($res)) { $schema[] = $r['Field']; } }
$opcacheEnabled = function_exists('opcache_get_status') ? @opcache_get_status(false) : null;
?>
<!doctype html>
<html lang="es">
<head><meta charset="utf-8"><title>Diagnóstico compatibilidad nómina</title><meta name="viewport" content="width=device-width, initial-scale=1">
<style>body{font-family:Arial,sans-serif;background:#f5f7fa;color:#24364b;margin:0}.container{max-width:1200px;margin:24px auto;padding:0 16px}.card{background:#fff;border:1px solid #e5e7eb;border-radius:14px;padding:16px;margin:14px 0;box-shadow:0 8px 24px rgba(16,24,40,.06)}.ok{color:#166534}.bad{color:#be123c}.muted{color:#6b7280;font-size:12px}.btn{display:inline-block;padding:10px 14px;background:#1a3c8b;color:#fff;border-radius:10px;text-decoration:none;font-weight:700}.btn.secondary{background:#fff;color:#1a3c8b;border:1px solid rgba(26,60,139,.25)}table{width:100%;border-collapse:collapse}td,th{border-bottom:1px solid #eef2f7;padding:8px;text-align:left;vertical-align:top;font-size:13px}th{background:#fafafa}code{background:#f3f4f6;padding:2px 4px;border-radius:4px}</style></head>
<body><div class="container">
  <div class="card"><h2>Diagnóstico de compatibilidad Nómina v6.5</h2><p class="muted">Verifica si el servidor todavía contiene consultas UPSERT incompatibles con MariaDB y confirma qué archivos principales están siendo leídos desde esta carpeta.</p><p><a class="btn secondary" href="index.php">Volver al inicio</a> <a class="btn" href="nomina_diagnostico_compatibilidad.php?reset_opcache=1">Reiniciar OPcache</a></p><?php if($resetMsg): ?><p class="ok"><strong><?php echo ndc_h($resetMsg); ?></strong></p><?php endif; ?></div>

  <div class="card"><h3>Archivos principales</h3><table><thead><tr><th>Archivo</th><th>Existe</th><th>Modificado</th><th>SHA1</th><th>Patrones incompatibles</th></tr></thead><tbody><?php foreach($scanRows as $r): ?><tr><td><strong><?php echo ndc_h($r['file']); ?></strong></td><td><?php echo $r['exists'] ? '<span class="ok">Sí</span>' : '<span class="bad">No</span>'; ?></td><td><?php echo ndc_h($r['mtime']); ?></td><td><code><?php echo ndc_h(substr($r['sha1'],0,16)); ?></code></td><td><?php if(!$r['bad']): ?><span class="ok">Sin patrones detectados</span><?php else: ?><span class="bad">Revisar:</span><ul><?php foreach($r['bad'] as $b): ?><li>L<?php echo (int)$b['line']; ?>: <code><?php echo ndc_h($b['text']); ?></code></li><?php endforeach; ?></ul><?php endif; ?></td></tr><?php endforeach; ?></tbody></table></div>

  <div class="card"><h3>Escaneo de PHP en raíz</h3><?php if(!$allPhpBad): ?><p class="ok"><strong>No se detectaron patrones incompatibles en los PHP de la raíz.</strong></p><?php else: ?><p class="bad"><strong>Se detectaron patrones incompatibles:</strong></p><?php foreach($allPhpBad as $file=>$bad): ?><h4><?php echo ndc_h($file); ?></h4><ul><?php foreach($bad as $b): ?><li>L<?php echo (int)$b['line']; ?>: <code><?php echo ndc_h($b['text']); ?></code></li><?php endforeach; ?></ul><?php endforeach; ?><?php endif; ?></div>

  <div class="card"><h3>Tabla novedades_periodo</h3><p class="muted">Columnas detectadas:</p><p><?php echo ndc_h(implode(', ', $schema)); ?></p></div>

  <div class="card"><h3>OPcache</h3><?php if(is_array($opcacheEnabled)): ?><p>OPcache habilitado: <strong><?php echo !empty($opcacheEnabled['opcache_enabled']) ? 'Sí' : 'No'; ?></strong></p><?php else: ?><p class="muted">No se pudo consultar OPcache.</p><?php endif; ?></div>
</div></body></html>
