<?php
// New Modern Installer for NCS Billing System
session_start();

// Set longer execution time and memory limit for large SQL operations
set_time_limit(0); // No time limit
ini_set('memory_limit', '1024M'); // 1GB
ini_set('max_execution_time', 0);
ini_set('max_input_time', 0);

// Clear any existing session data to prevent conflicts
session_destroy();
session_start();

// Define lock file path
define('INSTALLER_LOCK_FILE', __DIR__ . '/../../install.lock');

// Check if installation is locked
if (file_exists(INSTALLER_LOCK_FILE)) {
    die('<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Installation Locked - NCS Billing System</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: \'Segoe UI\', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        .lock-container {
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            max-width: 600px;
            width: 100%;
            padding: 40px;
            text-align: center;
        }
        .lock-icon {
            font-size: 80px;
            color: #e74c3c;
            margin-bottom: 20px;
        }
        .lock-container h1 {
            color: #2c3e50;
            margin-bottom: 20px;
            font-size: 2rem;
        }
        .lock-container p {
            color: #666;
            font-size: 1.1rem;
            margin-bottom: 30px;
            line-height: 1.6;
        }
        .warning-box {
            background: #fff3cd;
            border: 2px solid #ffc107;
            border-radius: 10px;
            padding: 20px;
            margin: 20px 0;
            text-align: left;
        }
        .warning-box h4 {
            color: #856404;
            margin-bottom: 15px;
            text-align: center;
        }
        .warning-box ul {
            color: #856404;
            margin-left: 20px;
        }
        .warning-box li {
            margin-bottom: 10px;
            font-size: 0.95rem;
        }
        .info-box {
            background: #d1ecf1;
            border: 2px solid #0c5460;
            border-radius: 10px;
            padding: 20px;
            margin: 20px 0;
            text-align: center;
        }
        .info-box strong {
            color: #0c5460;
            font-size: 1.1rem;
        }
        .contact-info {
            margin-top: 20px;
            padding-top: 20px;
            border-top: 2px solid #e0e0e0;
            color: #666;
            font-size: 0.9rem;
        }
        .contact-info a {
            color: #3498db;
            text-decoration: none;
            font-weight: 600;
        }
        .file-path {
            background: #f8f9fa;
            padding: 10px;
            border-radius: 5px;
            font-family: monospace;
            font-size: 0.9rem;
            color: #2c3e50;
            margin: 10px 0;
            word-break: break-all;
        }
    </style>
</head>
<body>
    <div class="lock-container">
        <div class="lock-icon">
            <i class="fas fa-lock"></i>
        </div>
        <h1>Installation Already Completed</h1>
        <p>Your NCS Billing System has already been installed and is currently locked to prevent re-installation.</p>
        
        <div class="warning-box">
            <h4><i class="fas fa-exclamation-triangle"></i> Important Security Notice</h4>
            <ul>
                <li>Do not delete the lock file unless you intend to perform a fresh installation</li>
                <li>Deleting the lock file will allow re-installation which will <strong>overwrite your existing database</strong></li>
                <li>Make sure to backup your database before re-installing</li>
                <li>The lock file prevents accidental re-installation which would cause data loss</li>
            </ul>
        </div>

        <div class="info-box">
            <strong>To re-install the application:</strong><br>
            Delete the lock file located at:<br>
            <div class="file-path">' . realpath(INSTALLER_LOCK_FILE) . '</div>
        </div>

        <div class="contact-info">
            <p><i class="fas fa-shield-alt"></i> This lock protects your installation from being overwritten accidentally.</p>
            <p>Need help? Contact support: <a href="mailto:admin@nanzige.com">admin@nanzige.com</a></p>
        </div>
    </div>
</body>
</html>');
}

// Include database library
require_once 'includes/databaseLibrary.php';

