<?php
/**
 * EgoGraph – installer.php
 * Unified installer (folders, DB, assets, base frontend)
 * PHP 8.0+
 */

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

define('BASE_PATH', __DIR__);

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

if (version_compare(PHP_VERSION, '8.0', '<')) {
    fail("PHP 8.0 or higher required. Current: " . PHP_VERSION);
}

/* ------------------ config form ------------------ */
if (!file_exists(BASE_PATH . '/config.php') && $_SERVER['REQUEST_METHOD'] !== 'POST') {
    ?>
    <!doctype html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>EgoGraph Installer</title>
        <style>
            body{font-family:system-ui;background:#0b0e14;color:#e6e6eb;padding:40px}
            input,button{padding:8px;margin:6px 0;width:280px}
            button{cursor:pointer}
        </style>
    </head>
    <body>
        <h2>EgoGraph – Installer</h2>
        <form method="post">
            <label>DB Host</label><br>
            <input name="db_host" value="localhost"><br>

            <label>DB Name</label><br>
            <input name="db_name" required><br>

            <label>DB User</label><br>
            <input name="db_user" required><br>

            <label>DB Password</label><br>
            <input name="db_pass" type="password"><br><br>

            <button type="submit">Install</button>
        </form>
    </body>
    </html>
    <?php
    exit;
}

/* ------------------ save config ------------------ */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $configData = [
        'host' => $_POST['db_host'] ?? 'localhost',
        'name' => $_POST['db_name'] ?? '',
        'user' => $_POST['db_user'] ?? '',
        'pass' => $_POST['db_pass'] ?? '',
    ];
    file_put_contents(
        BASE_PATH . '/config.php',
        "<?php\nreturn " . var_export($configData, true) . ";\n"
    );
}

$config = require BASE_PATH . '/config.php';

/* ------------------ db connect ------------------ */
try {
    $pdo = new PDO(
        "mysql:host={$config['host']};dbname={$config['name']};charset=utf8mb4",
        $config['user'],
        $config['pass'],
        [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        ]
    );
} catch (Throwable $e) {
    fail("Database connection failed:\n" . $e->getMessage());
}

/* ------------------ folders ------------------ */
$folders = [
    'api',
    'public',
    'assets',
    'assets/css',
    'assets/js',
    'uploads',
    'source-files',
    'storage'
];

foreach ($folders as $folder) {
    $path = BASE_PATH . '/' . $folder;
    if (!is_dir($path) && !mkdir($path, 0775, true)) {
        fail("Failed to create folder: $folder");
    }
}

/* ------------------ database schema ------------------ */
$schema = <<<'SQL'
CREATE TABLE IF NOT EXISTS relationships (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(191) NOT NULL UNIQUE,
    you_followed_at DATETIME NULL,
    they_followed_at DATETIME NULL,
    first_action ENUM('you','them','same') NULL,
    is_mutual TINYINT(1) DEFAULT 0,
    days_to_follow_back INT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS stats_cache (
    id INT PRIMARY KEY,
    data JSON NOT NULL,
    updated_at DATETIME NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
SQL;

try {
    $pdo->exec($schema);
} catch (Throwable $e) {
    fail("Schema creation failed:\n" . $e->getMessage());
}

/* ------------------ CSS ------------------ */
$cssApp = <<<'CSS'
:root{
  --bg:#0b0e14;
  --panel:#121826;
  --text:#e6e6eb;
  --muted:#8b93a7;
  --accent:#4da3ff;
}
*{box-sizing:border-box}
body{
  margin:0;
  font-family:system-ui,-apple-system,Segoe UI,Roboto;
  background:var(--bg);
  color:var(--text);
}
.panel{
  background:var(--panel);
  padding:16px;
  border-radius:10px;
  margin:12px;
}
h1,h2,h3{margin-top:0}
button{
  background:var(--accent);
  color:#000;
  border:0;
  border-radius:6px;
  padding:6px 12px;
  cursor:pointer;
}
input,select{
  background:#0e1320;
  color:var(--text);
  border:1px solid #1e253d;
  padding:6px;
  border-radius:4px;
}
a{color:var(--accent);text-decoration:none}
CSS;

$cssPolish = <<<'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}
CSS;

file_put_contents(BASE_PATH . '/assets/css/app.css', $cssApp);
file_put_contents(BASE_PATH . '/assets/css/polish.css', $cssPolish);

/* ------------------ JS ------------------ */
$jsApp = <<<'JS'
async function api(url){
  const r = await fetch(url);
  if(!r.ok) throw new Error('API error');
  return r.json();
}
function qs(s){return document.querySelector(s);}
function qsa(s){return document.querySelectorAll(s);}
JS;

$jsHelpers = <<<'JS'
function formatDate(d){
  if(!d) return '';
  return new Date(d).toISOString().split('T')[0];
}
JS;

file_put_contents(BASE_PATH . '/assets/js/app.js', $jsApp);
file_put_contents(BASE_PATH . '/assets/js/helpers.js', $jsHelpers);

/* ------------------ base frontend ------------------ */
$index = <<<'HTML'
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>EgoGraph</title>
/assets/css/app.css
/assets/css/polish.css
/assets/js/app.jsscript>
/assets/js/helpers.jsscript>
</head>
<body>
<div class="panel">
  <h2>EgoGraph</h2>
  <p>Installation complete.</p>
  <p>Next: run <strong>upgrader1.php</strong> to import your Instagram data.</p>
</div>
</body>
</html>
HTML;

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

/* ------------------ lock ------------------ */
file_put_contents(BASE_PATH . '/storage/installed_step1', (string)time());

/* ------------------ done ------------------ */
echo "<h2 style='font-family:system-ui'>Installer complete</h2>";
echo "<ul>";
echo "<li>Folders created</li>";
echo "<li>Database schema installed</li>";
echo "<li>Assets written</li>";
echo "</ul>";
echo "<p><strong>Upload and run upgrader1.php next.</strong></p>";