<?php
error_reporting(1);
$db_config_path = '../application/config/database.php';

// ==================== SERVER REQUIREMENTS CHECK ====================
$serverRequirements = [
    'all_met' => true,
    'checks' => [
        'PHP Version (>= 7.4)' => [
            'status' => version_compare(PHP_VERSION, '7.4.0', '>='),
            'message' => 'Current: ' . PHP_VERSION
        ],
        'MySQLi Extension' => [
            'status' => extension_loaded('mysqli'),
            'message' => extension_loaded('mysqli') ? 'Loaded' : 'Not loaded'
        ],
        'cURL Extension' => [
            'status' => extension_loaded('curl'),
            'message' => extension_loaded('curl') ? 'Loaded' : 'Not loaded'
        ],
        'GD Extension' => [
            'status' => extension_loaded('gd'),
            'message' => extension_loaded('gd') ? 'Loaded' : 'Not loaded'
        ],
        'OpenSSL Extension' => [
            'status' => extension_loaded('openssl'),
            'message' => extension_loaded('openssl') ? 'Loaded' : 'Not loaded'
        ],
        'File Uploads Enabled' => [
            'status' => ini_get('file_uploads'),
            'message' => ini_get('file_uploads') ? 'Enabled' : 'Disabled'
        ],
        'Writable Config File' => [
            'status' => is_writable($db_config_path),
            'message' => is_writable($db_config_path) ? 'Writable' : 'Not writable'
        ],
    ]
];

foreach ($serverRequirements['checks'] as $check) {
    if (!$check['status']) {
        $serverRequirements['all_met'] = false;
    }
}
// =====================================================================