// Auto-detect domain and base URL
function getAutoDetectedUrl() {
    $protocol = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    $host = $_SERVER['HTTP_HOST'];
    $requestUri = $_SERVER['REQUEST_URI'];
    
    // Find the position of /setup/install/ in the URI
    $setupPos = strpos($requestUri, '/setup/install/');
    
    if ($setupPos !== false) {
        // Extract everything before /setup/install/
        $basePath = substr($requestUri, 0, $setupPos);
    } else {
        // Fallback: try to find /setup/install without trailing slash
        $setupPos = strpos($requestUri, '/setup/install');
        if ($setupPos !== false) {
            $basePath = substr($requestUri, 0, $setupPos);
        } else {
            // If no setup/install found, use the full path and remove any filename
            $basePath = dirname($requestUri);
        }
    }
    
    // Clean up the path
    $basePath = rtrim($basePath, '/');
    
    // Handle different scenarios
    if (empty($basePath) || $basePath === '.' || $basePath === '/') {
        // Root domain (e.g., https://nanzige.com)
        $basePath = '';
    } else {
        // Subdirectory (e.g., /ncsbillingbook)
        $basePath = '/' . ltrim($basePath, '/');
    }
    
    $fullUrl = $protocol . $host . $basePath;
    
    // Clean up the URL - remove trailing slash unless it's root
    if ($basePath !== '') {
        $fullUrl = rtrim($fullUrl, '/');
    }
    
    return $fullUrl;
}

$urlWb = getAutoDetectedUrl();

// Debug output (uncomment for testing)
// if (isset($_GET['debug'])) {
//     echo "Request URI: " . $_SERVER['REQUEST_URI'] . "<br>";
//     echo "Detected URL: " . $urlWb . "<br>";
//     echo "Host: " . $_SERVER['HTTP_HOST'] . "<br>";
//     exit;
// }

// Handle installation process
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action'])) {
    header('Content-Type: application/json');
    
    $action = $_POST['action'];
    $response = ['success' => false, 'message' => '', 'step' => 0, 'progress' => 0];
    
    // Sanitize all POST data
    $cleanData = [];
    foreach ($_POST as $key => $value) {
        if ($key !== 'action') {
            $cleanData[$key] = htmlspecialchars(strip_tags(trim($value)), ENT_QUOTES, 'UTF-8');
        }
    }
    
    try {
        switch ($action) {
            case 'validate_database':
                $response = validateDatabase($cleanData);
                break;
            case 'create_database':
                $response = createDatabase($cleanData);
                break;
            case 'install_tables':
                $response = installTables($cleanData);
                break;
            case 'create_admin':
                $response = createAdminUser($cleanData);
                break;
            case 'finalize':
                $response = finalizeInstallation($cleanData);
                break;
            default:
                $response['message'] = 'Invalid action';
        }
    } catch (Exception $e) {
        $response['message'] = 'Error: ' . $e->getMessage();
        error_log("Installation error: " . $e->getMessage());
    }
    
    echo json_encode($response);
    exit;
}

function validateDatabase($data) {
    $host = $data['hostname'] ?? 'localhost';
    $username = $data['username'] ?? 'root';
    $password = $data['password'] ?? '';
    $database = $data['database'] ?? 'ncs';
    
    $connection = @mysqli_connect($host, $username, $password);
    
    if (!$connection) {
        return [
            'success' => false,
            'message' => 'Failed to connect to database server. Please check your credentials.',
            'step' => 1,
            'progress' => 0
        ];
    }
    
    mysqli_close($connection);
    
    return [
        'success' => true,
        'message' => 'Database connection successful!',
        'step' => 2,
        'progress' => 20
    ];
}

