<?php
declare(strict_types=1);

const ROOT = __DIR__ . '/..';
if (is_file(ROOT . '/config.php')) {
    $cfg = require ROOT . '/config.php';
    if (!empty($cfg['installed'])) {
        header('Location: ' . rtrim($cfg['app_url'], '/') . '/admin/');
        exit;
    }
}

session_name('gamesji_installer');
session_start();
if (empty($_SESSION['_install_csrf'])) {
    $_SESSION['_install_csrf'] = bin2hex(random_bytes(24));
}

$checks = [
    'PHP 8.2 or newer' => version_compare(PHP_VERSION, '8.2.0', '>='),
    'PDO MySQL extension' => extension_loaded('pdo_mysql'),
    'cURL or URL fopen' => extension_loaded('curl') || (bool)ini_get('allow_url_fopen'),
    'JSON extension' => extension_loaded('json'),
    'Mbstring extension' => extension_loaded('mbstring'),
    'Root directory writable' => is_writable(ROOT),
    'Storage directory writable' => is_dir(ROOT . '/storage') && is_writable(ROOT . '/storage'),
];
$errors = [];
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!hash_equals($_SESSION['_install_csrf'], (string)($_POST['_csrf'] ?? ''))) {
        $errors[] = 'Installer session expired. Reload and try again.';
    }
    foreach ($checks as $label => $ok) {
        if (!$ok) {
            $errors[] = $label . ' check failed.';
        }
    }
    $appUrl = rtrim(trim((string)($_POST['app_url'] ?? '')), '/');
    $dbHost = trim((string)($_POST['db_host'] ?? 'localhost'));
    $dbPort = (int)($_POST['db_port'] ?? 3306);
    $dbName = trim((string)($_POST['db_name'] ?? ''));
    $dbUser = trim((string)($_POST['db_user'] ?? ''));
    $dbPass = (string)($_POST['db_pass'] ?? '');
    $adminName = trim((string)($_POST['admin_name'] ?? 'Administrator'));
    $adminEmail = strtolower(trim((string)($_POST['admin_email'] ?? '')));
    $adminPassword = (string)($_POST['admin_password'] ?? '');
    if (!filter_var($appUrl, FILTER_VALIDATE_URL) || parse_url($appUrl, PHP_URL_SCHEME) !== 'https') {
        $errors[] = 'Enter the final HTTPS app URL, for example https://gamesji.com/app.';
    }
    if ($dbName === '' || $dbUser === '') {
        $errors[] = 'Database name and user are required.';
    }
    if (!filter_var($adminEmail, FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'Enter a valid admin email.';
    }
    if (strlen($adminPassword) < 12) {
        $errors[] = 'Admin password must contain at least 12 characters.';
    }
    if (!$errors) {
        try {
            $pdo = new PDO(
                "mysql:host={$dbHost};port={$dbPort};dbname={$dbName};charset=utf8mb4",
                $dbUser,
                $dbPass,
                [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_EMULATE_PREPARES => false]
            );
            $schema = file_get_contents(ROOT . '/database.sql');
            if ($schema === false) {
                throw new RuntimeException('database.sql could not be read.');
            }
            foreach (preg_split('/;\s*(?:\r?\n|$)/', $schema) ?: [] as $statement) {
                $statement = trim($statement);
                if ($statement !== '') {
                    $pdo->exec($statement);
                }
            }
            $stmt = $pdo->prepare('INSERT INTO admins (name,email,password_hash,created_at,updated_at) VALUES (?,?,?,NOW(),NOW()) ON DUPLICATE KEY UPDATE name=VALUES(name),password_hash=VALUES(password_hash),failed_attempts=0,locked_until=NULL,updated_at=NOW()');
            $stmt->execute([$adminName, $adminEmail, password_hash($adminPassword, PASSWORD_DEFAULT)]);
            $pdo->prepare("UPDATE settings SET setting_value=? WHERE setting_key='contact_email'")->execute([$adminEmail]);
            $pdo->prepare("UPDATE settings SET setting_value=? WHERE setting_key='privacy_salt'")->execute([bin2hex(random_bytes(20))]);
            $config = [
                'installed' => true,
                'app_url' => $appUrl,
                'timezone' => 'Asia/Kolkata',
                'app_key' => bin2hex(random_bytes(32)),
                'db' => ['host' => $dbHost, 'port' => $dbPort, 'name' => $dbName, 'user' => $dbUser, 'pass' => $dbPass, 'charset' => 'utf8mb4'],
                'cron_token' => bin2hex(random_bytes(32)),
            ];
            $contents = "<?php\ndeclare(strict_types=1);\n\nreturn " . var_export($config, true) . ";\n";
            if (file_put_contents(ROOT . '/config.php', $contents, LOCK_EX) === false) {
                throw new RuntimeException('Could not write config.php. Temporarily set the app folder permission to 755 or 775.');
            }
            @chmod(ROOT . '/config.php', 0640);
            file_put_contents(ROOT . '/storage/install.lock', date('c'), LOCK_EX);
            $success = 'Installation completed. You can now open the admin panel.';
        } catch (Throwable $e) {
            $errors[] = 'Installation failed: ' . $e->getMessage();
        }
    }
}

$detectedScheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$detectedHost = $_SERVER['HTTP_HOST'] ?? 'gamesji.com';
$scriptDir = preg_replace('~/install/?$~', '', dirname($_SERVER['SCRIPT_NAME'] ?? '/app/install/'));
$detectedUrl = $detectedScheme . '://' . $detectedHost . rtrim((string)$scriptDir, '/');
?><!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Install GamesJi Apps</title><link rel="stylesheet" href="../assets/app.css"></head>
<body><main class="installer">
<div class="panel"><img src="../assets/icon.svg" width="64" height="64" alt=""><h1>Install GamesJi Apps</h1><p>Shared-cPanel setup wizard</p></div>
<?php foreach ($errors as $error): ?><div class="alert error"><?= htmlspecialchars($error, ENT_QUOTES) ?></div><?php endforeach; ?>
<?php if ($success): ?><div class="alert success"><?= htmlspecialchars($success, ENT_QUOTES) ?> <a href="../admin/">Open admin</a></div><?php else: ?>
<div class="panel"><h2>Server check</h2><ul class="check-list"><?php foreach ($checks as $label => $ok): ?><li class="<?= $ok ? 'pass' : 'fail' ?>"><?= $ok ? '✓' : '✕' ?> <?= htmlspecialchars($label, ENT_QUOTES) ?></li><?php endforeach; ?></ul></div>
<form class="panel form-grid" method="post" autocomplete="off">
<input type="hidden" name="_csrf" value="<?= htmlspecialchars($_SESSION['_install_csrf'], ENT_QUOTES) ?>">
<h2>Website</h2>
<label>Final app URL<input type="url" name="app_url" value="<?= htmlspecialchars($_POST['app_url'] ?? $detectedUrl, ENT_QUOTES) ?>" required></label>
<h2>MySQL database</h2>
<label>Database host<input name="db_host" value="<?= htmlspecialchars($_POST['db_host'] ?? 'localhost', ENT_QUOTES) ?>" required></label>
<label>Port<input type="number" name="db_port" value="<?= htmlspecialchars($_POST['db_port'] ?? '3306', ENT_QUOTES) ?>" required></label>
<label>Database name<input name="db_name" value="<?= htmlspecialchars($_POST['db_name'] ?? '', ENT_QUOTES) ?>" required></label>
<label>Database user<input name="db_user" value="<?= htmlspecialchars($_POST['db_user'] ?? '', ENT_QUOTES) ?>" required></label>
<label>Database password<input type="password" name="db_pass" required></label>
<h2>Administrator</h2>
<label>Name<input name="admin_name" value="<?= htmlspecialchars($_POST['admin_name'] ?? 'Yogesh', ENT_QUOTES) ?>" required></label>
<label>Email<input type="email" name="admin_email" value="<?= htmlspecialchars($_POST['admin_email'] ?? '', ENT_QUOTES) ?>" required></label>
<label>Strong password<input type="password" name="admin_password" minlength="12" required><small>At least 12 characters.</small></label>
<button class="primary" type="submit">Install website</button>
</form>
<?php endif; ?></main></body></html>
