<?php
/**
 * SonicPesa - Professional System Installer
 * Upload this file to your shared hosting and visit it in the browser.
 * It will guide you through database setup, table creation, admin account, and .htaccess generation.
 * DELETE THIS FILE AFTER INSTALLATION FOR SECURITY.
 */

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

$error = '';
$success = '';
$step = isset($_GET['step']) ? (int)$_GET['step'] : 1;

// If config.php already exists and has valid DB credentials, skip to step check
$config_exists = file_exists(__DIR__ . '/config.php');

// ==================== SQL SCHEMA ====================
$sql_schema = "
-- Users table
CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `phone` varchar(20) DEFAULT NULL,
  `password` varchar(255) NOT NULL,
  `api_key` varchar(255) DEFAULT NULL,
  `api_secret` varchar(255) DEFAULT NULL,
  `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
  `role` enum('user','admin') DEFAULT 'user',
  `landing_page` varchar(50) DEFAULT 'landing1',
  `redirect_url` varchar(255) DEFAULT '',
  `webhook_token` varchar(64) DEFAULT NULL,
  `profile_pic` varchar(500) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Videos table
CREATE TABLE IF NOT EXISTS `videos` (
  `id` varchar(50) NOT NULL,
  `position` int(11) DEFAULT NULL,
  `user_id` int(11) NOT NULL,
  `title` varchar(255) NOT NULL,
  `description` text DEFAULT NULL,
  `price` decimal(10,2) NOT NULL DEFAULT 0.00,
  `video_url` varchar(255) DEFAULT NULL,
  `thumbnail_url` varchar(255) DEFAULT NULL,
  `views` int(11) DEFAULT 0,
  `status` enum('active','inactive') DEFAULT 'active',
  `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
  `fake_views` int(11) DEFAULT 0,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- User domains / landing page links
CREATE TABLE IF NOT EXISTS `user_domains` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `domain_name` varchar(255) NOT NULL,
  `status` enum('active','pending') DEFAULT 'active',
  `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Link analytics
CREATE TABLE IF NOT EXISTS `link_analytics` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `domain_id` int(11) NOT NULL,
  `ip_address` varchar(45) DEFAULT NULL,
  `user_agent` text DEFAULT NULL,
  `isp` varchar(255) DEFAULT NULL,
  `region` varchar(255) DEFAULT NULL,
  `device` varchar(50) DEFAULT NULL,
  `event_type` enum('view','click') DEFAULT 'view',
  `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Site settings
CREATE TABLE IF NOT EXISTS `site_settings` (
  `id` int(11) NOT NULL DEFAULT 1,
  `site_name` varchar(255) DEFAULT 'SonicPesa',
  `site_logo` varchar(500) DEFAULT 'assets/images/logo.png',
  `site_favicon` varchar(500) DEFAULT 'assets/images/favicon.png',
  `landing_title` varchar(100) DEFAULT 'UTAMU',
  `footer_copy` varchar(100) DEFAULT 'SonicPesa Dashboard. All Rights Reserved.',
  `footer_made_by` varchar(100) DEFAULT 'SonicPesa Dev',
  `allow_registration` tinyint(1) DEFAULT 1,
  `allow_uploads` tinyint(1) DEFAULT 1,
  `allow_withdrawals` tinyint(1) DEFAULT 1,
  `system_commission` decimal(5,2) DEFAULT 0.00,
  `min_withdrawal` decimal(10,2) DEFAULT 1000.00,
  `system_notification` text DEFAULT NULL,
  `payment_api_url` varchar(255) DEFAULT NULL,
  `payment_api_public_key` varchar(255) DEFAULT NULL,
  `updated_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- System notifications
CREATE TABLE IF NOT EXISTS `system_notifications` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `message` text NOT NULL,
  `is_active` tinyint(1) DEFAULT 1,
  `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- System root domains for subdomain support
CREATE TABLE IF NOT EXISTS `system_root_domains` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) DEFAULT NULL,
  `domain_name` varchar(255) NOT NULL,
  `is_active` tinyint(4) DEFAULT 1,
  `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
  PRIMARY KEY (`id`),
  UNIQUE KEY `domain_name` (`domain_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Templates registry
