<?php
/**
 * TOPBD — 1-Click Automated Installer Wizard
 * Works out-of-the-box on Hostinger, cPanel, and Apache PHP 8+
 */

session_start();

$step = $_GET['step'] ?? 'form';
$error = '';
$success = '';

if ($step === 'process' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $dbHost = trim($_POST['db_host'] ?? 'localhost');
    $dbName = trim($_POST['db_name'] ?? '');
    $dbUser = trim($_POST['db_user'] ?? '');
    $dbPass = $_POST['db_pass'] ?? '';
    $tablePrefix = trim($_POST['table_prefix'] ?? 'topbd_');

    $adminUser = trim($_POST['admin_user'] ?? 'admin');
    $adminEmail = trim($_POST['admin_email'] ?? 'admin@topbd.app');
    $adminPass = $_POST['admin_pass'] ?? '';
    $siteUrl = rtrim(trim($_POST['site_url'] ?? 'http://' . $_SERVER['HTTP_HOST']), '/');

    if (empty($dbName) || empty($dbUser) || empty($adminUser) || empty($adminPass)) {
        $error = "Please fill in all required fields.";
    } else {
        try {
            // 1. Test PDO Connection
            $dsn = "mysql:host={$dbHost};dbname={$dbName};charset=utf8mb4";
            $pdo = new PDO($dsn, $dbUser, $dbPass, [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4"
            ]);

            // 2. Execute Database Schema
            $schemaSql = file_get_contents(__DIR__ . '/database/schema.sql');
            if ($schemaSql) {
                $pdo->exec($schemaSql);
            }

            // 3. Execute Database Seed Data
            $seedSql = file_get_contents(__DIR__ . '/database/seed.sql');
            if ($seedSql) {
                $pdo->exec($seedSql);
            }

            // 4. Create Admin Account
            $hash = password_hash($adminPass, PASSWORD_DEFAULT);
            $checkAdmin = $pdo->prepare("SELECT id FROM admins WHERE username = ?");
            $checkAdmin->execute([$adminUser]);
            if ($checkAdmin->fetch()) {
                $updAdmin = $pdo->prepare("UPDATE admins SET email = ?, password_hash = ? WHERE username = ?");
                $updAdmin->execute([$adminEmail, $hash, $adminUser]);
            } else {
                $insAdmin = $pdo->prepare("INSERT INTO admins (username, email, password_hash, role, created_at) VALUES (?, ?, ?, 'admin', NOW())");
                $insAdmin->execute([$adminUser, $adminEmail, $hash]);
            }

            // 5. Update Site URL in settings
            $updUrl = $pdo->prepare("UPDATE settings SET setting_value = ? WHERE setting_key = 'site_url'");
            $updUrl->execute([$siteUrl]);

            // 6. Create uploads directory and security .htaccess
            $uploadDir = __DIR__ . '/uploads';
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0755, true);
            }
            file_put_contents($uploadDir . '/.htaccess', "# Disable PHP execution in uploads\n<FilesMatch \"\.(php|php5|php7|php8|phtml|phar)$\">\nOrder Deny,Allow\nDeny from all\n</FilesMatch>\n");

            // 7. Write config.php
            $configContent = "<?php\n" .
                "/**\n * TOPBD — Application Configuration\n */\n\n" .
                "define('DB_HOST', '" . addslashes($dbHost) . "');\n" .
                "define('DB_NAME', '" . addslashes($dbName) . "');\n" .
                "define('DB_USER', '" . addslashes($dbUser) . "');\n" .
                "define('DB_PASS', '" . addslashes($dbPass) . "');\n" .
                "define('DB_PREFIX', '" . addslashes($tablePrefix) . "');\n\n" .
                "define('APP_URL', '" . addslashes($siteUrl) . "');\n" .
                "define('APP_KEY', 'sec_" . bin2hex(random_bytes(16)) . "');\n" .
                "define('SESSION_LIFETIME', 86400);\n" .
                "define('ENVIRONMENT', 'production');\n" .
                "date_default_timezone_set('Asia/Dhaka');\n\n" .
                "error_reporting(0);\n" .
                "ini_set('display_errors', '0');\n";

            file_put_contents(__DIR__ . '/config.php', $configContent);

            $step = 'success';
        } catch (PDOException $e) {
            $error = "Database Connection Failed: " . $e->getMessage();
        } catch (Exception $e) {
            $error = "Installation Error: " . $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TOPBD Installer Wizard</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        body { background-color: #0A0D0F; color: #F0F4F8; font-family: system-ui, -apple-system, sans-serif; }
    </style>
</head>
<body class="min-h-screen flex items-center justify-center p-4">
    <div class="max-w-xl w-full rounded-2xl bg-[#13181D] border border-[#222A33] p-6 sm:p-8 shadow-2xl space-y-6">
        <!-- Logo & Header -->
        <div class="flex items-center gap-3 border-b border-[#222A33] pb-4">
            <div class="w-10 h-10 rounded-xl bg-emerald-600 flex items-center justify-center text-white font-bold font-mono">
                BD
            </div>
            <div>
                <h1 class="text-xl font-bold font-mono text-white">TOPBD Installer</h1>
                <p class="text-xs text-slate-400">Hostinger & cPanel 1-Click Automated Setup</p>
            </div>
        </div>

        <?php if ($error): ?>
            <div class="p-3.5 rounded-xl bg-rose-950/50 border border-rose-800/60 text-rose-300 text-xs">
                <?= htmlspecialchars($error) ?>
            </div>
        <?php endif; ?>

        <?php if ($step === 'success'): ?>
            <div class="text-center space-y-4 py-4">
                <div class="w-16 h-16 rounded-full bg-emerald-500/20 text-emerald-400 flex items-center justify-center mx-auto text-2xl">
                    ✓
                </div>
                <h2 class="text-2xl font-bold text-white font-mono">Installation Successful!</h2>
                <p class="text-xs text-slate-300 max-w-md mx-auto">
                    Database tables created, default Bangladesh categories seeded, and config.php written successfully.
                </p>
                <div class="pt-4 flex flex-col sm:flex-row gap-3 justify-center">
                    <a href="/" class="px-6 py-2.5 rounded-xl bg-emerald-600 hover:bg-emerald-500 text-white font-bold text-xs shadow-lg">
                        Go to Homepage
                    </a>
                    <a href="/admin/login.php" class="px-6 py-2.5 rounded-xl bg-[#1A222A] hover:bg-[#222D38] border border-[#2A3744] text-white font-bold text-xs">
                        Admin Login
                    </a>
                </div>
                <p class="text-[11px] text-amber-400 mt-2">
                    Tip: For production security, delete or rename <code class="font-mono">installer.php</code>.
                </p>
            </div>
        <?php else: ?>
            <form action="installer.php?step=process" method="POST" class="space-y-5 text-xs">
                <!-- Database Config Section -->
                <div className="space-y-3">
                    <h3 class="text-xs font-bold text-emerald-400 uppercase tracking-wider font-mono">1. MySQL Database Settings</h3>
                    <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
                        <div>
                            <label class="block text-slate-300 font-semibold mb-1">Database Host</label>
                            <input type="text" name="db_host" value="localhost" required class="w-full px-3 py-2 bg-[#0A0D0F] border border-[#222A33] rounded-xl text-white focus:outline-none focus:border-emerald-500 font-mono" />
                        </div>
                        <div>
                            <label class="block text-slate-300 font-semibold mb-1">Database Name</label>
                            <input type="text" name="db_name" placeholder="cpanel_topbd" required class="w-full px-3 py-2 bg-[#0A0D0F] border border-[#222A33] rounded-xl text-white focus:outline-none focus:border-emerald-500 font-mono" />
                        </div>
                        <div>
                            <label class="block text-slate-300 font-semibold mb-1">Database Username</label>
                            <input type="text" name="db_user" placeholder="cpanel_user" required class="w-full px-3 py-2 bg-[#0A0D0F] border border-[#222A33] rounded-xl text-white focus:outline-none focus:border-emerald-500 font-mono" />
                        </div>
                        <div>
                            <label class="block text-slate-300 font-semibold mb-1">Database Password</label>
                            <input type="password" name="db_pass" placeholder="••••••••" class="w-full px-3 py-2 bg-[#0A0D0F] border border-[#222A33] rounded-xl text-white focus:outline-none focus:border-emerald-500 font-mono" />
                        </div>
                    </div>
                </div>

                <!-- Admin Account Section -->
                <div className="space-y-3 pt-3 border-t border-[#222A33]">
                    <h3 class="text-xs font-bold text-emerald-400 uppercase tracking-wider font-mono">2. Administrator Credentials</h3>
                    <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
                        <div>
                            <label class="block text-slate-300 font-semibold mb-1">Admin Username</label>
                            <input type="text" name="admin_user" value="admin" required class="w-full px-3 py-2 bg-[#0A0D0F] border border-[#222A33] rounded-xl text-white focus:outline-none focus:border-emerald-500 font-mono" />
                        </div>
                        <div>
                            <label class="block text-slate-300 font-semibold mb-1">Admin Email</label>
                            <input type="email" name="admin_email" value="admin@topbd.app" required class="w-full px-3 py-2 bg-[#0A0D0F] border border-[#222A33] rounded-xl text-white focus:outline-none focus:border-emerald-500" />
                        </div>
                        <div class="sm:col-span-2">
                            <label class="block text-slate-300 font-semibold mb-1">Admin Password</label>
                            <input type="password" name="admin_pass" value="admin123" required class="w-full px-3 py-2 bg-[#0A0D0F] border border-[#222A33] rounded-xl text-white focus:outline-none focus:border-emerald-500 font-mono" />
                        </div>
                    </div>
                </div>

                <!-- Site URL -->
                <div class="pt-3 border-t border-[#222A33]">
                    <label class="block text-slate-300 font-semibold mb-1">Application URL (No trailing slash)</label>
                    <input type="url" name="site_url" value="http://<?= $_SERVER['HTTP_HOST'] ?? 'localhost' ?>" required class="w-full px-3 py-2 bg-[#0A0D0F] border border-[#222A33] rounded-xl text-white focus:outline-none focus:border-emerald-500 font-mono" />
                </div>

                <button type="submit" class="w-full py-3 rounded-xl bg-gradient-to-r from-emerald-600 to-teal-600 hover:from-emerald-500 hover:to-teal-500 text-white font-bold text-sm shadow-xl transition-all cursor-pointer">
                    Install TOPBD Database & Complete Setup
                </button>
            </form>
        <?php endif; ?>
    </div>
</body>
</html>
