<?php
// Catch any fatal setup errors
ini_set('display_errors', '1');
error_reporting(E_ALL);

// Safe Session Start
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Bulletproof dynamic Root Directory resolution
$currentDir = __DIR__;
$parentDir = dirname($currentDir);
$rootDir = (basename($parentDir) === 'public') ? dirname($parentDir) : $parentDir;
define('ROOT_DIR', $rootDir);

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

// SECURITY: If .env exists, the app is already installed! 
// Allow steps 4 and 5 to complete the setup, otherwise redirect out.
if (file_exists(ROOT_DIR . '/.env') && !in_array($step, [4, 5])) {
    header("Location: ../index.php");
    exit;
}

// Handle POST submissions to advance steps
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    
    // STEP 2: WRITE LICENSE KEY IMMEDIATELY
    if ($step === 2) {
        $licenseKey = trim($_POST['license_key'] ?? '');
        $_SESSION['install_license'] = $licenseKey;
        
        // Ensure config directory exists
        $keyDir = ROOT_DIR . '/config';
        if (!is_dir($keyDir)) {
            @mkdir($keyDir, 0755, true);
        }
        
        // Write the license file right now
        @file_put_contents($keyDir . '/license.key', $licenseKey);
        
        header("Location: ?step=3");
        exit;
    }
    
    // STEP 4: WRITE ADMIN & SETTINGS TO DB
    if ($step === 4) {
        try {
            $envPath = ROOT_DIR . '/.env';
            if (!file_exists($envPath)) {
                throw new Exception("Critical Error: .env file was not found in the root directory. Please ensure you created the file manually in Step 3.");
            }

            $lines = file($envPath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
            $dbConfig = [];
            foreach ($lines as $line) {
                if (strpos(trim($line), '#') === 0) continue;
                list($name, $value) = explode('=', $line, 2);
                $dbConfig[trim($name)] = trim($value, " \t\n\r\0\x0B\"");
            }

            $pdo = new PDO("mysql:host={$dbConfig['DB_HOST']};dbname={$dbConfig['DB_NAME']};charset=utf8mb4", $dbConfig['DB_USER'], $dbConfig['DB_PASS']);
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

            // 1. Insert Admin User
            $adminPass = password_hash($_POST['admin_pass'], PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("INSERT INTO users (name, email, password, role, is_active, email_verified) VALUES (?, ?, ?, 'admin', 1, 1)");
            $stmt->execute([$_POST['admin_name'], $_POST['admin_email'], $adminPass]);

            // Save credentials for the final screen
            $_SESSION['final_email'] = $_POST['admin_email'];
            $_SESSION['final_pass'] = $_POST['admin_pass'];

            // 2. Update Settings (Company & SMTP - Optional)
            $settingsUpdates = [
                'app_name' => $_POST['company_name'] ?? 'Jobcard Manager Pro',
                'contact_email' => $_POST['company_email'] ?? '',
                'contact_landline' => $_POST['company_phone'] ?? '',
                'contact_address_street' => $_POST['address_street'] ?? '',
                'contact_address_suburb' => $_POST['address_suburb'] ?? '',
                'contact_address_city' => $_POST['address_city'] ?? '',
                'contact_address_state' => $_POST['address_state'] ?? '',
                'contact_address_zip' => $_POST['address_zip'] ?? '',
                'contact_address_country' => $_POST['address_country'] ?? '',
                'smtp_host' => $_POST['smtp_host'] ?? '',
                'smtp_port' => $_POST['smtp_port'] ?? '',
                'smtp_user' => $_POST['smtp_user'] ?? '',
                'smtp_pass' => $_POST['smtp_pass'] ?? '',
                'smtp_from_email' => $_POST['smtp_from_email'] ?? '',
                'smtp_from_name' => $_POST['company_name'] ?? ''
            ];

            foreach ($settingsUpdates as $key => $val) {
                if (!empty($val)) {
                    $stmt = $pdo->prepare("UPDATE settings SET setting_value = ? WHERE setting_key = ?");
                    $stmt->execute([$val, $key]);
                }
            }

            header("Location: ?step=5");
            exit;

        } catch (Exception $e) {
            $error = "Failed to save configuration: " . $e->getMessage();
        }
    }
}

// ---------------------------------------------------------
// STEP 1 LOGIC: DEPENDENCY CHECKS
// ---------------------------------------------------------
$dependencies = [];
$allPassed = true;
if ($step === 1) {
    $dependencies = [
        'PHP Version >= 8.0' => PHP_VERSION_ID >= 80000,
        'PDO Extension' => extension_loaded('pdo'),
        'PDO MySQL' => extension_loaded('pdo_mysql'),
        'MBString' => extension_loaded('mbstring'),
        'cURL' => extension_loaded('curl'),
        'OpenSSL' => extension_loaded('openssl'),
        'JSON' => extension_loaded('json'),
        'ZIP Extension' => extension_loaded('zip'),
        'Root Directory Writable' => is_writable(ROOT_DIR),
        'Config Directory Writable' => is_writable(ROOT_DIR . '/config') || is_writable(ROOT_DIR)
    ];
    foreach ($dependencies as $name => $passed) {
        if (!$passed && strpos($name, 'Writable') === false) {
            $allPassed = false;
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Application Setup</title>
    
    <?php if (file_exists(dirname(__DIR__) . '/uploads/favicon.png')): ?>
        <link rel="icon" type="image/png" href="../uploads/favicon.png">
    <?php endif; ?>

    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap');
        body { font-family: 'Plus Jakarta Sans', sans-serif; background-color: #f8fafc; }
        .spinner { animation: spin 1s linear infinite; }
        @keyframes spin { 100% { transform: rotate(360deg); } }
    </style>
</head>
<body class="min-h-screen flex items-center justify-center p-4">

<div class="max-w-3xl w-full">
    
    <div class="text-center mb-8">
        <?php if (file_exists(dirname(__DIR__) . '/uploads/logo_light.png')): ?>
            <img src="../uploads/logo_light.png" alt="Company Logo" class="mx-auto h-16 object-contain mb-4">
        <?php endif; ?>
        <h1 class="text-3xl font-extrabold text-slate-800">Jobcard Manager Pro Setup</h1>
        <p class="text-slate-500 mt-2">Welcome! Let's get your system configured and ready for production.</p>
    </div>

    <!-- Progress Indicator -->
    <div class="flex items-center justify-between mb-8 relative">
        <div class="absolute left-0 top-1/2 transform -translate-y-1/2 w-full h-1 bg-slate-200 z-0 rounded"></div>
        <div class="absolute left-0 top-1/2 transform -translate-y-1/2 h-1 bg-blue-600 z-0 rounded transition-all duration-500" style="width: <?php echo ($step - 1) * 25; ?>%;"></div>
        
        <?php for($i = 1; $i <= 5; $i++): ?>
            <div class="relative z-10 w-8 h-8 flex items-center justify-center rounded-full font-bold text-sm <?php echo $i <= $step ? 'bg-blue-600 text-white' : 'bg-slate-200 text-slate-500'; ?> border-4 border-[#f8fafc]">
                <?php echo $i; ?>
            </div>
        <?php endfor; ?>
    </div>

    <div class="bg-white rounded-2xl shadow-xl border border-slate-200 overflow-hidden">
        
        <?php if(isset($error)): ?>
            <div class="bg-red-50 border-b border-red-200 p-4 text-red-600 font-bold text-sm text-center">
                <?php echo $error; ?>
            </div>
        <?php endif; ?>

        <div class="p-8">
            
            <!-- STEP 1: Dependencies -->
            <?php if ($step === 1): ?>
                <h2 class="text-xl font-bold text-slate-800 mb-6 border-b border-slate-200 pb-3">1. System Requirements</h2>
                <div class="space-y-3 mb-8">
                    <?php foreach ($dependencies as $name => $passed): ?>
                        <div class="flex items-center justify-between p-3 rounded-lg <?php echo $passed ? 'bg-green-50 border border-green-100' : 'bg-red-50 border border-red-200'; ?>">
                            <span class="text-sm font-medium <?php echo $passed ? 'text-slate-700' : 'text-red-700 font-bold'; ?>"><?php echo $name; ?></span>
                            <?php if($passed): ?>
                                <svg class="w-5 h-5 text-green-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path></svg>
                            <?php else: ?>
                                <svg class="w-5 h-5 text-red-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                </div>
                
                <div class="flex justify-end">
                    <?php if ($allPassed): ?>
                        <a href="?step=2" class="px-6 py-3 bg-blue-600 text-white font-bold rounded-lg hover:bg-blue-700 transition-colors">Continue to Licensing</a>
                    <?php else: ?>
                        <button disabled class="px-6 py-3 bg-slate-300 text-slate-500 font-bold rounded-lg cursor-not-allowed">Fix errors to continue</button>
                    <?php endif; ?>
                </div>
            <?php endif; ?>

            <!-- STEP 2: License -->
            <?php if ($step === 2): ?>
                <form method="POST">
                    <h2 class="text-xl font-bold text-slate-800 mb-6 border-b border-slate-200 pb-3">2. Software Registration</h2>
                    <div class="mb-6">
                        <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">License Key</label>
                        <input type="text" name="license_key" placeholder="APP-XXXX-XXXX-XXXX" class="w-full px-4 py-3 rounded-lg border border-slate-300 focus:ring-2 focus:ring-blue-500 outline-none font-mono tracking-widest text-center text-lg" required>
                    </div>
                    <div class="bg-blue-50 p-4 rounded-lg border border-blue-100 mb-8 text-sm text-blue-800">
                        Don't have a license key? <a href="https://license.christodev.co.za/portal/request" target="_blank" class="font-bold underline text-blue-900">Click here to request a 30-day trial or purchase a permanent license.</a>
                    </div>
                    <div class="flex justify-between">
                        <a href="?step=1" class="px-6 py-3 bg-slate-100 text-slate-600 font-bold rounded-lg hover:bg-slate-200 transition-colors">Back</a>
                        <button type="submit" class="px-6 py-3 bg-blue-600 text-white font-bold rounded-lg hover:bg-blue-700 transition-colors">Verify & Continue</button>
                    </div>
                </form>
            <?php endif; ?>

            <!-- STEP 3: Database -->
            <?php if ($step === 3): ?>
                <h2 class="text-xl font-bold text-slate-800 mb-6 border-b border-slate-200 pb-3">3. Database Connection</h2>
                
                <div id="db-form-container">
                    <form id="db-form" class="space-y-5">
                        <div class="grid grid-cols-2 gap-5">
                            <div>
                                <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Database Host</label>
                                <input type="text" id="db_host" value="localhost" class="w-full px-4 py-2.5 rounded-lg border border-slate-300 focus:ring-2 focus:ring-blue-500 outline-none" required>
                            </div>
                            <div>
                                <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Database Name</label>
                                <input type="text" id="db_name" class="w-full px-4 py-2.5 rounded-lg border border-slate-300 focus:ring-2 focus:ring-blue-500 outline-none" required>
                            </div>
                            <div>
                                <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Database Username</label>
                                <input type="text" id="db_user" class="w-full px-4 py-2.5 rounded-lg border border-slate-300 focus:ring-2 focus:ring-blue-500 outline-none" required>
                            </div>
                            <div>
                                <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Database Password</label>
                                <input type="password" id="db_pass" class="w-full px-4 py-2.5 rounded-lg border border-slate-300 focus:ring-2 focus:ring-blue-500 outline-none">
                            </div>
                        </div>

                        <div id="db-error" class="hidden text-sm text-red-600 bg-red-50 border border-red-200 p-3 rounded-lg"></div>

                        <div class="flex justify-between pt-4">
                            <a href="?step=2" class="px-6 py-3 bg-slate-100 text-slate-600 font-bold rounded-lg hover:bg-slate-200 transition-colors">Back</a>
                            <button type="submit" class="px-6 py-3 bg-blue-600 text-white font-bold rounded-lg hover:bg-blue-700 transition-colors">Install Database</button>
                        </div>
                    </form>
                </div>

                <!-- Animated Loading State -->
                <div id="db-loading-container" class="hidden flex-col items-center justify-center py-10">
                    <svg class="spinner w-12 h-12 text-blue-600 mb-4" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg>
                    <h3 id="db-status-text" class="text-lg font-bold text-slate-800">Connecting to database...</h3>
                    <p class="text-sm text-slate-500 mt-2">Please do not close or refresh this page.</p>
                </div>

                <!-- Fallback UI for File Permission Errors -->
                <div id="manual-env-container" class="hidden">
                    <div class="bg-amber-50 border border-amber-200 rounded-xl p-5 mb-6">
                        <div class="flex items-center mb-2">
                            <svg class="w-6 h-6 text-amber-500 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"></path></svg>
                            <h3 class="text-lg font-bold text-amber-800">Manual Configuration Required</h3>
                        </div>
                        <p class="text-sm text-amber-700 mb-4">The database was successfully installed, but the system does not have permission to automatically write the configuration file to your server. Please create the file manually.</p>
                        
                        <p class="text-xs font-bold uppercase tracking-wider text-slate-500 mb-1">Create a file at this exact location:</p>
                        <code id="manual-env-path" class="block bg-white p-3 rounded text-sm font-mono mb-4 border border-slate-200 text-slate-800 select-all"></code>
                        
                        <p class="text-xs font-bold uppercase tracking-wider text-slate-500 mb-1">Paste this exact content inside it:</p>
                        <pre id="manual-env-content" class="bg-slate-900 text-green-400 p-4 rounded-lg text-sm font-mono overflow-x-auto whitespace-pre-wrap select-all"></pre>
                    </div>

                    <div class="flex justify-end">
                        <a href="?step=4" class="px-6 py-3 bg-blue-600 text-white font-bold rounded-lg hover:bg-blue-700 transition-colors">I have created the file - Continue</a>
                    </div>
                </div>

                <script>
                    document.getElementById('db-form').addEventListener('submit', function(e) {
                        e.preventDefault();
                        
                        document.getElementById('db-form-container').classList.add('hidden');
                        document.getElementById('db-loading-container').classList.remove('hidden');
                        document.getElementById('db-loading-container').classList.add('flex');

                        const statuses = [
                            'Connecting to database...', 
                            'Importing base schema...', 
                            'Setting database version to 0...', 
                            'Running structural migrations...', 
                            'Finalizing database installation...'
                        ];
                        let i = 0;
                        const statusEl = document.getElementById('db-status-text');
                        
                        const statusInterval = setInterval(() => {
                            if (i < statuses.length - 1) i++;
                            statusEl.innerText = statuses[i];
                        }, 1200);

                        const formData = new FormData();
                        formData.append('action', 'install_db');
                        formData.append('db_host', document.getElementById('db_host').value);
                        formData.append('db_name', document.getElementById('db_name').value);
                        formData.append('db_user', document.getElementById('db_user').value);
                        formData.append('db_pass', document.getElementById('db_pass').value);

                        fetch('api.php', { method: 'POST', body: formData })
                        .then(res => res.json())
                        .then(data => {
                            clearInterval(statusInterval);
                            if (data.success) {
                                if (data.requires_manual_env) {
                                    document.getElementById('db-loading-container').classList.add('hidden');
                                    document.getElementById('db-loading-container').classList.remove('flex');
                                    document.getElementById('manual-env-container').classList.remove('hidden');
                                    document.getElementById('manual-env-content').textContent = data.env_content;
                                    document.getElementById('manual-env-path').textContent = data.env_path;
                                } else {
                                    statusEl.innerText = 'Database installed successfully!';
                                    statusEl.classList.replace('text-slate-800', 'text-green-600');
                                    document.querySelector('.spinner').classList.add('hidden');
                                    setTimeout(() => { window.location.href = "?step=4"; }, 1500);
                                }
                            } else {
                                document.getElementById('db-loading-container').classList.add('hidden');
                                document.getElementById('db-loading-container').classList.remove('flex');
                                document.getElementById('db-form-container').classList.remove('hidden');
                                const errEl = document.getElementById('db-error');
                                errEl.innerText = data.message;
                                errEl.classList.remove('hidden');
                            }
                        })
                        .catch(err => {
                            clearInterval(statusInterval);
                            alert("A critical fetch error occurred. Check server logs.");
                        });
                    });
                </script>
            <?php endif; ?>

            <!-- STEP 4: Configuration -->
            <?php if ($step === 4): ?>
                <form method="POST" class="space-y-8">
                    
                    <!-- Admin User -->
                    <div>
                        <h2 class="text-sm font-bold text-slate-800 uppercase tracking-wider border-b border-slate-200 pb-2 mb-4">Master Administrator Account</h2>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
                            <div class="md:col-span-2">
                                <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Full Name *</label>
                                <input type="text" name="admin_name" class="w-full px-4 py-2.5 rounded-lg border border-slate-300 focus:ring-2 focus:ring-blue-500 outline-none" required autofocus>
                            </div>
                            <div>
                                <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Email Address (Login ID) *</label>
                                <input type="email" name="admin_email" class="w-full px-4 py-2.5 rounded-lg border border-slate-300 focus:ring-2 focus:ring-blue-500 outline-none" required>
                            </div>
                            <div>
                                <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Secure Password *</label>
                                <input type="password" name="admin_pass" class="w-full px-4 py-2.5 rounded-lg border border-slate-300 focus:ring-2 focus:ring-blue-500 outline-none" required minlength="6">
                            </div>
                        </div>
                    </div>

                    <!-- Company Info & Structured Address -->
                    <div>
                        <div class="flex justify-between items-end border-b border-slate-200 pb-2 mb-4">
                            <h2 class="text-sm font-bold text-slate-800 uppercase tracking-wider">Company Information & Address</h2>
                            <span class="text-[10px] font-bold text-slate-400 uppercase">Optional</span>
                        </div>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-5 mb-5">
                            <div>
                                <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Company Name</label>
                                <input type="text" name="company_name" class="w-full px-4 py-2.5 rounded-lg border border-slate-300 focus:ring-2 focus:ring-blue-500 outline-none">
                            </div>
                            <div>
                                <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Company Phone</label>
                                <input type="text" name="company_phone" class="w-full px-4 py-2.5 rounded-lg border border-slate-300 focus:ring-2 focus:ring-blue-500 outline-none">
                            </div>
                            <div class="md:col-span-2">
                                <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Public Email</label>
                                <input type="email" name="company_email" class="w-full px-4 py-2.5 rounded-lg border border-slate-300 focus:ring-2 focus:ring-blue-500 outline-none">
                            </div>
                        </div>

                        <!-- Pill Based Address Layout -->
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-5 bg-slate-50 p-4 rounded-xl border border-slate-200">
                            <div class="md:col-span-2">
                                <label class="block text-[10px] font-bold text-slate-500 uppercase tracking-wider mb-2">Street Address</label>
                                <input type="text" name="address_street" class="w-full px-4 py-2.5 rounded-lg border border-slate-300 focus:ring-2 focus:ring-blue-500 outline-none">
                            </div>
                            <div>
                                <label class="block text-[10px] font-bold text-slate-500 uppercase tracking-wider mb-2">Suburb</label>
                                <input type="text" name="address_suburb" class="w-full px-4 py-2.5 rounded-lg border border-slate-300 focus:ring-2 focus:ring-blue-500 outline-none">
                            </div>
                            <div>
                                <label class="block text-[10px] font-bold text-slate-500 uppercase tracking-wider mb-2">City</label>
                                <input type="text" name="address_city" class="w-full px-4 py-2.5 rounded-lg border border-slate-300 focus:ring-2 focus:ring-blue-500 outline-none">
                            </div>
                            <div>
                                <label class="block text-[10px] font-bold text-slate-500 uppercase tracking-wider mb-2">State / Province</label>
                                <input type="text" name="address_state" class="w-full px-4 py-2.5 rounded-lg border border-slate-300 focus:ring-2 focus:ring-blue-500 outline-none">
                            </div>
                            <div>
                                <label class="block text-[10px] font-bold text-slate-500 uppercase tracking-wider mb-2">Postal / Zip Code</label>
                                <input type="text" name="address_zip" class="w-full px-4 py-2.5 rounded-lg border border-slate-300 focus:ring-2 focus:ring-blue-500 outline-none">
                            </div>
                            <div class="md:col-span-2">
                                <label class="block text-[10px] font-bold text-slate-500 uppercase tracking-wider mb-2">Country</label>
                                <input type="text" name="address_country" class="w-full px-4 py-2.5 rounded-lg border border-slate-300 focus:ring-2 focus:ring-blue-500 outline-none">
                            </div>
                        </div>
                    </div>

                    <!-- SMTP Info -->
                    <div>
                        <div class="flex justify-between items-end border-b border-slate-200 pb-2 mb-4">
                            <h2 class="text-sm font-bold text-slate-800 uppercase tracking-wider">Mail Server (SMTP)</h2>
                            <span class="text-[10px] font-bold text-slate-400 uppercase">Optional - Configure Later</span>
                        </div>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
                            <div class="md:col-span-2 flex gap-5">
                                <div class="w-3/4">
                                    <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">SMTP Host</label>
                                    <input type="text" name="smtp_host" placeholder="mail.domain.com" class="w-full px-4 py-2.5 rounded-lg border border-slate-300 focus:ring-2 focus:ring-blue-500 outline-none">
                                </div>
                                <div class="w-1/4">
                                    <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Port</label>
                                    <input type="text" name="smtp_port" placeholder="465" class="w-full px-4 py-2.5 rounded-lg border border-slate-300 focus:ring-2 focus:ring-blue-500 outline-none">
                                </div>
                            </div>
                            <div>
                                <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">SMTP Username</label>
                                <input type="text" name="smtp_user" class="w-full px-4 py-2.5 rounded-lg border border-slate-300 focus:ring-2 focus:ring-blue-500 outline-none">
                            </div>
                            <div>
                                <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">SMTP Password</label>
                                <input type="password" name="smtp_pass" class="w-full px-4 py-2.5 rounded-lg border border-slate-300 focus:ring-2 focus:ring-blue-500 outline-none">
                            </div>
                            <div class="md:col-span-2">
                                <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Sender Address (From)</label>
                                <input type="email" name="smtp_from_email" placeholder="noreply@domain.com" class="w-full px-4 py-2.5 rounded-lg border border-slate-300 focus:ring-2 focus:ring-blue-500 outline-none">
                            </div>
                        </div>
                    </div>

                    <div class="flex justify-end pt-4 border-t border-slate-200">
                        <button type="submit" class="px-8 py-3 bg-blue-600 text-white font-bold rounded-lg hover:bg-blue-700 transition-colors">Save & Finalize</button>
                    </div>
                </form>
            <?php endif; ?>

            <!-- STEP 5: Success -->
            <?php if ($step === 5): ?>
                <div class="text-center py-8">
                    
                    <div class="mx-auto flex items-center justify-center h-20 w-20 rounded-full bg-green-100 text-green-600 mb-6">
                        <svg class="h-10 w-10" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path></svg>
                    </div>

                    <h2 class="text-3xl font-extrabold text-slate-800 mb-4">Installation Complete!</h2>
                    <p class="text-slate-500 mb-8 max-w-lg mx-auto">Your application has been successfully configured. Please safely document the credentials below.</p>
                    
                    <div class="bg-slate-50 border border-slate-200 rounded-xl p-6 inline-block text-left mb-8 w-full max-w-md">
                        <h3 class="text-xs font-bold text-slate-400 uppercase tracking-wider mb-4">Administrator Credentials</h3>
                        <div class="mb-3">
                            <span class="block text-xs text-slate-500 font-bold mb-1">Email Address</span>
                            <span class="text-slate-900 font-mono font-bold"><?php echo $_SESSION['final_email'] ?? ''; ?></span>
                        </div>
                        <div>
                            <span class="block text-xs text-slate-500 font-bold mb-1">Password</span>
                            <span class="text-slate-900 font-mono font-bold"><?php echo $_SESSION['final_pass'] ?? ''; ?></span>
                        </div>
                    </div>

                    <div class="flex flex-col sm:flex-row justify-center gap-4">
                        <a href="../index.php" class="px-8 py-3 bg-slate-800 text-white font-bold rounded-lg hover:bg-slate-900 transition-colors">View Frontend</a>
                        <a href="../users/login" class="px-8 py-3 bg-blue-600 text-white font-bold rounded-lg hover:bg-blue-700 transition-colors">Login to Admin Portal</a>
                    </div>
                </div>
                <?php session_destroy(); ?>
            <?php endif; ?>

        </div>
    </div>
</div>

</body>
</html>