<?php
session_start();

if (file_exists('db/config.php') && !isset($_GET['force'])) {
    // Check if DB is already connected
    require_once 'db/config.php';
    try {
        db();
        die("Application already installed. Delete db/config.php if you want to reinstall.");
    } catch (Exception $e) {
        // Continue to installation
    }
}

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($step == 2) {
        $host = $_POST['db_host'];
        $name = $_POST['db_name'];
        $user = $_POST['db_user'];
        $pass = $_POST['db_pass'];

        try {
            $pdo = new PDO("mysql:host=$host;charset=utf8mb4", $user, $pass, [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
            ]);
            $pdo->exec("CREATE DATABASE IF NOT EXISTS `$name` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
            $pdo->exec("USE `$name`");
            
            // Save config
            $configContent = "<?php\ndefine('DB_HOST', '$host');\ndefine('DB_NAME', '$name');\ndefine('DB_USER', '$user');\ndefine('DB_PASS', '$pass');\n\nfunction db() {\n  static \$pdo;\n  if (!\$pdo) {\n    \$pdo = new PDO('mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=utf8mb4', DB_USER, DB_PASS, [
      PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
      PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]);\n  }\n  return \$pdo;
}\n";
            file_put_contents('db/config.php', $configContent);
            
            $_SESSION['install_pdo'] = ['host' => $host, 'name' => $name, 'user' => $user, 'pass' => $pass];
            header("Location: install.php?step=3");
            exit;
        } catch (PDOException $e) {
            $error = "Database Error: " . $e->getMessage();
        }
    }

    if ($step == 3) {
        require_once 'db/config.php';
        $db = db();
        
        // Import Schema
        $schemaFile = 'full_schema.sql';
        if (file_exists($schemaFile)) {
            $sql = file_get_contents($schemaFile);
            $db->exec($sql);
        } else {
            // Basic tables if full_schema.sql is missing
            $db->exec("CREATE TABLE IF NOT EXISTS users (id INT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(50) UNIQUE, password VARCHAR(255), balance DECIMAL(10,2) DEFAULT 0, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)");
            $db->exec("CREATE TABLE IF NOT EXISTS settings (id INT AUTO_INCREMENT PRIMARY KEY, setting_key VARCHAR(255) UNIQUE, setting_value TEXT)");
            $db->exec("INSERT IGNORE INTO settings (setting_key, setting_value) VALUES ('site_name', 'My APK Store'), ('site_icon', ''), ('site_favicon', '')");
        }

        // Create Admin
        $admin_user = $_POST['admin_user'];
        $admin_pass = password_hash($_POST['admin_pass'], PASSWORD_DEFAULT);
        
        $stmt = $db->prepare("INSERT INTO users (username, password) VALUES (?, ?)");
        $stmt->execute([$admin_user, $admin_pass]);
        
        $success = "Installation complete!";
        $step = 4;
    }
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Installer</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body { background-color: #f4f7f6; }
        .install-box { max-width: 500px; margin: 100px auto; background: #fff; padding: 40px; border-radius: 10px; box-shadow: 0 5px 15px rgba(0,0,0,0.1); }
        .step-indicator { display: flex; justify-content: space-between; margin-bottom: 30px; }
        .step { width: 30px; height: 30px; border-radius: 50%; background: #ddd; text-align: center; line-height: 30px; color: #fff; }
        .step.active { background: #0d6efd; }
    </style>
</head>
<body>

<div class="install-box">
    <h3 class="text-center mb-4">Web Installer</h3>
    
    <div class="step-indicator">
        <div class="step <?php echo $step >= 1 ? 'active' : ''; ">1</div>
        <div class="step <?php echo $step >= 2 ? 'active' : ''; ">2</div>
        <div class="step <?php echo $step >= 3 ? 'active' : ''; ">3</div>
        <div class="step <?php echo $step >= 4 ? 'active' : ''; ">4</div>
    </div>

    <?php if ($error): ?>
        <div class="alert alert-danger"><?php echo $error; ?></div>
    <?php endif; ?>

    <?php if ($step == 1): ?>
        <h5>Welcome</h5>
        <p>This wizard will help you install the application on your server.</p>
        <div class="d-grid">
            <a href="?step=2" class="btn btn-primary">Start Installation</a>
        </div>
    <?php endif; ?>

    <?php if ($step == 2): ?>
        <h5>Database Configuration</h5>
        <form method="POST">
            <div class="mb-3">
                <label>DB Host</label>
                <input type="text" name="db_host" class="form-control" value="localhost" required>
            </div>
            <div class="mb-3">
                <label>DB Name</label>
                <input type="text" name="db_name" class="form-control" required>
            </div>
            <div class="mb-3">
                <label>DB User</label>
                <input type="text" name="db_user" class="form-control" required>
            </div>
            <div class="mb-3">
                <label>DB Password</label>
                <input type="password" name="db_pass" class="form-control">
            </div>
            <div class="d-grid">
                <button type="submit" class="btn btn-primary">Connect & Continue</button>
            </div>
        </form>
    <?php endif; ?>

    <?php if ($step == 3): ?>
        <h5>Admin Account</h5>
        <form method="POST">
            <div class="mb-3">
                <label>Admin Username</label>
                <input type="text" name="admin_user" class="form-control" required>
            </div>
            <div class="mb-3">
                <label>Admin Password</label>
                <input type="password" name="admin_pass" class="form-control" required>
            </div>
            <div class="d-grid">
                <button type="submit" class="btn btn-primary">Finish Installation</button>
            </div>
        </form>
    <?php endif; ?>

    <?php if ($step == 4): ?>
        <div class="text-center">
            <h1 class="text-success"><i class="fas fa-check-circle"></i></h1>
            <h5>Installation Successful!</h5>
            <p>You can now log in to your admin panel.</p>
            <div class="alert alert-warning">
                <strong>Important:</strong> Please delete <code>install.php</code> file from your server.
            </div>
            <div class="d-grid">
                <a href="/admin/login" class="btn btn-primary">Go to Admin Panel</a>
            </div>
        </div>
    <?php endif; ?>
</div>

</body>
</html>
