<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Setup Wizard - {{ config('app.name', 'Afrilen Technologies') }}</title>
    
    <!-- Fonts -->
    <link rel="preconnect" href="https://fonts.bunny.net">
    <link href="https://fonts.bunny.net/css?family=figtree:400,500,600&display=swap" rel="stylesheet" />
    
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" integrity="sha512-iecdLmaskl7CVkqkXNQ/ZH/XLlvWZOJyj7Yy7tcenmpD1ypASozpmT/E0iPtmFIB46ZmdtAc9eNBvH0H/ZpiBw==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Figtree', sans-serif;
            background: linear-gradient(135deg, #1a1a1a 0%, #2d2d2d 100%);
            color: #e0e0e0;
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        
        .setup-container {
            max-width: 800px;
            width: 100%;
            background: #2d2d2d;
            border-radius: 10px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.5);
            overflow: hidden;
        }
        
        .setup-header {
            background: linear-gradient(135deg, #4a9eff 0%, #6bff6b 100%);
            padding: 40px;
            text-align: center;
            color: white;
        }
        
        .setup-header h1 {
            font-size: 32px;
            margin-bottom: 10px;
        }
        
        .setup-header p {
            font-size: 16px;
            opacity: 0.9;
        }
        
        .setup-content {
            padding: 40px;
        }
        
        .step-indicator {
            display: flex;
            justify-content: space-between;
            margin-bottom: 40px;
            position: relative;
        }
        
        .step-indicator::before {
            content: '';
            position: absolute;
            top: 20px;
            left: 0;
            right: 0;
            height: 2px;
            background: #404040;
            z-index: 0;
        }
        
        .step {
            position: relative;
            z-index: 1;
            text-align: center;
            flex: 1;
        }
        
        .step-circle {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: #404040;
            color: #888;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 10px;
            font-weight: 600;
            transition: all 0.3s;
        }
        
        .step.active .step-circle {
            background: #4a9eff;
            color: white;
        }
        
        .step.completed .step-circle {
            background: #6bff6b;
            color: white;
        }
        
        .step-label {
            font-size: 12px;
            color: #888;
        }
        
        .step.active .step-label {
            color: #4a9eff;
        }
        
        .step-content {
            display: none;
        }
        
        .step-content.active {
            display: block;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        label {
            display: block;
            margin-bottom: 8px;
            color: #e0e0e0;
            font-weight: 500;
        }
        
        input[type="text"],
        input[type="email"],
        input[type="password"],
        input[type="url"],
        input[type="number"],
        select {
            width: 100%;
            padding: 12px;
            background: #1a1a1a;
            border: 1px solid #404040;
            border-radius: 5px;
            font-size: 16px;
            color: #e0e0e0;
            transition: border-color 0.3s;
            font-family: inherit;
        }
        
        input:focus,
        select:focus {
            outline: none;
            border-color: #4a9eff;
        }
        
        .btn {
            display: inline-block;
            padding: 12px 24px;
            border-radius: 5px;
            text-decoration: none;
            font-size: 16px;
            cursor: pointer;
            border: none;
            transition: all 0.3s;
            font-weight: 500;
        }
        
        .btn-primary {
            background: #4a9eff;
            color: white;
        }
        
        .btn-primary:hover {
            background: #3a8eef;
        }
        
        .btn-secondary {
            background: #404040;
            color: #e0e0e0;
        }
        
        .btn-secondary:hover {
            background: #505050;
        }
        
        .btn-success {
            background: #6bff6b;
            color: white;
        }
        
        .btn-success:hover {
            background: #5bef5b;
        }
        
        .btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        
        .alert {
            padding: 15px 20px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        
        .alert-success {
            background: #6bff6b;
            color: #000;
        }
        
        .alert-error {
            background: #ff6b6b;
            color: white;
        }
        
        .alert-warning {
            background: #ffc107;
            color: #000;
        }
        
        .alert-info {
            background: #4a9eff;
            color: white;
        }
        
        .requirement-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px;
            background: #1a1a1a;
            border-radius: 5px;
            margin-bottom: 10px;
        }
        
        .requirement-status {
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
        }
        
        .requirement-status.met {
            background: #6bff6b;
            color: #000;
        }
        
        .requirement-status.failed {
            background: #ff6b6b;
            color: white;
        }
        
        .form-actions {
            display: flex;
            justify-content: space-between;
            margin-top: 30px;
            gap: 10px;
        }
        
        .loading {
            display: none;
            text-align: center;
            padding: 20px;
        }
        
        .loading.active {
            display: block;
        }
        
        .spinner {
            border: 3px solid #404040;
            border-top: 3px solid #4a9eff;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 15px;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .grid-2 {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 20px;
        }
        
        @media (max-width: 768px) {
            .grid-2 {
                grid-template-columns: 1fr;
            }
            
            .step-indicator {
                flex-direction: column;
                gap: 20px;
            }
            
            .step-indicator::before {
                display: none;
            }
        }
    </style>
</head>
<body>
    <div class="setup-container">
        <div class="setup-header">
            <h1><i class="fas fa-rocket"></i> Installation Wizard</h1>
            <p>Welcome! Let's get your application set up in a few simple steps.</p>
        </div>
        
        <div class="setup-content">
            <!-- Step Indicator -->
            <div class="step-indicator">
                <div class="step active" data-step="1">
                    <div class="step-circle">1</div>
                    <div class="step-label">Requirements</div>
                </div>
                <div class="step" data-step="2">
                    <div class="step-circle">2</div>
                    <div class="step-label">Database</div>
                </div>
                <div class="step" data-step="3">
                    <div class="step-circle">3</div>
                    <div class="step-label">Application</div>
                </div>
                <div class="step" data-step="4">
                    <div class="step-circle">4</div>
                    <div class="step-label">Admin Account</div>
                </div>
            </div>
            
            <!-- Loading Indicator -->
            <div id="loading" class="loading">
                <div class="spinner"></div>
                <p>Installing... Please wait, this may take a few moments.</p>
            </div>
            
            <!-- Step 1: Requirements -->
            <div id="step1" class="step-content active">
                <h2 style="margin-bottom: 20px; color: #e0e0e0;">System Requirements</h2>
                <p style="color: #888; margin-bottom: 30px;">Checking if your server meets the minimum requirements...</p>
                
                <div id="requirementsList">
                    <div style="text-align: center; padding: 40px;">
                        <div class="spinner"></div>
                        <p>Checking requirements...</p>
                    </div>
                </div>
                
                <div class="form-actions">
                    <div></div>
                    <button type="button" onclick="nextStep()" id="nextBtn1" class="btn btn-primary" disabled>
                        Next <i class="fas fa-arrow-right"></i>
                    </button>
                </div>
            </div>
            
            <!-- Step 2: Database Configuration -->
            <div id="step2" class="step-content">
                <h2 style="margin-bottom: 20px; color: #e0e0e0;">Database Configuration</h2>
                <p style="color: #888; margin-bottom: 30px;">Enter your database connection details.</p>
                
                <div id="databaseError" class="alert alert-error" style="display: none;"></div>
                <div id="databaseWarning" class="alert alert-warning" style="display: none;"></div>
                
                <form id="databaseForm">
                    <div class="grid-2">
                        <div class="form-group">
                            <label for="database_host">Database Host *</label>
                            <input type="text" id="database_host" name="database_host" value="localhost" required>
                            <small style="color: #888; font-size: 12px; display: block; margin-top: 5px;">Use 'localhost' for cPanel hosting</small>
                        </div>
                        
                        <div class="form-group">
                            <label for="database_port">Database Port *</label>
                            <input type="number" id="database_port" name="database_port" value="3306" required>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label for="database_name">Database Name *</label>
                        <input type="text" id="database_name" name="database_name" required placeholder="e.g., afrilen_portal">
                        <small style="color: #888; font-size: 12px; display: block; margin-top: 5px;">Enter the name of your existing database</small>
                    </div>
                    
                    <div class="grid-2">
                        <div class="form-group">
                            <label for="database_username">Database Username *</label>
                            <input type="text" id="database_username" name="database_username" required>
                        </div>
                        
                        <div class="form-group">
                            <label for="database_password">Database Password</label>
                            <input type="password" id="database_password" name="database_password" placeholder="Leave empty if none">
                        </div>
                    </div>
                    
                    <div class="form-group" style="margin-top: 20px;">
                        <label style="display: flex; align-items: center; cursor: pointer;">
                            <input type="checkbox" id="use_existing_database" name="use_existing_database" style="width: auto; margin-right: 10px; cursor: pointer;">
                            <span>Use existing database (database already has tables/data)</span>
                        </label>
                        <small style="color: #888; font-size: 12px; display: block; margin-top: 5px; margin-left: 28px;">
                            Check this if your database already exists and contains data. Migrations will be skipped.
                        </small>
                    </div>
                    
                    <button type="button" onclick="testDatabase()" class="btn btn-secondary" style="margin-top: 10px;">
                        <i class="fas fa-plug"></i> Test Connection
                    </button>
                </form>
                
                <div class="form-actions">
                    <button type="button" onclick="previousStep()" class="btn btn-secondary">
                        <i class="fas fa-arrow-left"></i> Previous
                    </button>
                    <button type="button" onclick="nextStep()" id="nextBtn2" class="btn btn-primary" disabled>
                        Next <i class="fas fa-arrow-right"></i>
                    </button>
                </div>
            </div>
            
            <!-- Step 3: Application Settings -->
            <div id="step3" class="step-content">
                <h2 style="margin-bottom: 20px; color: #e0e0e0;">Application Settings</h2>
                <p style="color: #888; margin-bottom: 30px;">Configure your application name and URL.</p>
                
                <form id="appForm">
                    <div class="form-group">
                        <label for="app_name">Application Name *</label>
                        <input type="text" id="app_name" name="app_name" value="Afrilen Technologies" required>
                        <small style="color: #888; font-size: 12px; display: block; margin-top: 5px;">The name of your application</small>
                    </div>
                    
                    <div class="form-group">
                        <label for="app_url">Application URL *</label>
                        <input type="url" id="app_url" name="app_url" required placeholder="https://yourdomain.com">
                        <small style="color: #888; font-size: 12px; display: block; margin-top: 5px;">The base URL where your application will be accessed</small>
                    </div>
                </form>
                
                <div class="form-actions">
                    <button type="button" onclick="previousStep()" class="btn btn-secondary">
                        <i class="fas fa-arrow-left"></i> Previous
                    </button>
                    <button type="button" onclick="nextStep()" class="btn btn-primary">
                        Next <i class="fas fa-arrow-right"></i>
                    </button>
                </div>
            </div>
            
            <!-- Step 4: Admin Account -->
            <div id="step4" class="step-content">
                <h2 style="margin-bottom: 20px; color: #e0e0e0;">Create Admin Account</h2>
                <p style="color: #888; margin-bottom: 30px;">Create the default administrator account.</p>
                
                <form id="adminForm">
                    <div class="form-group">
                        <label for="admin_name">Admin Name *</label>
                        <input type="text" id="admin_name" name="admin_name" value="Admin" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="admin_email">Admin Email *</label>
                        <input type="email" id="admin_email" name="admin_email" required placeholder="admin@example.com">
                    </div>
                    
                    <div class="grid-2">
                        <div class="form-group">
                            <label for="admin_password">Admin Password *</label>
                            <input type="password" id="admin_password" name="admin_password" required minlength="8">
                            <small style="color: #888; font-size: 12px; display: block; margin-top: 5px;">Minimum 8 characters</small>
                        </div>
                        
                        <div class="form-group">
                            <label for="admin_password_confirmation">Confirm Password *</label>
                            <input type="password" id="admin_password_confirmation" name="admin_password_confirmation" required minlength="8">
                        </div>
                    </div>
                </form>
                
                <div class="form-actions">
                    <button type="button" onclick="previousStep()" class="btn btn-secondary">
                        <i class="fas fa-arrow-left"></i> Previous
                    </button>
                    <button type="button" onclick="startInstallation()" class="btn btn-success">
                        <i class="fas fa-check"></i> Complete Installation
                    </button>
                </div>
            </div>
            
            <!-- Success Message -->
            <div id="successMessage" class="step-content" style="text-align: center; padding: 40px;">
                <div style="font-size: 64px; color: #6bff6b; margin-bottom: 20px;">
                    <i class="fas fa-check-circle"></i>
                </div>
                <h2 style="color: #e0e0e0; margin-bottom: 15px;">Installation Complete!</h2>
                <p style="color: #888; margin-bottom: 30px;">Your application has been successfully installed.</p>
                <div style="background: #1a1a1a; padding: 20px; border-radius: 5px; margin-bottom: 30px; text-align: left;">
                    <p style="color: #e0e0e0; margin-bottom: 10px;"><strong>Admin Login Details:</strong></p>
                    <p style="color: #888; margin: 5px 0;"><strong>Email:</strong> <span id="successEmail" style="color: #4a9eff;"></span></p>
                    <p style="color: #888; margin: 5px 0;"><strong>Password:</strong> The password you set during installation</p>
                </div>
                <a href="/admin" class="btn btn-primary" style="text-decoration: none;">
                    <i class="fas fa-sign-in-alt"></i> Go to Admin Login
                </a>
            </div>
        </div>
    </div>
    
    <script>
        let currentStep = 1;
        let requirementsMet = false;
        let databaseConnected = false;
        
        // Check requirements on page load
        document.addEventListener('DOMContentLoaded', function() {
            checkRequirements();
        });
        
        function checkRequirements() {
            fetch('/setup/check-requirements')
                .then(response => response.json())
                .then(data => {
                    displayRequirements(data.requirements);
                    requirementsMet = data.all_met;
                    document.getElementById('nextBtn1').disabled = !requirementsMet;
                })
                .catch(error => {
                    console.error('Error checking requirements:', error);
                    document.getElementById('requirementsList').innerHTML = 
                        '<div class="alert alert-error">Error checking requirements. Please refresh the page.</div>';
                });
        }
        
        function displayRequirements(requirements) {
            let html = '';
            
            // PHP Version
            html += `
                <div class="requirement-item">
                    <div>
                        <strong>PHP Version</strong>
                        <div style="color: #888; font-size: 12px; margin-top: 5px;">
                            Required: ${requirements.php_version.required}+ | Current: ${requirements.php_version.current}
                        </div>
                    </div>
                    <span class="requirement-status ${requirements.php_version.met ? 'met' : 'failed'}">
                        ${requirements.php_version.met ? '✓ Met' : '✗ Failed'}
                    </span>
                </div>
            `;
            
            // Extensions
            html += '<div style="margin-top: 20px;"><strong style="display: block; margin-bottom: 10px;">PHP Extensions:</strong>';
            for (let [ext, met] of Object.entries(requirements.extensions)) {
                html += `
                    <div class="requirement-item">
                        <span>${ext}</span>
                        <span class="requirement-status ${met ? 'met' : 'failed'}">
                            ${met ? '✓' : '✗'}
                        </span>
                    </div>
                `;
            }
            html += '</div>';
            
            // Permissions
            html += '<div style="margin-top: 20px;"><strong style="display: block; margin-bottom: 10px;">File Permissions:</strong>';
            for (let [permission, met] of Object.entries(requirements.permissions)) {
                html += `
                    <div class="requirement-item">
                        <span>${permission.charAt(0).toUpperCase() + permission.slice(1)}</span>
                        <span class="requirement-status ${met ? 'met' : 'failed'}">
                            ${met ? '✓ Writable' : '✗ Not Writable'}
                        </span>
                    </div>
                `;
            }
            html += '</div>';
            
            document.getElementById('requirementsList').innerHTML = html;
        }
        
        function testDatabase() {
            const form = document.getElementById('databaseForm');
            const formData = new FormData(form);
            
            const data = {
                host: formData.get('database_host'),
                port: formData.get('database_port'),
                database: formData.get('database_name'),
                username: formData.get('database_username'),
                password: formData.get('database_password'),
            };
            
            const errorDiv = document.getElementById('databaseError');
            const warningDiv = document.getElementById('databaseWarning');
            errorDiv.style.display = 'none';
            warningDiv.style.display = 'none';
            
            fetch('/setup/test-database', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                },
                body: JSON.stringify(data)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    errorDiv.className = 'alert alert-success';
                    errorDiv.textContent = '✓ ' + data.message;
                    errorDiv.style.display = 'block';
                    databaseConnected = true;
                    document.getElementById('nextBtn2').disabled = false;
                    
                    // Build warning message
                    let warningMessage = '';
                    
                    // If database has tables, suggest using existing database
                    if (data.has_tables) {
                        warningMessage += '⚠ <strong>Existing database detected!</strong> This database already has ' + data.table_count + ' table(s). ';
                        
                        if (data.has_users_table) {
                            warningMessage += 'The database appears to be already set up. ';
                            // Auto-check the checkbox if users table exists
                            document.getElementById('use_existing_database').checked = true;
                        }
                        
                        warningMessage += 'If you want to use this existing database, please check the "Use existing database" checkbox above. ';
                        warningMessage += 'Otherwise, migrations will try to add missing tables.';
                    }
                    
                    // Show migration status
                    if (data.migration_status === 'pending' && data.pending_migrations_count > 0) {
                        if (warningMessage) warningMessage += '<br><br>';
                        warningMessage += '📋 <strong>Migration Status:</strong> ' + data.pending_migrations_count + ' pending migration(s) detected. ';
                        
                        if (data.has_migrations_table) {
                            warningMessage += 'These migrations will be run during installation to add any missing tables.';
                        } else {
                            warningMessage += 'A migrations table will be created and all migrations will be run.';
                        }
                        
                        // Show pending migrations list (first 5)
                        if (data.pending_migrations && data.pending_migrations.length > 0) {
                            const migrationsToShow = data.pending_migrations.slice(0, 5);
                            warningMessage += '<br><small style="display: block; margin-top: 8px; color: #666;">Pending: ' + 
                                migrationsToShow.join(', ') + 
                                (data.pending_migrations.length > 5 ? ' ...' : '') + '</small>';
                        }
                    } else if (data.migration_status === 'up_to_date') {
                        if (warningMessage) warningMessage += '<br><br>';
                        warningMessage += '✅ <strong>Migration Status:</strong> All migrations are up to date.';
                    }
                    
                    if (warningMessage) {
                        warningDiv.className = 'alert alert-warning';
                        warningDiv.innerHTML = warningMessage;
                        warningDiv.style.display = 'block';
                    }
                } else {
                    errorDiv.className = 'alert alert-error';
                    errorDiv.textContent = '✗ ' + data.message;
                    errorDiv.style.display = 'block';
                    databaseConnected = false;
                    document.getElementById('nextBtn2').disabled = true;
                }
            })
            .catch(error => {
                errorDiv.className = 'alert alert-error';
                let errorMessage = error.message;
                // If it's a JSON parse error, provide more helpful message
                if (errorMessage.includes('JSON') || errorMessage.includes('DOCTYPE')) {
                    errorMessage = 'Server error: The server returned an error page instead of JSON. This might be a CSRF token issue or server configuration problem. Please check the browser console and server logs.';
                }
                errorDiv.textContent = '✗ Error: ' + errorMessage;
                errorDiv.style.display = 'block';
                console.error('Database test error:', error);
            });
        }
        
        function nextStep() {
            if (currentStep < 4) {
                // Validate current step
                if (currentStep === 2 && !databaseConnected) {
                    alert('Please test the database connection first.');
                    return;
                }
                
                document.getElementById('step' + currentStep).classList.remove('active');
                document.querySelector(`.step[data-step="${currentStep}"]`).classList.remove('active');
                document.querySelector(`.step[data-step="${currentStep}"]`).classList.add('completed');
                
                currentStep++;
                
                document.getElementById('step' + currentStep).classList.add('active');
                document.querySelector(`.step[data-step="${currentStep}"]`).classList.add('active');
            }
        }
        
        function previousStep() {
            if (currentStep > 1) {
                document.getElementById('step' + currentStep).classList.remove('active');
                document.querySelector(`.step[data-step="${currentStep}"]`).classList.remove('active');
                document.querySelector(`.step[data-step="${currentStep}"]`).classList.remove('completed');
                
                currentStep--;
                
                document.getElementById('step' + currentStep).classList.add('active');
                document.querySelector(`.step[data-step="${currentStep}"]`).classList.add('active');
            }
        }
        
        function startInstallation() {
            const adminForm = document.getElementById('adminForm');
            const appForm = document.getElementById('appForm');
            const databaseForm = document.getElementById('databaseForm');
            
            const adminData = new FormData(adminForm);
            const appData = new FormData(appForm);
            const databaseData = new FormData(databaseForm);
            
            // Validate password confirmation
            if (adminData.get('admin_password') !== adminData.get('admin_password_confirmation')) {
                alert('Password confirmation does not match!');
                return;
            }
            
            const installData = {
                database_host: databaseData.get('database_host'),
                database_port: databaseData.get('database_port'),
                database_name: databaseData.get('database_name'),
                database_username: databaseData.get('database_username'),
                database_password: databaseData.get('database_password'),
                use_existing_database: databaseData.get('use_existing_database') === 'on',
                admin_name: adminData.get('admin_name'),
                admin_email: adminData.get('admin_email'),
                admin_password: adminData.get('admin_password'),
                admin_password_confirmation: adminData.get('admin_password_confirmation'),
                app_name: appData.get('app_name'),
                app_url: appData.get('app_url'),
            };
            
            // Show loading
            document.getElementById('step' + currentStep).classList.remove('active');
            document.getElementById('loading').classList.add('active');
            
            fetch('/setup/install', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                },
                body: JSON.stringify(installData)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    document.getElementById('loading').classList.remove('active');
                    document.getElementById('successEmail').textContent = data.admin_email;
                    document.getElementById('successMessage').classList.add('active');
                    document.querySelector(`.step[data-step="${currentStep}"]`).classList.add('completed');
                } else {
                    alert('Installation failed: ' + data.message);
                    document.getElementById('loading').classList.remove('active');
                    document.getElementById('step' + currentStep).classList.add('active');
                }
            })
            .catch(error => {
                let errorMessage = error.message;
                // If it's a JSON parse error, provide more helpful message
                if (errorMessage.includes('JSON') || errorMessage.includes('DOCTYPE')) {
                    errorMessage = 'Server error: The server returned an error page instead of JSON. Please check the server logs (storage/logs/laravel.log) for details.';
                }
                alert('Installation failed: ' + errorMessage);
                document.getElementById('loading').classList.remove('active');
                document.getElementById('step' + currentStep).classList.add('active');
                console.error('Installation error:', error);
            });
        }
    </script>
</body>
</html>