CREATE TABLE IF NOT EXISTS `templates` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `slug` varchar(100) NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
  PRIMARY KEY (`id`),
  UNIQUE KEY `slug` (`slug`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Transactions
CREATE TABLE IF NOT EXISTS `transactions` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `tran_id` varchar(100) DEFAULT NULL,
  `video_id` varchar(50) NOT NULL,
  `phone_number` varchar(20) NOT NULL,
  `amount` decimal(10,2) NOT NULL,
  `method` varchar(50) DEFAULT 'Mobile Money',
  `status` enum('pending','completed','failed','cancelled','expired') DEFAULT 'pending',
  `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
  PRIMARY KEY (`id`),
  UNIQUE KEY `tran_id` (`tran_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Withdrawals
CREATE TABLE IF NOT EXISTS `withdrawals` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `withdrawal_id` varchar(50) DEFAULT NULL,
  `user_id` int(11) NOT NULL,
  `amount` decimal(10,2) NOT NULL,
  `method` varchar(50) DEFAULT NULL,
  `network_or_bank` varchar(100) DEFAULT NULL,
  `mobile_or_account` varchar(100) DEFAULT NULL,
  `account_holder_name` varchar(100) DEFAULT NULL,
  `status` enum('pending','completed','cancelled') DEFAULT 'pending',
  `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Admin logs
CREATE TABLE IF NOT EXISTS `admin_logs` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `admin_id` int(11) NOT NULL,
  `action` varchar(255) NOT NULL,
  `target_id` int(11) DEFAULT NULL,
  `details` text DEFAULT NULL,
  `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Tutorials table
CREATE TABLE IF NOT EXISTS `tutorials` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(255) NOT NULL,
  `description` text DEFAULT NULL,
  `video_url` varchar(255) DEFAULT NULL,
  `thumbnail_url` varchar(255) DEFAULT NULL,
  `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
";

// ==================== HANDLE POST ====================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // ---------- STEP 1: Database Config ----------
    if ($step === 1) {
        $db_host = trim($_POST['db_host'] ?? 'localhost');
        $db_name = trim($_POST['db_name'] ?? '');
        $db_user = trim($_POST['db_user'] ?? '');
        $db_pass = $_POST['db_pass'] ?? '';

        if (empty($db_name) || empty($db_user)) {
            $error = "Database name and username are required.";
        } else {
            try {
                $test_pdo = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass);
                $test_pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

                // Generate config.php with dynamic SITE_URL
                $config = <<<PHP
<?php
// config.php - Generated by SonicPesa Installer
session_start();
date_default_timezone_set('Africa/Dar_es_Salaam');

define('DB_HOST', '$db_host');
define('DB_USER', '$db_user');
define('DB_PASS', '$db_pass');
define('DB_NAME', '$db_name');

// Dynamic SITE_URL Detection - works on any hosting
\$protocol = (isset(\$_SERVER['HTTPS']) && \$_SERVER['HTTPS'] === 'on') ? "https" : "http";
\$host = \$_SERVER['HTTP_HOST'] ?? 'localhost';

// Normalize path separators to forward slashes
\$doc_root = str_replace('\\\\', '/', \$_SERVER['DOCUMENT_ROOT'] ?? '');
\$dir = str_replace('\\\\', '/', __DIR__);

// Calculate the relative web path securely
\$base_dir = '';
if (\$doc_root && stripos(\$dir, \$doc_root) === 0) {
    \$base_dir = substr(\$dir, strlen(\$doc_root));
} else {
    // Fallback if __DIR__ isn't inside DOCUMENT_ROOT (rare aliases or CLI)
    \$script_name = \$_SERVER['SCRIPT_NAME'] ?? '';
    \$dirname = str_replace('\\\\', '/', dirname(\$script_name));
    
    // If Apache Windows mod_rewrite leaks the physical path into SCRIPT_NAME (e.g. C:/ or /C:/)
    if (preg_match('~^/?[a-zA-Z]:~', \$dirname) || \$dirname === '.') {
        \$folderName = basename(__DIR__);
        \$reqUri = \$_SERVER['REQUEST_URI'] ?? '';
        // See if the folder name is actually part of the requested URL (meaning it's in a subfolder)
        if (preg_match('~^/(' . preg_quote(\$folderName, '~') . ')(/|$)~i', \$reqUri)) {
            \$base_dir = '/' . \$folderName;
        } else {
            \$base_dir = ''; // Assume it's hosted at the root domain
        }
    } else {
        \$base_dir = \$dirname;
    }
}

// Guarantee format
\$base_dir = '/' . ltrim(\$base_dir, '/');
\$detected_url = "\$protocol://\$host" . rtrim(\$base_dir, '/');
define('SITE_URL', \$detected_url);

// SonicPesa API
define('SONICPESA_API_URL', 'https://api.sonicpesa.com/api/v1');
define('SONICPESA_API_TOKEN', 'YOUR_SONICPESA_API_TOKEN');
define('SONICPESA_API_SECRET', 'YOUR_SONICPESA_API_SECRET');

// NextSMS Configuration (nextsms.co.tz)
define('NEXTSMS_USERNAME', 'YOUR_NEXTSMS_USERNAME');
define('NEXTSMS_PASSWORD', 'YOUR_NEXTSMS_PASSWORD');
define('NEXTSMS_SENDER_ID', 'NEXTSMS'); // Or your registered Sender ID
define('NEXTSMS_ADMIN_PHONE', '255xxxxxxxxx'); // Your phone number to receive notifications
?>
PHP;

                if (file_put_contents(__DIR__ . '/config.php', $config)) {
                    $_SESSION['installer_db'] = compact('db_host', 'db_name', 'db_user', 'db_pass');
                    header("Location: install.php?step=2");
                    exit;
                } else {
                    $error = "Cannot write config.php. Set folder permissions to 755 or 775.";
                }
            } catch (PDOException $e) {
                $error = "Connection failed: " . $e->getMessage();
            }
        }
    }

    // ---------- STEP 2: Install Tables ----------
    elseif ($step === 2) {
        if ($config_exists) require_once __DIR__ . '/config.php';
        try {
            $pdo = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER, DB_PASS);
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

            // Execute schema (each statement separately for compatibility)
            $statements = array_filter(array_map('trim', explode(';', $sql_schema)));
            foreach ($statements as $stmt) {
                if (!empty($stmt)) $pdo->exec($stmt);
            }

            // Insert default site settings
            $pdo->exec("INSERT IGNORE INTO site_settings (id, site_name, site_logo, site_favicon, landing_title, footer_copy, footer_made_by, allow_registration, system_commission, min_withdrawal) 
                         VALUES (1, 'SonicPesa', 'assets/images/logo.png', 'assets/images/favicon.png', 'UTAMU', 'SonicPesa Dashboard. All Rights Reserved.', 'SonicPesa Dev', 1, 0.00, 1000.00)");

            // Insert default templates
            for ($i = 1; $i <= 14; $i++) {
                $pdo->exec("INSERT IGNORE INTO templates (name, slug) VALUES ('Model V$i', 'landing$i')");
            }

            // --- Auto-register the current domain as a root domain ---
            $current_host = $_SERVER['HTTP_HOST'] ?? 'localhost';
            // Simple cleanup to ensure it's just the host
            $current_host = strtolower(trim($current_host));
            $pdo->exec("INSERT IGNORE INTO system_root_domains (domain_name, is_active) VALUES ('$current_host', 1)");

            header("Location: install.php?step=3");
            exit;
        } catch (PDOException $e) {
            $error = "Table creation error: " . $e->getMessage();
        }
    }

    // ---------- STEP 3: Create Admin ----------
    elseif ($step === 3) {
        if ($config_exists) require_once __DIR__ . '/config.php';
        $name  = trim($_POST['adm_name'] ?? '');
        $email = trim($_POST['adm_email'] ?? '');
        $pass  = trim($_POST['adm_pass'] ?? '');

        if (empty($name) || empty($email) || empty($pass)) {
            $error = "All fields are required.";
        } elseif (strlen($pass) < 6) {
            $error = "Password must be at least 6 characters.";
        } else {
            try {
                $pdo = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER, DB_PASS);
                $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

                $hash = password_hash($pass, PASSWORD_DEFAULT);
                $token = bin2hex(random_bytes(32));

                // Check if admin already exists
                $check = $pdo->prepare("SELECT id FROM users WHERE email = ?");
                $check->execute([$email]);
                if ($check->fetch()) {
                    $error = "An account with this email already exists.";
                } else {
                    $stmt = $pdo->prepare("INSERT INTO users (name, email, password, role, webhook_token) VALUES (?, ?, ?, 'admin', ?)");
                    $stmt->execute([$name, $email, $hash, $token]);
                    header("Location: install.php?step=4");
                    exit;
                }
            } catch (PDOException $e) {
                $error = "Admin creation error: " . $e->getMessage();
            }
        }
    }

    // ---------- STEP 4: Generate .htaccess ----------
    elseif ($step === 4) {
        $htaccess = <<<'HTACCESS'
# SonicPesa .htaccess - Generated by Installer

# Enable Rewriting
RewriteEngine On
RewriteBase /

# -------------------------------------------------------
# FIX: Always allow direct access to install.php so the
# installer is never caught by any rewrite or deny rule.
# -------------------------------------------------------
RewriteRule ^install\.php$ - [L,NC]

# --- Clean URLs: Strip .php extension ---
# Redirect /page.php to /page (skip system files and POST requests)
RewriteCond %{REQUEST_METHOD} !POST
RewriteCond %{THE_REQUEST} \s/+([^?\s]*?)([^/?.\s]+)\.php[?\s] [NC]
RewriteCond %2 !^(index|store|install|webhook|404|api)$ [NC]
RewriteRule ^(.+)\.php$ /$1 [R=301,L,NE]

# Internally serve page.php when /page is requested
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+)/?$ $1.php [L]

# --- Route /webhook ---
RewriteRule ^webhook/?$ webhook.php [L,QSA]

# --- Route /404 ---
RewriteRule ^404/?$ 404.php [L]

# --- Landing Page Slug Catch-All ---
# Explicitly skip reserved system filenames
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !/(index|store|install|login|register|dashboard|superadmin|admin_payments|webhook|revenue_stats|transactions|withdraw|profile|settings|statistics|sonicpesa_sandbox|users|domains|videos|upload|user_uploads|v|watch|edit_video|analytics|404|api)(\.php)?/?$ [NC]
RewriteRule ^([a-zA-Z0-9_-]+)/?$ store.php?name=$1 [L,QSA]

# --- Error Documents ---
ErrorDocument 404 /404.php

# --- Security: Protect Sensitive Files ---
<Files "config.php">
    <IfModule mod_authz_core.c>
        Require all denied
    </IfModule>
    <IfModule !mod_authz_core.c>
        Order deny,allow
        Deny from all
    </IfModule>
</Files>

# Note: install.php is intentionally NOT blocked here.
# DELETE install.php manually after completing all steps.
HTACCESS;

        if (file_put_contents(__DIR__ . '/.htaccess', $htaccess)) {
            header("Location: install.php?step=5");
            exit;
        } else {
            $error = "Could not write .htaccess file. Check permissions.";
        }
    }
}

// ==================== SYSTEM CHECKS ====================
function check_requirements() {
    $checks = [];
    $checks['PHP Version (7.4+)'] = version_compare(PHP_VERSION, '7.4.0', '>=');
    $checks['PDO MySQL Extension'] = extension_loaded('pdo_mysql');
    $checks['JSON Extension'] = extension_loaded('json');
    $checks['Mbstring Extension'] = extension_loaded('mbstring');
    $checks['config.php Writable'] = is_writable(__DIR__) || (file_exists(__DIR__ . '/config.php') && is_writable(__DIR__ . '/config.php'));
    $checks['.htaccess Writable'] = is_writable(__DIR__);
    $checks['templates/ Directory'] = is_dir(__DIR__ . '/templates');
    $checks['includes/ Directory'] = is_dir(__DIR__ . '/includes');
    return $checks;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SonicPesa — System Installer</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%); font-family: 'Inter', sans-serif; min-height: 100vh; display: flex; align-items: center; justify-content: center; padding: 20px; color: #e2e8f0; }
        .card { background: #1e293b; border: 1px solid #334155; border-radius: 20px; width: 100%; max-width: 550px; padding: 40px; box-shadow: 0 25px 50px rgba(0,0,0,0.4); }
        .logo { text-align: center; margin-bottom: 30px; }
        .logo h1 { font-size: 1.8rem; font-weight: 700; background: linear-gradient(135deg, #60a5fa, #a78bfa); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }
        .logo p { font-size: 0.8rem; color: #94a3b8; margin-top: 5px; }

        /* Step Indicator */
        .steps { display: flex; justify-content: center; gap: 8px; margin-bottom: 30px; }
        .step-dot { width: 40px; height: 5px; border-radius: 3px; background: #334155; transition: 0.3s; }
        .step-dot.active { background: linear-gradient(135deg, #60a5fa, #a78bfa); }
        .step-dot.done { background: #22c55e; }

        h3 { font-size: 1.2rem; margin-bottom: 5px; }
        .subtitle { font-size: 0.8rem; color: #94a3b8; margin-bottom: 25px; }

        /* Form */
        label { display: block; font-size: 0.8rem; font-weight: 600; color: #94a3b8; margin-bottom: 6px; text-transform: uppercase; letter-spacing: 0.5px; }
        input[type="text"], input[type="email"], input[type="password"], input[type="url"] {
            width: 100%; background: #0f172a; border: 1px solid #334155; border-radius: 10px; padding: 14px 16px; color: #e2e8f0; font-size: 0.95rem; outline: none; transition: 0.2s; margin-bottom: 18px;
        }
        input:focus { border-color: #60a5fa; box-shadow: 0 0 0 3px rgba(96,165,250,0.15); }
        .btn { width: 100%; padding: 16px; border: none; border-radius: 12px; font-weight: 700; font-size: 1rem; cursor: pointer; transition: 0.2s; }
        .btn-primary { background: linear-gradient(135deg, #3b82f6, #8b5cf6); color: #fff; }
        .btn-primary:hover { transform: translateY(-2px); box-shadow: 0 10px 20px rgba(59,130,246,0.3); }
        .btn-success { background: linear-gradient(135deg, #22c55e, #16a34a); color: #fff; }
        .btn-outline { background: transparent; border: 2px solid #334155; color: #e2e8f0; }
        .btn-outline:hover { border-color: #60a5fa; }
        .btn + .btn { margin-top: 10px; }

        /* Alerts */
        .alert { padding: 14px 18px; border-radius: 10px; font-size: 0.85rem; margin-bottom: 20px; }
        .alert-danger { background: rgba(239,68,68,0.15); border: 1px solid rgba(239,68,68,0.3); color: #fca5a5; }
        .alert-success { background: rgba(34,197,94,0.15); border: 1px solid rgba(34,197,94,0.3); color: #86efac; }

        /* Checks */
        .check-list { margin-bottom: 25px; }
        .check-item { display: flex; align-items: center; gap: 10px; padding: 10px 0; border-bottom: 1px solid #1e293b; font-size: 0.9rem; }
        .check-icon { font-size: 1.1rem; }
        .pass { color: #22c55e; }
        .fail { color: #ef4444; }

        /* Success page */
        .success-icon { font-size: 4rem; color: #22c55e; text-align: center; margin-bottom: 15px; }
        .warn-box { background: rgba(245,158,11,0.1); border: 1px solid rgba(245,158,11,0.3); border-radius: 10px; padding: 15px; font-size: 0.85rem; color: #fbbf24; margin: 20px 0; }
    </style>
</head>
<body>
<div class="card">
    <div class="logo">
        <h1>⚡ SonicPesa Installer</h1>
        <p>Automated System Setup</p>
    </div>

    <div class="steps">
        <div class="step-dot <?= $step >= 1 ? ($step > 1 ? 'done' : 'active') : '' ?>"></div>
        <div class="step-dot <?= $step >= 2 ? ($step > 2 ? 'done' : 'active') : '' ?>"></div>
        <div class="step-dot <?= $step >= 3 ? ($step > 3 ? 'done' : 'active') : '' ?>"></div>
        <div class="step-dot <?= $step >= 4 ? ($step > 4 ? 'done' : 'active') : '' ?>"></div>
        <div class="step-dot <?= $step >= 5 ? 'active' : '' ?>"></div>
    </div>

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

    <!-- ==================== STEP 1: System Check & Database ==================== -->
    <?php if ($step === 1): ?>
        <?php $checks = check_requirements(); $all_pass = !in_array(false, $checks, true); ?>
        <h3>Step 1: System Requirements & Database</h3>
        <p class="subtitle">Checking your server and connecting to your database.</p>

        <div class="check-list">
            <?php foreach ($checks as $label => $pass): ?>
            <div class="check-item">
                <span class="check-icon <?= $pass ? 'pass' : 'fail' ?>"><?= $pass ? '✓' : '✗' ?></span>
                <span><?= $label ?></span>
            </div>
            <?php endforeach; ?>
        </div>

        <?php if ($all_pass): ?>
        <form method="POST">
            <label>MySQL Host</label>
            <input type="text" name="db_host" value="localhost" required>
            <label>Database Name</label>
            <input type="text" name="db_name" placeholder="SonicPesa_db" required>
            <label>Database Username</label>
            <input type="text" name="db_user" placeholder="e.g. root or cpanel_user" required>
            <label>Database Password</label>
            <input type="password" name="db_pass" placeholder="Your DB password">
            <button type="submit" class="btn btn-primary">Connect & Save Config →</button>
        </form>
        <?php else: ?>
            <div class="alert alert-danger">Please fix the failed requirements before continuing.</div>
        <?php endif; ?>

    <!-- ==================== STEP 2: Install Tables ==================== -->
    <?php elseif ($step === 2): ?>
        <h3>Step 2: Database Tables</h3>
        <p class="subtitle">Config saved! Now creating all required database tables.</p>
        <form method="POST">
            <p style="font-size:0.85rem; color:#94a3b8; margin-bottom:20px;">This will create 11 tables: users, videos, user_domains, link_analytics, site_settings, system_root_domains, templates, transactions, withdrawals, admin_logs, and tutorials.</p>
            <button type="submit" class="btn btn-primary">Install Tables →</button>
        </form>

    <!-- ==================== STEP 3: Admin Account ==================== -->
    <?php elseif ($step === 3): ?>
        <h3>Step 3: Super Admin Account</h3>
        <p class="subtitle">Create your master admin account to manage the system.</p>
        <form method="POST">
            <label>Full Name</label>
            <input type="text" name="adm_name" placeholder="John Doe" required>
            <label>Email Address</label>
            <input type="email" name="adm_email" placeholder="admin@example.com" required>
            <label>Password (min 6 chars)</label>
            <input type="password" name="adm_pass" placeholder="••••••••" required minlength="6">
            <button type="submit" class="btn btn-primary">Create Admin →</button>
        </form>

    <!-- ==================== STEP 4: Generate .htaccess ==================== -->
    <?php elseif ($step === 4): ?>
        <h3>Step 4: Generate .htaccess</h3>
        <p class="subtitle">Setting up clean URLs and security rules for your hosting.</p>
        <form method="POST">
            <p style="font-size:0.85rem; color:#94a3b8; margin-bottom:20px;">This will create a production-ready .htaccess file with:
            <br>• Clean URLs (no .php extensions)
            <br>• Landing page slug routing
            <br>• Security protection for config files</p>
            <button type="submit" class="btn btn-primary">Generate .htaccess →</button>
        </form>

    <!-- ==================== STEP 5: Complete ==================== -->
    <?php elseif ($step === 5): ?>
        <div class="success-icon">✓</div>
        <h3 style="text-align:center;">Installation Complete!</h3>
        <p class="subtitle" style="text-align:center;">SonicPesa is ready to use on your hosting.</p>

        <div class="warn-box">
            <strong>🔒 SECURITY:</strong> Delete <code>install.php</code> from your server immediately to prevent unauthorized access!
        </div>

        <p style="font-size:0.85rem; color:#94a3b8; margin-bottom:20px; text-align:center;">
            Login with the admin email and password you just created.
        </p>

        <a href="login" class="btn btn-success" style="display:block; text-align:center; text-decoration:none;">🚀 Launch Admin Dashboard</a>
        <a href="." class="btn btn-outline" style="display:block; text-align:center; text-decoration:none; margin-top:10px;">Visit Homepage</a>

    <?php endif; ?>
</div>
</body>
</html>