if ($_SERVER['REQUEST_METHOD'] == 'POST' && $_POST) {
    
    define('APP_URL', (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://" . $_SERVER['HTTP_HOST'] . str_replace(basename($_SERVER['SCRIPT_NAME']), "", $_SERVER['SCRIPT_NAME']));
    
    require_once('taskCoreClass.php');
    require_once('includes/databaseLibrary.php');
    
    $core = new Core();
    $database = new Database();

    if (!empty($_POST['hostname']) && !empty($_POST['username']) && !empty($_POST['database'])  && !empty($_POST['admin_email'])) {
        if ($database->create_database($_POST) == false) {
            $message = $core->show_message('error', "The database could not be created, make sure your the host, username, password, database name is correct.");
        } 
        if ($core->write_config($_POST) == false) {
            $message = $core->show_message('error', "The database configuration file could not be written, please chmod application/config/database.php file to 777");
        }
        if ($database->create_tables($_POST) == false) {
            $message = $core->show_message('error', "The database could not be created, make sure your the host, username, password, database name is correct.");
        } 
        sleep(15);
        if ($database->create_admin($_POST) == false) {
            $message = $core->show_message('error', "The admin could not be created.");
        }
        if ($core->checkFile() == false) {
            $message = $core->show_message('error', "File application/config/database.php is Empty");
        }
        if (!isset($message)) {
            $urlWb = str_replace("install/","",APP_URL);
            $core->delete_directory('../install/');
            $type = 'success';
            $message = $core->show_message('success', 'Congrats! Installation is successful. Please wait redirecting you to the main page in seconds.. .');
            header('Refresh:5; url=' . $urlWb);
        }
       
    } else {
        $message = $core->show_message('error', 'The host, username, password, database name required.');
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>eShop Installer</title>
    
    <!-- Tabler Core CSS -->
    <link href="https://cdn.jsdelivr.net/npm/@tabler/core@1.0.0-beta20/dist/css/tabler.min.css" rel="stylesheet"/>
    <!-- Tabler Icons -->
    <link href="https://cdn.jsdelivr.net/npm/@tabler/icons-webfont@3.29.0/dist/tabler-icons.min.css" rel="stylesheet"/>
    
    <style>
        :root {
            --tblr-primary: #6232bd;
            --tblr-primary-rgb: 98, 50, 189;
        }
        body {
            background: linear-gradient(135deg, #f0f7ff 0%, #e3f2fd 100%);
            min-height: 100vh;
            font-family: var(--tblr-font-sans-serif);
        }
        .page-wrapper {
            display: flex;
            align-items: center;
            justify-content: center;
            min-height: 100vh;
            padding: 2rem 1rem;
        }
        .installer-card {
            max-width: 750px;
            width: 100%;
            margin: 0 auto;
        }
        .card-header-custom {
            background:#6232bd;
            color: white;
            padding: 2rem;
            border-radius: var(--tblr-border-radius) var(--tblr-border-radius) 0 0;
        }
        .card-header-custom h2 {
            margin: 0;
            font-size: 1.75rem;
            font-weight: 700;
        }
        .card-header-custom p {
            margin: 0.5rem 0 0 0;
            opacity: 0.95;
        }
        .progress-section {
            padding: 1.5rem;
            background: white;
            border-bottom: 1px solid var(--tblr-border-color);
        }
        .progress-labels {
            display: flex;
            justify-content: space-between;
            margin-bottom: 0.75rem;
            font-size: 0.875rem;
            font-weight: 600;
            color: var(--tblr-primary);
        }
        .step-content {
            display: none;
        }
        .step-content.active {
            display: block;
        }
        .welcome-header {
            text-align: center;
            padding: 2rem 0;
        }
        .welcome-icon {
            font-size: 4rem;
            color: var(--tblr-primary);
            margin-bottom: 1rem;
        }
        .welcome-header h3 {
            color: var(--tblr-primary);
            font-weight: 600;
            margin-bottom: 0.75rem;
        }
        .feature-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 1rem;
            margin: 2rem 0;
        }
        .feature-card {
            text-align: center;
            padding: 1.5rem 1rem;
            background: var(--tblr-bg-surface-secondary);
            border-radius: var(--tblr-border-radius);
            border: 1px solid var(--tblr-border-color);
        }
        .feature-card i {
            font-size: 2.5rem;
            color: var(--tblr-primary);
            margin-bottom: 0.75rem;
        }
        .feature-card span {
            display: block;
            font-weight: 500;
        }
        .requirement-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 1rem;
            margin-bottom: 0.75rem;
            background: var(--tblr-bg-surface-secondary);
            border-radius: var(--tblr-border-radius);
            border: 1px solid var(--tblr-border-color);
        }
        .requirement-info strong {
            display: block;
            margin-bottom: 0.25rem;
        }
        .status-icon {
            font-size: 1.75rem;
        }
        .status-success {
            color: var(--tblr-success);
        }
        .status-error {
            color: var(--tblr-danger);
        }
        .info-callout {
            display: flex;
            gap: 1rem;
            padding: 1rem;
            margin-bottom: 1.5rem;
            background: var(--tblr-blue-lt);
            border-left: 4px solid var(--tblr-primary);
            border-radius: var(--tblr-border-radius);
        }
        .info-callout i {
            font-size: 1.5rem;
            color: var(--tblr-primary);
            flex-shrink: 0;
        }
        .info-callout-content h6 {
            margin: 0 0 0.5rem 0;
            font-weight: 600;
            color: var(--tblr-primary);
        }
        .info-callout-content p {
            margin: 0;
            font-size: 0.875rem;
        }
        .form-label {
            font-weight: 600;
        }
        .form-label i {
            color: var(--tblr-primary);
            margin-right: 0.5rem;
        }
        .final-review {
            text-align: center;
            padding: 2rem 0;
        }
        .success-icon-large {
            font-size: 5rem;
            color: var(--tblr-success);
            margin-bottom: 1.5rem;
        }
        .review-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
            gap: 1rem;
            margin: 2rem 0;
        }
        .review-card {
            text-align: left;
            padding: 1.25rem;
            background: var(--tblr-bg-surface-secondary);
            border: 1px solid var(--tblr-border-color);
            border-radius: var(--tblr-border-radius);
        }
        .review-card h6 {
            display: flex;
            align-items: center;
            margin-bottom: 1rem;
            font-weight: 600;
        }
        .review-card h6 i {
            margin-right: 0.5rem;
        }
        .review-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 0.75rem;
            font-size: 0.875rem;
        }
        .review-item:last-child {
            margin-bottom: 0;
        }
        .copy-btn {
            padding: 0.125rem 0.5rem;
            font-size: 0.75rem;
        }
        .btn-navigation {
            min-width: 120px;
        }
    </style>
</head>
<body>

<div class="page-wrapper">
    <div class="installer-card">
        <div class="card">
            
            <!-- Card Header -->
            <div class="card-header-custom">
                <h2><i class="ti ti-shopping-cart me-2"></i>eShop Installer</h2>
                <p>Professional E-Commerce Platform Setup</p>
            </div>

            <!-- Progress Section -->
            <div class="progress-section" <?= (isset($type) && $type === 'success') ? 'style="display: none;"' : '' ?>>
                <div class="progress-labels">
                    <span id="step-label">Step 1 of 5</span>
                    <span id="step-percentage">20%</span>
                </div>
                <div class="progress">
                    <div class="progress-bar" id="progress-bar" style="width: 20%;" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100"></div>
                </div>
            </div>

            <div class="card-body">

                <?php if (is_writable($db_config_path)) { ?>

                    <?php if (isset($message)) { ?>
                        <?php if ($type === 'success') { ?>
                            <!-- Success Message Display -->
                            <div class="text-center py-5">
                                <div class="mb-4">
                                    <i class="ti ti-circle-check" style="font-size: 6rem; color: var(--tblr-success);"></i>
                                </div>
                                <h3 class="text-success mb-3">Installation Successful!</h3>
                                <p class="text-secondary mb-2">Congratulations! eShop has been installed successfully.</p>
                                <p class="text-muted small">Redirecting you to the main page in a few seconds...</p>
                                <div class="mt-4">
                                    <div class="spinner-border text-success" role="status">
                                        <span class="visually-hidden">Loading...</span>
                                    </div>
                                </div>
                            </div>
                        <?php } else { ?>
                            <!-- Error Message Display -->
                            <div class="alert alert-danger alert-dismissible" role="alert">
                                <div class="d-flex">
                                    <div>
                                        <i class="ti ti-alert-circle icon alert-icon"></i>
                                    </div>
                                    <div>
                                        <?= $message ?>
                                    </div>
                                </div>
                                <a class="btn-close" data-bs-dismiss="alert" aria-label="close"></a>
                            </div>
                        <?php } ?>
                    <?php } ?>

                    <form method="POST" action="<?= $_SERVER['PHP_SELF'] ?>" id="installer-form" novalidate <?= (isset($type) && $type === 'success') ? 'style="display: none;"' : '' ?>>

                        <!-- Step 1: Welcome -->
                        <div class="step-content active" id="step1">
                            <div class="welcome-header">
                                <div class="welcome-icon">
                                    <i class="ti ti-rocket"></i>
                                </div>
                                <h3>Welcome to eShop Installation</h3>
                                <p class="text-secondary">Set up your professional e-commerce platform in just a few minutes.</p>
                                <p class="text-muted small">Please ensure you have your database credentials ready before proceeding.</p>
                            </div>

                            <div class="feature-grid">
                                <div class="feature-card">
                                    <i class="ti ti-bolt"></i>
                                    <span>Fast Setup</span>
                                </div>
                                <div class="feature-card">
                                    <i class="ti ti-shield-lock"></i>
                                    <span>Secure</span>
                                </div>
                                <div class="feature-card">
                                    <i class="ti ti-settings"></i>
                                    <span>Easy Config</span>
                                </div>
                            </div>

                            <div class="text-center mt-4">
                                <button type="button" class="btn btn-primary btn-lg" onclick="nextStep(2)">
                                    Start Installation
                                    <i class="ti ti-arrow-right ms-2"></i>
                                </button>
                            </div>
                        </div>

                        <!-- Step 2: Extension Check -->
                        <div class="step-content" id="step2">
                            <h4 class="mb-4">
                                <i class="ti ti-puzzle me-2"></i>Extension Check
                            </h4>
                            <p class="text-secondary mb-4">Checking required PHP extensions and server requirements.</p>

                            <div class="requirements-list">
                                <?php foreach ($serverRequirements['checks'] as $check => $result) { ?>
                                    <div class="requirement-item">
                                        <div class="requirement-info">
                                            <strong><?= htmlspecialchars($check) ?></strong>
                                            <small class="text-muted"><?= htmlspecialchars($result['message']) ?></small>
                                        </div>
                                        <div class="status-icon <?= $result['status'] ? 'status-success' : 'status-error' ?>">
                                            <i class="ti <?= $result['status'] ? 'ti-circle-check-filled' : 'ti-circle-x-filled' ?>"></i>
                                        </div>
                                    </div>
                                <?php } ?>
                            </div>

                            <div class="alert <?= $serverRequirements['all_met'] ? 'alert-success' : 'alert-danger' ?> mt-4" role="alert">
                                <div class="d-flex">
                                    <div>
                                        <i class="ti <?= $serverRequirements['all_met'] ? 'ti-check' : 'ti-alert-triangle' ?> icon alert-icon"></i>
                                    </div>
                                    <div>
                                        <h4 class="alert-title"><?= $serverRequirements['all_met'] ? 'Great!' : 'Warning!' ?></h4>
                                        <div class="text-secondary">
                                            <?= $serverRequirements['all_met'] 
                                                ? 'All requirements are met. You can proceed with the installation.' 
                                                : 'Some requirements are not met. Please resolve the issues before continuing.' ?>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="d-flex justify-content-between mt-4">
                                <button type="button" class="btn btn-outline-primary btn-navigation" onclick="nextStep(1)">
                                    <i class="ti ti-arrow-left me-2"></i>Back
                                </button>
                                <button type="button" class="btn btn-primary btn-navigation" onclick="nextStep(3)" <?= !$serverRequirements['all_met'] ? 'disabled' : '' ?>>
                                    Continue<i class="ti ti-arrow-right ms-2"></i>
                                </button>
                            </div>
                        </div>

                        <!-- Step 3: Database -->
                        <div class="step-content" id="step3">
                            <h4 class="mb-4">
                                <i class="ti ti-database me-2"></i>Database Configuration
                            </h4>

                            <div class="info-callout">
                                <i class="ti ti-info-circle"></i>
                                <div class="info-callout-content">
                                    <h6>Secure Connection</h6>
                                    <p>Your database credentials are encrypted and stored securely. We never share your information.</p>
                                </div>
                            </div>

                            <div class="mb-3">
                                <label class="form-label required">
                                    <i class="ti ti-server"></i>Database Hostname
                                </label>
                                <input type="text" class="form-control" name="hostname" id="hostname" value="localhost" placeholder="localhost" required>
                                <small class="form-hint">Usually "localhost" for local servers</small>
                            </div>

                            <div class="mb-3">
                                <label class="form-label required">
                                    <i class="ti ti-user"></i>Database Username
                                </label>
                                <input type="text" class="form-control" name="username" id="username" placeholder="Enter database username" required>
                            </div>

                            <div class="mb-3">
                                <label class="form-label">
                                    <i class="ti ti-lock"></i>Database Password
                                </label>
                                <input type="password" class="form-control" name="password" placeholder="Enter database password (if any)">
                                <small class="form-hint">Leave blank if no password is set</small>
                            </div>

                            <div class="mb-3">
                                <label class="form-label required">
                                    <i class="ti ti-database"></i>Database Name
                                </label>
                                <input type="text" class="form-control" name="database" id="database" placeholder="Enter database name" required>
                                <small class="form-hint">The database will be created if it doesn't exist</small>
                            </div>

                            <div class="d-flex justify-content-between mt-4">
                                <button type="button" class="btn btn-outline-primary btn-navigation" onclick="nextStep(2)">
                                    <i class="ti ti-arrow-left me-2"></i>Back
                                </button>
                                <button type="button" class="btn btn-primary btn-navigation" id="db-next-btn">
                                    Continue<i class="ti ti-arrow-right ms-2"></i>
                                </button>
                            </div>
                        </div>

                        <!-- Step 4: Admin -->
                        <div class="step-content" id="step4">
                            <h4 class="mb-4">
                                <i class="ti ti-user-circle me-2"></i>Administrator Account
                            </h4>

                            <div class="info-callout">
                                <i class="ti ti-shield-check"></i>
                                <div class="info-callout-content">
                                    <h6>Admin Security</h6>
                                    <p>Choose a strong password to protect your admin account. We recommend using a combination of letters, numbers, and symbols.</p>
                                </div>
                            </div>

                            <div class="mb-3">
                                <label class="form-label required">
                                    <i class="ti ti-phone"></i>Mobile Number
                                </label>
                                <input type="text" class="form-control" name="admin_mobile" id="adminMobile" placeholder="Enter admin mobile number" required>
                                <small class="form-hint">This will be used for login and notifications</small>
                            </div>

                            <div class="mb-3">
                                <label class="form-label required">
                                    <i class="ti ti-key"></i>Admin Password
                                </label>
                                <input type="password" class="form-control" name="admin_password" id="adminPassword" placeholder="Create a strong password" required>
                                <small class="form-hint">Minimum 8 characters recommended</small>
                            </div>

                            <div class="mb-3">
                                <label class="form-label required">
                                    <i class="ti ti-mail"></i>Email Address
                                </label>
                                <input type="email" class="form-control" name="admin_email" placeholder="admin@example.com" required>
                                <small class="form-hint">For password recovery and important notifications</small>
                            </div>

                            <div class="d-flex justify-content-between mt-4">
                                <button type="button" class="btn btn-outline-primary btn-navigation" onclick="nextStep(3)">
                                    <i class="ti ti-arrow-left me-2"></i>Back
                                </button>
                                <button type="button" class="btn btn-primary btn-navigation" id="admin-next-btn">
                                    Review & Install<i class="ti ti-arrow-right ms-2"></i>
                                </button>
                            </div>
                        </div>

                        <!-- Step 5: Final Install -->
                        <div class="step-content" id="step5">
                            <div class="final-review">
                                <div class="success-icon-large">
                                    <i class="ti ti-circle-check"></i>
                                </div>
                                <h3 class="text-success mb-2">Installation Ready!</h3>
                                <p class="text-secondary mb-4">Please review your details and click 'Install' to complete the setup.</p>

                                <div class="review-grid">
                                    <div class="review-card">
                                        <h6 class="text-success">
                                            <i class="ti ti-user-check"></i>Admin Account
                                        </h6>
                                        <div class="review-item">
                                            <strong>Mobile:</strong>
                                            <div>
                                                <span id="finalMobile" class="text-muted">-</span>
                                                <button type="button" class="btn btn-sm btn-success copy-btn ms-2" data-clipboard-target="#finalMobile">
                                                    <i class="ti ti-copy"></i>
                                                </button>
                                            </div>
                                        </div>
                                        <div class="review-item">
                                            <strong>Password:</strong>
                                            <div>
                                                <span id="finalPassword" class="text-muted">-</span>
                                                <button type="button" class="btn btn-sm btn-success copy-btn ms-2" data-clipboard-target="#finalPassword">
                                                    <i class="ti ti-copy"></i>
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="review-card">
                                        <h6 class="text-info">
                                            <i class="ti ti-database"></i>Database
                                        </h6>
                                        <div class="review-item">
                                            <strong>Host:</strong>
                                            <span id="finalHostname" class="text-muted">-</span>
                                        </div>
                                        <div class="review-item">
                                            <strong>Status:</strong>
                                            <span class="badge bg-success text-white">Ready</span>
                                        </div>
                                    </div>
                                </div>

                                <div class="d-flex justify-content-center gap-2 mt-4">
                                    <button type="button" class="btn btn-outline-primary btn-navigation" onclick="nextStep(4)">
                                        <i class="ti ti-arrow-left me-2"></i>Back
                                    </button>
                                    <button type="submit" class="btn btn-primary btn-lg px-4" id="install-btn">
                                        <span id="install-btn-text">
                                            <i class="ti ti-download me-2"></i>Install eShop Now
                                        </span>
                                        <span id="install-btn-loading" style="display: none;">
                                            <span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>
                                            Installing...
                                        </span>
                                    </button>
                                </div>
                            </div>
                        </div>

                    </form>

                <?php } else { ?>
                    <div class="alert alert-danger" role="alert">
                        <div class="d-flex">
                            <div>
                                <i class="ti ti-alert-circle icon alert-icon"></i>
                            </div>
                            <div>
                                <h4 class="alert-title">Permission Error</h4>
                                <div class="text-secondary">
                                    <p>The following file needs write permissions:</p>
                                    <div class="bg-danger-lt p-2 rounded mb-3">
                                        <code>application/config/database.php</code>
                                    </div>
                                    <p class="mb-1"><strong>Solution:</strong></p>
                                    <div class="bg-danger-lt p-2 rounded">
                                        <code>chmod 777 application/config/database.php</code>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php } ?>

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

<!-- Tabler Core JS -->
<script src="https://cdn.jsdelivr.net/npm/@tabler/core@1.0.0-beta20/dist/js/tabler.min.js"></script>
<!-- Clipboard.js -->
<script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>

<script>
let databaseVerified = false; // Track if database is verified

function nextStep(n) {
    // Block progression from step 3 to 4 if database not verified
    if (n === 4 && !databaseVerified) {
        return;
    }

    // Hide all steps
    document.querySelectorAll('.step-content').forEach(s => s.classList.remove('active'));
    // Show current step
    document.getElementById('step' + n).classList.add('active');

    // Update progress
    const labels = ['Step 1 of 5', 'Step 2 of 5', 'Step 3 of 5', 'Step 4 of 5', 'Step 5 of 5'];
    const percentages = ['20%', '40%', '60%', '80%', '100%'];
    const percentValues = [20, 40, 60, 80, 100];

    document.getElementById('step-label').textContent = labels[n-1];
    document.getElementById('step-percentage').textContent = percentages[n-1];
    
    const progressBar = document.getElementById('progress-bar');
    progressBar.style.width = percentages[n-1];
    progressBar.setAttribute('aria-valuenow', percentValues[n-1]);

    // Populate final review`
    if (n === 5) {
        document.getElementById('finalMobile').textContent = document.getElementById('adminMobile').value;
        document.getElementById('finalPassword').textContent = document.getElementById('adminPassword').value;
        document.getElementById('finalHostname').textContent = document.getElementById('hostname').value;
    }
}

// Initialize Clipboard.js
new ClipboardJS('.copy-btn');

// Validation for Database Step (Step 3 → Step 4)
document.getElementById('db-next-btn').addEventListener('click', function(e) {
    e.preventDefault();

    // Remove previous error states
    document.querySelectorAll('#step3 .is-invalid').forEach(el => el.classList.remove('is-invalid'));

    let valid = true;

    const hostname = document.getElementById('hostname');
    const username = document.getElementById('username');
    const database = document.getElementById('database');

    if (hostname.value.trim() === '') {
        hostname.classList.add('is-invalid');
        valid = false;
    }
    if (username.value.trim() === '') {
        username.classList.add('is-invalid');
        valid = false;
    }
    if (database.value.trim() === '') {
        database.classList.add('is-invalid');
        valid = false;
    }

    if (valid) {
        nextStep(4);
    }
});

// Validation for Admin Step (Step 4 → Step 5)
document.getElementById('admin-next-btn').addEventListener('click', function(e) {
    e.preventDefault();

    // Remove previous error states and alerts
    document.querySelectorAll('#step4 .is-invalid').forEach(el => el.classList.remove('is-invalid'));
    document.querySelectorAll('#step4 .alert').forEach(el => el.remove());

    let valid = true;
    const errors = [];

    const mobile = document.getElementById('adminMobile');
    const password = document.getElementById('adminPassword');
    const email = document.querySelector('input[name="admin_email"]');

    if (mobile.value.trim() === '') {
        mobile.classList.add('is-invalid');
        errors.push('Mobile number is required');
        valid = false;
    }
    if (password.value.trim() === '') {
        password.classList.add('is-invalid');
        errors.push('Admin password is required');
        valid = false;
    }
    if (email.value.trim() === '') {
        email.classList.add('is-invalid');
        errors.push('Email address is required');
        valid = false;
    } else if (!isValidEmail(email.value)) {
        email.classList.add('is-invalid');
        errors.push('Please enter a valid email address');
        valid = false;
    }

    if (!valid) {
        showAdminError(errors.join(', '));
        return;
    }

    nextStep(5);
});

function isValidEmail(email) {
    const emailRegex = /^[\w\.-]+@[\w\.-]+\.\w+$/;
    return emailRegex.test(email);
}

function showAdminError(msg) {
    const alert = document.createElement('div');
    alert.className = 'alert alert-danger mt-3';
    alert.innerHTML = `
        <div class="d-flex">
            <i class="ti ti-alert-circle me-2"></i>
            <div>${msg}</div>
        </div>
    `;
    document.getElementById('step4').prepend(alert);
}
document.getElementById('db-next-btn').addEventListener('click', function (e) {
    e.preventDefault();

    // Remove old alerts
    document.querySelectorAll('#step3 .alert').forEach(el => el.remove());
    document.querySelectorAll('#step3 .is-invalid').forEach(el => el.classList.remove('is-invalid'));

    const hostname = document.getElementById('hostname');
    const username = document.getElementById('username');
    const database = document.getElementById('database');
    const password = document.querySelector('input[name="password"]');

    let valid = true;

    if (!hostname.value.trim()) {
        hostname.classList.add('is-invalid');
        valid = false;
    }
    if (!username.value.trim()) {
        username.classList.add('is-invalid');
        valid = false;
    }
    if (!database.value.trim()) {
        database.classList.add('is-invalid');
        valid = false;
    }

    if (!valid) return; // ⛔ HARD STOP

    const btn = this;
    const originalHTML = btn.innerHTML;

    btn.disabled = true;
    btn.innerHTML = `
        <span class="spinner-border spinner-border-sm me-2"></span>
        Verifying database...
    `;

    fetch('check_database.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: new URLSearchParams({
            hostname: hostname.value,
            username: username.value,
            password: password.value,
            database: database.value
        })
    })
    .then(res => res.json())
    .then(data => {
        if (data.status !== true) {
            // Database verification FAILED - highlight fields and show error message
            databaseVerified = false;
            btn.disabled = true;
            btn.innerHTML = originalHTML;
            
            // Remove old error message
            document.querySelectorAll('#step3 .alert-danger').forEach(el => el.remove());
            
            // Show error message
            const errorMsg = document.createElement('div');
            errorMsg.className = 'alert alert-danger mt-3';
            errorMsg.innerHTML = `
                <div class="d-flex">
                    <i class="ti ti-alert-circle me-2"></i>
                    <div>${data.message || 'Database verification failed'}</div>
                </div>
            `;
            document.getElementById('step3').prepend(errorMsg);
            
            // Add error styling to input fields
            hostname.classList.add('is-invalid');
            username.classList.add('is-invalid');
            database.classList.add('is-invalid');
            if (password.value.trim()) {
                password.classList.add('is-invalid');
            }
            return;
        }

        // ✅ Database verification SUCCESSFUL - set flag and proceed
        databaseVerified = true;
        btn.disabled = false;
        btn.innerHTML = originalHTML;
        // Clear error styling from all fields
        hostname.classList.remove('is-invalid');
        username.classList.remove('is-invalid');
        database.classList.remove('is-invalid');
        password.classList.remove('is-invalid');
        // Clear any error alerts from Step 3
        document.querySelectorAll('#step3 .alert').forEach(el => el.remove());
        nextStep(4);
    })
    .catch(() => {
        // Network/fetch error - highlight fields and show error message
        databaseVerified = false;
        btn.disabled = true;
        btn.innerHTML = originalHTML;
        
        // Remove old error message
        document.querySelectorAll('#step3 .alert-danger').forEach(el => el.remove());
        
        // Show error message
        const errorMsg = document.createElement('div');
        errorMsg.className = 'alert alert-danger mt-3';
        errorMsg.innerHTML = `
            <div class="d-flex">
                <i class="ti ti-alert-circle me-2"></i>
                <div>Database verification failed. Please try again.</div>install-a
            </div>
        `;
        document.getElementById('step3').prepend(errorMsg);
        
        // Add error styling to input fields
        hostname.classList.add('is-invalid');
        username.classList.add('is-invalid');
        database.classList.add('is-invalid');
    });
});

function showDbError(msg) {
    // Silent verification - no alert display
}

// Re-enable continue button when user modifies input fields
document.getElementById('hostname').addEventListener('input', enableDbButton);
document.getElementById('username').addEventListener('input', enableDbButton);
document.getElementById('database').addEventListener('input', enableDbButton);
document.querySelector('input[name="password"]').addEventListener('input', enableDbButton);

function enableDbButton() {
    const btn = document.getElementById('db-next-btn');
    databaseVerified = false; // Reset verification when user changes input
    btn.disabled = false;
    btn.innerHTML = `
        Continue<i class="ti ti-arrow-right ms-2"></i>
    `;
}



</script>

</body>
</html>