function createDatabase($data) {
    $host = $data['hostname'] ?? 'localhost';
    $username = $data['username'] ?? 'root';
    $password = $data['password'] ?? '';
    $database = $data['database'] ?? 'ncs';
    
    $connection = @mysqli_connect($host, $username, $password);
    
    if (!$connection) {
        return [
            'success' => false,
            'message' => 'Failed to connect to database server.',
            'step' => 2,
            'progress' => 20
        ];
    }
    
    $result = mysqli_query($connection, "CREATE DATABASE IF NOT EXISTS `$database`");
    
    if (!$result) {
        mysqli_close($connection);
        return [
            'success' => false,
            'message' => 'Failed to create database: ' . mysqli_error($connection),
            'step' => 2,
            'progress' => 20
        ];
    }
    
    mysqli_close($connection);
    
    return [
        'success' => true,
        'message' => 'Database created successfully!',
        'step' => 3,
        'progress' => 40
    ];
}

function installTables($data) {
    $host = $data['hostname'] ?? 'localhost';
    $username = $data['username'] ?? 'root';
    $password = $data['password'] ?? '';
    $database = $data['database'] ?? 'ncs';
    
    $connection = @mysqli_connect($host, $username, $password, $database);
    
    if (!$connection) {
        return [
            'success' => false,
            'message' => 'Failed to connect to database.',
            'step' => 3,
            'progress' => 40
        ];
    }
    
    // Set longer timeout for large operations
    mysqli_query($connection, "SET SESSION wait_timeout = 600");
    mysqli_query($connection, "SET SESSION interactive_timeout = 600");
    
    // Read SQL file
    $sqlFile = 'billing.sql';
    $sqlContent = file_get_contents($sqlFile);
    
    if ($sqlContent === false) {
        mysqli_close($connection);
        return [
            'success' => false,
            'message' => 'Failed to read SQL file.',
            'step' => 3,
            'progress' => 40
        ];
    }
    
    // Use mysqli_multi_query for better performance
    $result = mysqli_multi_query($connection, $sqlContent);
    
    if ($result) {
        // Clear any remaining results
        while (mysqli_more_results($connection)) {
            mysqli_next_result($connection);
        }
        
        mysqli_close($connection);
        return [
            'success' => true,
            'message' => 'Database tables installed successfully!',
            'step' => 4,
            'progress' => 70
        ];
    } else {
        $error = mysqli_error($connection);
        mysqli_close($connection);
        return [
            'success' => false,
            'message' => 'Failed to install database tables: ' . $error,
            'step' => 3,
            'progress' => 40
        ];
    }
}

function createAdminUser($data) {
    $host = $data['hostname'] ?? 'localhost';
    $username = $data['username'] ?? 'root';
    $password = $data['password'] ?? '';
    $database = $data['database'] ?? 'ncs';
    
    // Use default admin credentials
    $adminEmail = 'admin@example.com';
    $adminPassword = '123456';
    
    $connection = @mysqli_connect($host, $username, $password, $database);
    
    if (!$connection) {
        return [
            'success' => false,
            'message' => 'Failed to connect to database.',
            'step' => 4,
            'progress' => 70
        ];
    }
    
    // Escape data for SQL
    $adminEmail = mysqli_real_escape_string($connection, $adminEmail);
    $hashedPassword = password_hash($adminPassword, PASSWORD_DEFAULT);
    $hashedPassword = mysqli_real_escape_string($connection, $hashedPassword);
    
    // Update admin user with proper escaping
    $updateQuery = "UPDATE `db_users` SET `email` = '$adminEmail', `password` = '$hashedPassword' WHERE `id` = '1'";
    
    if (mysqli_query($connection, $updateQuery)) {
        mysqli_close($connection);
        return [
            'success' => true,
            'message' => 'Admin user configured with default credentials!',
            'step' => 5,
            'progress' => 90
        ];
    } else {
        $error = mysqli_error($connection);
        mysqli_close($connection);
        return [
            'success' => false,
            'message' => 'Failed to create admin user: ' . $error,
            'step' => 4,
            'progress' => 70
        ];
    }
}

