<?php
/**
 * EgoGraph – upgrader5.php
 * Final fixer + source-files inspector
 * PHP 8.0+
 */

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

define('BASE_PATH', __DIR__);
define('SOURCE_DIR', BASE_PATH . '/source-files');

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

/* ---------- PRECHECK ---------- */
if (!is_dir(BASE_PATH . '/storage')) {
    fail('Storage folder missing.');
}

/* ---------- FRONTEND FIX (rewrite files cleanly) ---------- */

$head =
'/assets/css/app.css' . PHP_EOL .
'/assets/css/polish.css' . PHP_EOL .
'/assets/js/app.jsscript>' . PHP_EOL .
'/assets/js/helpers.jsscript>';

$index =
'<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>EgoGraph – Overview</title>
'.$head.'
</head>
<body>
<div class="panel">
  <h2>EgoGraph – Overview</h2>
  <div id="stats">Loading…</div>
  <p>
    nonfollowers.phpView Non‑Followers</a> |
    autobiography.phpAutobiography</a>
  </p>
</div>

<script>
api("/api/stats.php").then(s=>{
  let h="<ul>";
  for(const k in s){
    h+="<li><strong>"+k+"</strong>: "+s[k]+"</li>";
  }
  h+="</ul>";
  qs("#stats").innerHTML=h;
});
</script>
</body>
</html>';

file_put_contents(BASE_PATH . '/public/index.php', $index);

$nonfollowers =
'<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Non‑Followers</title>
'.$head.'
</head>
<body>
<div class="panel">
  <h2>Accounts Not Following You Back</h2>
  <input id="search" placeholder="Search username">
  <table id="list"></table>
  <p>index.php← Back</a></p>
</div>

<script>
let all=[];
api("/api/nonfollowers.php").then(d=>{ all=d; render(d); });

function render(rows){
  let h="<tr><th>User</th><th>Followed</th><th>Action</th></tr>";
  rows.forEach(r=>{
    h+="<tr>"
      +"<td>@"+r.username+"</td>"
      +"<td>"+(r.you_followed_at||"")+"</td>"
      +"<td><a target=\"_blank\" href=\"https://instagram.com/"+r.username+"\">Profile</a></td>"
      +"</tr>";
  });
  qs("#list").innerHTML=h;
}

qs("#search").oninput=e=>{
  const v=e.target.value.toLowerCase();
  render(all.filter(r=>r.username.toLowerCase().includes(v)));
};
</script>
</body>
</html>';

file_put_contents(BASE_PATH . '/public/nonfollowers.php', $nonfollowers);

$autobio =
'<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Autobiography</title>
'.$head.'
</head>
<body>
<div class="panel">
  <h2>Your Instagram Story</h2>
  <div id="story">Loading…</div>
  <p>index.php← Back</a></p>
</div>

<script>
api("/api/stats.php").then(s=>{
  qs("#story").innerHTML =
    "<p>You follow <strong>"+s.total_following+"</strong> accounts and have <strong>"+s.total_followers+"</strong> followers.</p>"
  + "<p><strong>"+s.mutual+"</strong> are mutual relationships.</p>"
  + "<p><strong>"+s.non_followers+"</strong> never followed you back.</p>"
  + "<p>Average follow‑back time: <strong>"+(s.avg_followback_days ?? "N/A")+"</strong> days.</p>";
});
</script>
</body>
</html>';

file_put_contents(BASE_PATH . '/public/autobiography.php', $autobio);

/* ---------- SOURCE-FILES HELPERS ---------- */

function listFilesRecursive($dir) {
    $out = [];
    if (!is_dir($dir)) return $out;

    $it = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS)
    );
    foreach ($it as $f) {
        $out[] = str_replace(BASE_PATH.'/', '', $f->getPathname());
    }
    return $out;
}

function extractZips($dir) {
    $done = [];
    if (!class_exists('ZipArchive')) return ['ZipArchive not enabled'];

    foreach (glob($dir.'/*.zip') as $zipFile) {
        $zip = new ZipArchive();
        if ($zip->open($zipFile) === true) {
            $zip->extractTo($dir);
            $zip->close();
            $done[] = basename($zipFile);
        }
    }
    return $done;
}

/* ---------- UI ---------- */

$action = $_POST['action'] ?? null;

echo "<h2 style='font-family:system-ui'>Upgrader 5 – Fixer</h2>";
echo "<p><strong>Source directory:</strong> ".htmlspecialchars(SOURCE_DIR)."</p>";

echo '<form method="post" style="margin-bottom:20px">
  <button name="action" value="check">🔍 Check source-files</button>
  <button name="action" value="extract">📦 Extract ZIPs</button>
</form>';

if ($action === 'check') {
    $files = listFilesRecursive(SOURCE_DIR);
    echo "<h3>source-files contents</h3>";
    if (!$files) {
        echo "<p><em>No files found.</em></p>";
    } else {
        echo "<pre>";
        foreach ($files as $f) echo $f.PHP_EOL;
        echo "</pre>";
    }
}

if ($action === 'extract') {
    $z = extractZips(SOURCE_DIR);
    echo "<h3>ZIP extraction</h3><pre>";
    if (!$z) {
        echo "No ZIP files found.";
    } else {
        foreach ($z as $n) echo "Extracted: ".$n.PHP_EOL;
    }
    echo "</pre>";
}

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

echo "<p><strong>Frontend fixed.</strong> Open <code>/public/index.php</code>.</p>";