<?php
/**
 * EgoGraph – upgrader4.php
 * Phase 5 – polish, helpers, installer lock-down, final checks
 * PHP 8.0+
 */

ini_set('display_errors', 1);
error_reporting(E_ALL);

define('BASE_PATH', __DIR__);

function fail($msg) {
    echo "<h2 style='color:red;font-family:system-ui'>Upgrader failed</h2>";
    echo "<pre>" . htmlspecialchars($msg) . "</pre>";
    exit;
}

/* ---------- PRECHECK ---------- */
if (!file_exists(BASE_PATH . '/storage/installed_step4')) {
    fail('upgrader3.php has not been run.');
}

/* ---------- HARDEN ASSETS ---------- */

/* extra JS helpers */
file_put_contents(
    BASE_PATH . '/assets/js/helpers.js',
<<<'JS'
function formatDate(d){
  if(!d) return '';
  return new Date(d).toISOString().split('T')[0];
}
function debounce(fn,ms){
  let t; return (...a)=>{
    clearTimeout(t); t=setTimeout(()=>fn(...a),ms);
  };
}
JS
);

/* enhanced CSS polish */
file_put_contents(
    BASE_PATH . '/assets/css/polish.css',
<<<'CSS'
table{width:100%;border-collapse:collapse;margin-top:12px}
th,td{padding:8px;border-bottom:1px solid #1e253d;text-align:left}
th{color:#8b93a7;font-weight:600}
tr:hover{background:#0e1320}
.badge{padding:2px 6px;border-radius:4px;font-size:12px}
.badge.mutual{background:#4da3ff;color:#000}
.badge.ghost{background:#ff4d4d;color:#000}
CSS
);

/* ---------- UPDATE INDEX TO LOAD POLISH ---------- */
$indexPath = BASE_PATH . '/public/index.php';
$index = file_get_contents($indexPath);

if ($index !== false) {
    $index = str_replace(
        '</head>',
        '/assets/css/polish.css
/assets/js/helpers.jsscript>
</head>',
        $index
    );
    file_put_contents($indexPath, $index);
}

/* ---------- INSTALLER LOCKDOWN ---------- */
$lockMsg = <<<'PHP'
<?php
http_response_code(403);
echo "Installer disabled.";
exit;
PHP;

file_put_contents(BASE_PATH . '/installer.php', $lockMsg);
file_put_contents(BASE_PATH . '/upgrader1.php', $lockMsg);
file_put_contents(BASE_PATH . '/upgrader2.php', $lockMsg);
file_put_contents(BASE_PATH . '/upgrader3.php', $lockMsg);

/* ---------- OPTIONAL .HTACCESS ---------- */
$htaccess = <<<'HT'
Options -Indexes
<FilesMatch "(config\.php|\.lock)">
  Require all denied
</FilesMatch>
HT;

file_put_contents(BASE_PATH . '/.htaccess', $htaccess);

/* ---------- FINAL LOCK ---------- */
file_put_contents(BASE_PATH . '/storage/installed_step5', time());

echo "<h2 style='font-family:system-ui'>EgoGraph installation complete</h2>";
echo "<p>✅ All phases installed</p>";
echo "<p>✅ Installers locked</p>";
echo "<p>✅ System ready</p>";
echo "<p><strong>Open /public/index.php to begin</strong></p>";