function finalizeInstallation($data) {
    $host = $data['hostname'] ?? 'localhost';
    $username = $data['username'] ?? 'root';
    $password = $data['password'] ?? '';
    $database = $data['database'] ?? 'ncs';
    $siteUrl = $data['site_url'] ?? '';
    
    $connection = @mysqli_connect($host, $username, $password, $database);
    
    if (!$connection) {
        return [
            'success' => false,
            'message' => 'Failed to connect to database.',
            'step' => 5,
            'progress' => 90
        ];
    }
    
    // Escape data for SQL
    $siteUrl = mysqli_real_escape_string($connection, $siteUrl);
    
    // Update site settings with proper escaping
    $updateQuery = "UPDATE `db_sitesettings` SET `domain` = '$siteUrl', `version` = '3.4' WHERE `id` = '1'";
    
    if (mysqli_query($connection, $updateQuery)) {
        mysqli_close($connection);
        
        // Write database configuration
        $dbConfigPath = '../../application/config/database.php';
        
        // Debug: Show current working directory and file path
        $currentDir = getcwd();
        $absolutePath = realpath($dbConfigPath);
        
        // Check if file exists and is readable
        if (!file_exists($dbConfigPath)) {
            throw new Exception('Database config file not found. Current dir: ' . $currentDir . ', Looking for: ' . $dbConfigPath . ', Absolute path: ' . $absolutePath);
        }
        
        if (!is_readable($dbConfigPath)) {
            throw new Exception('Database config file is not readable: ' . $dbConfigPath);
        }
        
        $dbConfigContent = file_get_contents($dbConfigPath);
        
        if ($dbConfigContent === false) {
            throw new Exception('Failed to read database config file');
        }
        
        // Replace placeholders with actual values
        $dbConfigContent = str_replace('%HOSTNAME%', $host, $dbConfigContent);
        $dbConfigContent = str_replace('%USERNAME%', $username, $dbConfigContent);
        $dbConfigContent = str_replace('%PASSWORD%', $password, $dbConfigContent);
        $dbConfigContent = str_replace('%DATABASE%', $database, $dbConfigContent);
        
        // Check if file is writable
        if (!is_writable($dbConfigPath)) {
            throw new Exception('Database config file is not writable: ' . $dbConfigPath);
        }
        
        // Write the updated configuration
        if (file_put_contents($dbConfigPath, $dbConfigContent) === false) {
            throw new Exception('Failed to write database config file');
        }
        
        // Create lock file to prevent re-installation
        $lockContent = "Installation completed on: " . date('Y-m-d H:i:s') . "\n";
        $lockContent .= "Database: " . $database . "\n";
        $lockContent .= "Site URL: " . $siteUrl . "\n";
        $lockContent .= "\n";
        $lockContent .= "WARNING: Do not delete this file unless you want to re-install the application.\n";
        $lockContent .= "Re-installation will overwrite your existing database and cause data loss!\n";
        
        if (file_put_contents(INSTALLER_LOCK_FILE, $lockContent) === false) {
            // Don't throw error, just log it
            error_log('Failed to create installer lock file at: ' . INSTALLER_LOCK_FILE);
        }
        
        return [
            'success' => true,
            'message' => 'Installation completed successfully!',
            'step' => 6,
            'progress' => 100,
            'redirect_url' => $siteUrl . '/login'
        ];
    } else {
        $error = mysqli_error($connection);
        mysqli_close($connection);
        return [
            'success' => false,
            'message' => 'Failed to finalize installation: ' . $error,
            'step' => 5,
            'progress' => 90
        ];
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>NCS Billing System - Installation</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }

        .installer-container {
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            max-width: 800px;
            width: 100%;
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #2c3e50, #34495e);
            color: white;
            padding: 30px;
            text-align: center;
        }

        .header h1 {
            font-size: 2.5rem;
            margin-bottom: 10px;
            font-weight: 300;
        }

        .header p {
            font-size: 1.1rem;
            opacity: 0.9;
        }

        .progress-container {
            padding: 30px;
        }

        .step-indicator {
            display: flex;
            justify-content: space-between;
            margin-bottom: 25px;
            position: relative;
        }

        .step-indicator::before {
            content: '';
            position: absolute;
            top: 20px;
            left: 0;
            right: 0;
            height: 2px;
            background: #e0e0e0;
            z-index: 1;
        }

        .step {
            display: flex;
            flex-direction: column;
            align-items: center;
            position: relative;
            z-index: 2;
            background: white;
            padding: 0 10px;
        }

        .step-number {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: #e0e0e0;
            color: #666;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            margin-bottom: 10px;
            transition: all 0.3s ease;
        }

        .step.active .step-number {
            background: #3498db;
            color: white;
        }

        .step.completed .step-number {
            background: #27ae60;
            color: white;
        }

        .step-label {
            font-size: 0.9rem;
            text-align: center;
            color: #666;
            font-weight: 500;
        }

        .step.active .step-label {
            color: #3498db;
        }

        .step.completed .step-label {
            color: #27ae60;
        }

        .progress-bar {
            width: 100%;
            height: 6px;
            background: #e0e0e0;
            border-radius: 3px;
            overflow: hidden;
            margin-bottom: 20px;
        }

        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #3498db, #2ecc71);
            width: 0%;
            transition: width 0.5s ease;
        }

        .form-container {
            display: none;
        }

        .form-container.active {
            display: block;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: 600;
            color: #2c3e50;
            font-size: 0.9rem;
        }

        .form-group input {
            width: 100%;
            padding: 10px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 0.95rem;
            transition: border-color 0.3s ease;
        }

        .form-group input:focus {
            outline: none;
            border-color: #3498db;
        }

        .btn {
            background: linear-gradient(135deg, #3498db, #2980b9);
            color: white;
            border: none;
            padding: 12px 25px;
            border-radius: 8px;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            width: 100%;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(52, 152, 219, 0.4);
        }

        .btn:disabled {
            background: #bdc3c7;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }

        .status-message {
            text-align: center;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 15px;
            font-weight: 500;
            font-size: 0.95rem;
        }

        .status-message.success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .status-message.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .status-message.info {
            background: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }

        .loading-spinner {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid #3498db;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-right: 10px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .success-screen {
            text-align: center;
            padding: 40px;
        }

        .success-icon {
            font-size: 4rem;
            color: #27ae60;
            margin-bottom: 20px;
        }

        .success-screen h2 {
            color: #2c3e50;
            margin-bottom: 20px;
        }

        .success-screen p {
            color: #666;
            margin-bottom: 30px;
        }

        .btn-success {
            background: linear-gradient(135deg, #27ae60, #2ecc71);
        }

        .btn-success:hover {
            box-shadow: 0 5px 15px rgba(39, 174, 96, 0.4);
        }
    </style>
</head>
<body>
    <div class="installer-container">
        <div class="header">
            <h1><i class="fas fa-cube"></i> NCS Billing System</h1>
            <p>Complete POS & Inventory Management Solution</p>
        </div>

        <div class="progress-container">
            <!-- Auto-detection Notice -->
            <div class="status-message info" style="margin-bottom: 20px;">
                <i class="fas fa-magic"></i> <strong>Smart Detection:</strong> Your domain and URL have been automatically detected. No need to change the Site URL unless you're using a different domain.
            </div>
            
            <!-- Step Indicator -->
            <div class="step-indicator">
                <div class="step active" id="step-1">
                    <div class="step-number">1</div>
                    <div class="step-label">Database</div>
                </div>
                <div class="step" id="step-2">
                    <div class="step-number">2</div>
                    <div class="step-label">Create DB</div>
                </div>
                <div class="step" id="step-3">
                    <div class="step-number">3</div>
                    <div class="step-label">Install Tables</div>
                </div>
                <div class="step" id="step-4">
                    <div class="step-number">4</div>
                    <div class="step-label">Configure</div>
                </div>
                <div class="step" id="step-5">
                    <div class="step-number">5</div>
                    <div class="step-label">Complete</div>
                </div>
            </div>

            <!-- Progress Bar -->
            <div class="progress-bar">
                <div class="progress-fill" id="progress-fill"></div>
            </div>

            <!-- Status Message -->
            <div id="status-message" class="status-message info" style="display: none;">
                <span id="status-text">Ready to start installation</span>
            </div>

            <!-- Step 1: Database Configuration -->
            <div class="form-container active" id="form-step-1">
                <h3 style="margin-bottom: 20px; color: #2c3e50;">Database Configuration</h3>
                <form id="install-form">
                    <div class="form-group">
                        <label for="hostname">Database Host *</label>
                        <input type="text" id="hostname" name="hostname" value="localhost" placeholder="localhost or 127.0.0.1" required>
                    </div>
                    <div class="form-group">
                        <label for="username">Database Username *</label>
                        <input type="text" id="username" name="username" value="root" placeholder="root or your MySQL username" required>
                    </div>
                    <div class="form-group">
                        <label for="password">Database Password</label>
                        <input type="password" id="password" name="password" placeholder="Leave empty if no password">
                    </div>
                    <div class="form-group">
                        <label for="database">Database Name *</label>
                        <input type="text" id="database" name="database" placeholder="ncsbillingbook or your preferred name" required>
                    </div>
                    <div class="form-group">
                        <label for="site_url">Site URL *</label>
                        <input type="url" id="site_url" name="site_url" value="<?= $urlWb ?>" required readonly style="background-color: #f8f9fa; cursor: not-allowed;">
                        <small style="color: #666; font-size: 0.9rem; margin-top: 5px; display: block;">
                            <i class="fas fa-info-circle"></i> Auto-detected from your current domain
                        </small>
                    </div>
                    <button type="submit" class="btn" id="install-btn">
                        <i class="fas fa-play"></i> Start Installation
                    </button>
                </form>
            </div>

            <!-- Success Screen -->
            <div class="form-container" id="success-screen">
                <div class="success-screen">
                    <div class="success-icon">
                        <i class="fas fa-check-circle"></i>
                    </div>
                    <h2>Installation Complete!</h2>
                    <p>NCS Billing System has been successfully installed and configured.</p>
                    
                    <!-- Login Credentials -->
                    <div style="background: #f8f9fa; border: 2px solid #e9ecef; border-radius: 10px; padding: 20px; margin: 20px 0; text-align: left;">
                        <h4 style="color: #2c3e50; margin-bottom: 15px; text-align: center;">
                            <i class="fas fa-key"></i> Default Login Credentials
                        </h4>
                        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                            <strong>Email:</strong>
                            <code style="background: #e9ecef; padding: 5px 10px; border-radius: 5px; font-size: 1.1rem;">admin@example.com</code>
                        </div>
                        <div style="display: flex; justify-content: space-between; align-items: center;">
                            <strong>Password:</strong>
                            <code style="background: #e9ecef; padding: 5px 10px; border-radius: 5px; font-size: 1.1rem;">123456</code>
                        </div>
                        <div style="text-align: center; margin-top: 15px; color: #6c757d; font-size: 0.9rem;">
                            <i class="fas fa-info-circle"></i> Please change these credentials after your first login
                        </div>
                    </div>
                    
                    <!-- Lock File Info -->
                    <div style="background: #d1ecf1; border: 2px solid #0c5460; border-radius: 10px; padding: 15px; margin: 20px 0;">
                        <h5 style="color: #0c5460; margin-bottom: 10px; text-align: center;">
                            <i class="fas fa-shield-alt"></i> Installation Locked
                        </h5>
                        <p style="color: #0c5460; font-size: 0.9rem; margin: 0; text-align: center;">
                            A lock file has been created to prevent accidental re-installation.<br>
                            To re-install, delete the <code>install.lock</code> file in the setup directory.
                        </p>
                    </div>
                    
                    <button class="btn btn-success" id="go-to-login">
                        <i class="fas fa-sign-in-alt"></i> Go to Login Page
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script>
        let currentStep = 1;
        let installationData = {};

        document.getElementById('install-form').addEventListener('submit', function(e) {
            e.preventDefault();
            startInstallation();
        });

        document.getElementById('go-to-login').addEventListener('click', function() {
            window.location.href = installationData.site_url + '/login';
        });

        async function startInstallation() {
            // Collect form data
            const formData = new FormData(document.getElementById('install-form'));
            installationData = Object.fromEntries(formData.entries());

            // Disable all form fields
            disableFormFields();

            // Disable form button
            document.getElementById('install-btn').disabled = true;
            document.getElementById('install-btn').innerHTML = '<span class="loading-spinner"></span>Starting Installation...';

            // Start installation steps
            await runInstallationStep('validate_database', 'Validating database connection...');
            await runInstallationStep('create_database', 'Creating database...');
            await runInstallationStep('install_tables', 'Installing database tables (this may take a few minutes)...');
            await runInstallationStep('create_admin', 'Configuring admin user...');
            await runInstallationStep('finalize', 'Finalizing installation...');

            // Show success screen
            showSuccessScreen();
        }

        function disableFormFields() {
            // Get all form inputs
            const inputs = document.querySelectorAll('#install-form input, #install-form select, #install-form textarea');
            
            inputs.forEach(input => {
                input.disabled = true;
                input.style.backgroundColor = '#f8f9fa';
                input.style.cursor = 'not-allowed';
                input.style.opacity = '0.7';
            });

            // Add visual indicator
            const form = document.getElementById('install-form');
            form.style.position = 'relative';
            
            // Create overlay
            const overlay = document.createElement('div');
            overlay.id = 'form-overlay';
            overlay.style.cssText = `
                position: absolute;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background: rgba(248, 249, 250, 0.8);
                display: flex;
                align-items: center;
                justify-content: center;
                z-index: 10;
                border-radius: 10px;
            `;
            
            overlay.innerHTML = `
                <div style="text-align: center; color: #6c757d;">
                    <div class="loading-spinner" style="margin: 0 auto 10px;"></div>
                    <div style="font-weight: 600;">Installation in Progress...</div>
                    <div style="font-size: 0.9rem;">Please wait while we set up your system</div>
                </div>
            `;
            
            form.style.position = 'relative';
            form.appendChild(overlay);
        }

        async function runInstallationStep(action, message) {
            showStatus(message, 'info');
            
            const response = await fetch('', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    action: action,
                    ...installationData
                })
            });

            const result = await response.json();

            if (result.success) {
                updateStep(result.step, result.progress);
                showStatus(result.message, 'success');
            } else {
                showStatus(result.message, 'error');
                throw new Error(result.message);
            }

            // Add delay for better UX
            await new Promise(resolve => setTimeout(resolve, 2000));
        }

        function updateStep(step, progress) {
            // Update progress bar
            document.getElementById('progress-fill').style.width = progress + '%';

            // Update step indicators
            for (let i = 1; i <= 5; i++) {
                const stepElement = document.getElementById(`step-${i}`);
                if (i < step) {
                    stepElement.classList.add('completed');
                    stepElement.classList.remove('active');
                } else if (i === step) {
                    stepElement.classList.add('active');
                    stepElement.classList.remove('completed');
                } else {
                    stepElement.classList.remove('active', 'completed');
                }
            }
        }

        function showStatus(message, type) {
            const statusElement = document.getElementById('status-message');
            const statusText = document.getElementById('status-text');
            
            statusElement.className = `status-message ${type}`;
            statusText.textContent = message;
            statusElement.style.display = 'block';
        }

        function showSuccessScreen() {
            document.getElementById('form-step-1').classList.remove('active');
            document.getElementById('success-screen').classList.add('active');
        }
    </script>
</body>
</html>
