<?php
session_start();

if (file_exists(__DIR__ . '/installed.lock')) {
    die('<div style="text-align:center;padding:60px;font-family:sans-serif;">
        <h2>Tap2Order is already installed.</h2>
        <p>Please delete the <code>install/installed.lock</code> file to re-run the installer.</p>
        <a href="../login.php" style="color:#4a90d9;">Go to Login</a>
    </div>');
}

if (!isset($_SESSION['install_step'])) {
    $_SESSION['install_step'] = 1;
}

$current_step = (int)$_SESSION['install_step'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tap2Order - Installation Wizard</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.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: #eef2f7;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }
        .install-header {
            background: linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%);
            padding: 20px 0;
            text-align: center;
            box-shadow: 0 2px 10px rgba(0,0,0,0.2);
        }
        .install-header .logo-text {
            color: #fff;
            font-size: 28px;
            font-weight: 700;
            letter-spacing: 1px;
        }
        .install-header .logo-text span {
            color: #e63946;
        }
        .install-header .tagline {
            color: rgba(255,255,255,0.6);
            font-size: 13px;
            margin-top: 4px;
        }
        .progress-container {
            background: #fff;
            padding: 25px 0;
            border-bottom: 1px solid #e0e0e0;
        }
        .step-indicator {
            display: flex;
            justify-content: center;
            align-items: center;
            max-width: 800px;
            margin: 0 auto;
            position: relative;
        }
        .step-dot {
            width: 38px;
            height: 38px;
            border-radius: 50%;
            background: #dee2e6;
            color: #adb5bd;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            font-size: 14px;
            position: relative;
            z-index: 2;
            transition: all 0.3s ease;
            flex-shrink: 0;
        }
        .step-dot.active {
            background: #4a90d9;
            color: #fff;
            box-shadow: 0 0 0 4px rgba(74,144,217,0.25);
        }
        .step-dot.completed {
            background: #28a745;
            color: #fff;
        }
        .step-line {
            flex: 1;
            height: 3px;
            background: #dee2e6;
            margin: 0 5px;
            transition: background 0.3s ease;
        }
        .step-line.completed {
            background: #28a745;
        }
        .step-label {
            position: absolute;
            bottom: -22px;
            font-size: 10px;
            color: #6c757d;
            white-space: nowrap;
            left: 50%;
            transform: translateX(-50%);
        }
        .step-dot.active .step-label,
        .step-dot.completed .step-label { color: #333; }
        .main-content {
            flex: 1;
            padding: 30px 15px;
        }
        .install-card {
            background: #fff;
            border-radius: 12px;
            box-shadow: 0 2px 20px rgba(0,0,0,0.08);
            max-width: 700px;
            margin: 0 auto;
            overflow: hidden;
        }
        .card-header-section {
            padding: 25px 30px 20px;
            border-bottom: 1px solid #f0f0f0;
        }
        .card-header-section h4 {
            font-weight: 700;
            color: #1a1a2e;
            margin-bottom: 5px;
        }
        .card-header-section p {
            color: #6c757d;
            font-size: 14px;
            margin: 0;
        }
        .card-body-section {
            padding: 30px;
        }
        .req-item {
            display: flex;
            align-items: center;
            padding: 10px 0;
            border-bottom: 1px solid #f5f5f5;
        }
        .req-item:last-child { border-bottom: none; }
        .req-icon {
            width: 28px;
            height: 28px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 12px;
            flex-shrink: 0;
            font-size: 13px;
        }
        .req-icon.pass { background: #d4edda; color: #28a745; }
        .req-icon.fail { background: #f8d7da; color: #dc3545; }
        .req-label { flex: 1; font-size: 14px; color: #333; }
        .req-status { font-size: 12px; font-weight: 600; }
        .req-status.pass { color: #28a745; }
        .req-status.fail { color: #dc3545; }

        .form-label { font-weight: 600; font-size: 13px; color: #495057; margin-bottom: 6px; }
        .form-control, .form-select {
            border-radius: 8px;
            border: 1px solid #dee2e6;
            padding: 10px 14px;
            font-size: 14px;
            transition: border-color 0.2s;
        }
        .form-control:focus, .form-select:focus {
            border-color: #4a90d9;
            box-shadow: 0 0 0 3px rgba(74,144,217,0.15);
        }

        .btn-install {
            background: linear-gradient(135deg, #4a90d9, #357abd);
            color: #fff;
            border: none;
            padding: 10px 28px;
            border-radius: 8px;
            font-weight: 600;
            font-size: 14px;
            transition: all 0.2s;
        }
        .btn-install:hover { background: linear-gradient(135deg, #357abd, #2c6aa0); color: #fff; transform: translateY(-1px); }
        .btn-install:disabled { opacity: 0.5; cursor: not-allowed; transform: none; }

        .btn-secondary-install {
            background: #f8f9fa;
            color: #495057;
            border: 1px solid #dee2e6;
            padding: 10px 28px;
            border-radius: 8px;
            font-weight: 600;
            font-size: 14px;
            transition: all 0.2s;
        }
        .btn-secondary-install:hover { background: #e9ecef; }

        .btn-success-install {
            background: linear-gradient(135deg, #28a745, #218838);
            color: #fff;
            border: none;
            padding: 10px 28px;
            border-radius: 8px;
            font-weight: 600;
            font-size: 14px;
            transition: all 0.2s;
        }
        .btn-success-install:hover { background: linear-gradient(135deg, #218838, #1e7e34); color: #fff; }

        .test-result {
            padding: 12px 16px;
            border-radius: 8px;
            margin-top: 15px;
            font-size: 14px;
            display: none;
        }
        .test-result.success { display: block; background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .test-result.error { display: block; background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
        .test-result.loading { display: block; background: #d1ecf1; color: #0c5460; border: 1px solid #bee5eb; }

        .install-progress {
            display: none;
            margin-top: 20px;
        }
        .install-progress.active { display: block; }
        .progress-log {
            background: #1a1a2e;
            color: #a8e6cf;
            border-radius: 8px;
            padding: 15px;
            max-height: 300px;
            overflow-y: auto;
            font-family: 'Consolas', 'Courier New', monospace;
            font-size: 13px;
            line-height: 1.6;
        }
        .progress-log .log-line { margin-bottom: 2px; }
        .progress-log .log-success { color: #a8e6cf; }
        .progress-log .log-error { color: #ff6b6b; }
        .progress-log .log-info { color: #74b9ff; }

        .password-strength {
            height: 4px;
            border-radius: 2px;
            margin-top: 8px;
            background: #e9ecef;
            overflow: hidden;
        }
        .password-strength .bar {
            height: 100%;
            border-radius: 2px;
            transition: width 0.3s, background 0.3s;
            width: 0%;
        }
        .strength-text {
            font-size: 12px;
            margin-top: 4px;
            font-weight: 600;
        }

        .complete-card {
            text-align: center;
            padding: 20px 0;
        }
        .complete-icon {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            background: linear-gradient(135deg, #28a745, #218838);
            color: #fff;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 20px;
            font-size: 36px;
        }
        .credentials-box {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            padding: 20px;
            text-align: left;
            margin: 20px 0;
        }
        .credentials-box .cred-item {
            display: flex;
            justify-content: space-between;
            padding: 8px 0;
            border-bottom: 1px solid #e9ecef;
            font-size: 14px;
        }
        .credentials-box .cred-item:last-child { border-bottom: none; }
        .credentials-box .cred-label { font-weight: 600; color: #495057; }
        .credentials-box .cred-value { color: #333; font-family: 'Consolas', monospace; background: #fff; padding: 2px 8px; border-radius: 4px; }

        .install-footer {
            text-align: center;
            padding: 15px;
            color: #adb5bd;
            font-size: 12px;
        }
        .install-footer a { color: #4a90d9; text-decoration: none; }

        .spinner-overlay {
            display: none;
            position: fixed;
            top: 0; left: 0; right: 0; bottom: 0;
            background: rgba(255,255,255,0.7);
            z-index: 9999;
            justify-content: center;
            align-items: center;
        }
        .spinner-overlay.active { display: flex; }

        .logo-upload-area {
            border: 2px dashed #dee2e6;
            border-radius: 8px;
            padding: 20px;
            text-align: center;
            cursor: pointer;
            transition: border-color 0.2s;
        }
        .logo-upload-area:hover { border-color: #4a90d9; }
        .logo-upload-area i { font-size: 32px; color: #adb5bd; margin-bottom: 8px; }
        .logo-upload-area p { color: #6c757d; font-size: 13px; margin: 0; }
        #logoPreview { max-width: 150px; max-height: 100px; margin-top: 10px; display: none; }
    </style>
</head>
<body>

<div class="install-header">
    <div class="logo-text">Tap<span>2</span>Order</div>
    <div class="tagline">Installation Wizard</div>
</div>

<div class="progress-container">
    <div class="step-indicator">
        <div class="step-dot <?php echo $current_step >= 1 ? ($current_step > 1 ? 'completed' : 'active') : ''; ?>" id="dot1">
            <?php echo $current_step > 1 ? '<i class="fas fa-check"></i>' : '1'; ?>
            <span class="step-label">Requirements</span>
        </div>
        <div class="step-line <?php echo $current_step > 1 ? 'completed' : ''; ?>" id="line1"></div>
        <div class="step-dot <?php echo $current_step >= 2 ? ($current_step > 2 ? 'completed' : 'active') : ''; ?>" id="dot2">
            <?php echo $current_step > 2 ? '<i class="fas fa-check"></i>' : '2'; ?>
            <span class="step-label">Database</span>
        </div>
        <div class="step-line <?php echo $current_step > 2 ? 'completed' : ''; ?>" id="line2"></div>
        <div class="step-dot <?php echo $current_step >= 3 ? ($current_step > 3 ? 'completed' : 'active') : ''; ?>" id="dot3">
            <?php echo $current_step > 3 ? '<i class="fas fa-check"></i>' : '3'; ?>
            <span class="step-label">Install DB</span>
        </div>
        <div class="step-line <?php echo $current_step > 3 ? 'completed' : ''; ?>" id="line3"></div>
        <div class="step-dot <?php echo $current_step >= 4 ? ($current_step > 4 ? 'completed' : 'active') : ''; ?>" id="dot4">
            <?php echo $current_step > 4 ? '<i class="fas fa-check"></i>' : '4'; ?>
            <span class="step-label">Admin</span>
        </div>
        <div class="step-line <?php echo $current_step > 4 ? 'completed' : ''; ?>" id="line4"></div>
        <div class="step-dot <?php echo $current_step >= 5 ? ($current_step > 5 ? 'completed' : 'active') : ''; ?>" id="dot5">
            <?php echo $current_step > 5 ? '<i class="fas fa-check"></i>' : '5'; ?>
            <span class="step-label">Settings</span>
        </div>
        <div class="step-line <?php echo $current_step > 5 ? 'completed' : ''; ?>" id="line5"></div>
        <div class="step-dot <?php echo $current_step >= 6 ? 'active' : ''; ?>" id="dot6">
            6
            <span class="step-label">Complete</span>
        </div>
    </div>
</div>

<div class="main-content">
    <div class="install-card">

        <!-- STEP 1: Requirements -->
        <div id="step1" class="step-panel" style="<?php echo $current_step === 1 ? '' : 'display:none;'; ?>">
            <div class="card-header-section">
                <h4><i class="fas fa-clipboard-check me-2" style="color:#4a90d9;"></i>Server Requirements</h4>
                <p>Verify that your server meets the minimum requirements for Tap2Order.</p>
            </div>
            <div class="card-body-section">
                <div id="requirementsList">
                    <?php
                    $checks = [
                        ['PHP Version >= 7.4', version_compare(PHP_VERSION, '7.4.0', '>=')],
                        ['PDO Extension', extension_loaded('pdo')],
                        ['PDO MySQL Driver', extension_loaded('pdo_mysql')],
                        ['MBString Extension', extension_loaded('mbstring')],
                        ['JSON Extension', extension_loaded('json')],
                        ['GD Extension', extension_loaded('gd')],
                        ['OpenSSL Extension', extension_loaded('openssl')],
                        ['cURL Extension', extension_loaded('curl')],
                        ['Session Support', extension_loaded('session')],
                        ['uploads/ is writable', is_writable(dirname(__DIR__) . '/uploads')],
                        ['storage/logs/ is writable', is_writable(dirname(__DIR__) . '/logs')],
                        ['config/ is writable', is_writable(dirname(__DIR__) . '/config')],
                    ];
                    $all_pass = true;
                    foreach ($checks as $check) {
                        $pass = $check[1];
                        if (!$pass) $all_pass = false;
                        echo '<div class="req-item">';
                        echo '<div class="req-icon ' . ($pass ? 'pass' : 'fail') . '">';
                        echo $pass ? '<i class="fas fa-check"></i>' : '<i class="fas fa-times"></i>';
                        echo '</div>';
                        echo '<span class="req-label">' . htmlspecialchars($check[0]) . '</span>';
                        echo '<span class="req-status ' . ($pass ? 'pass' : 'fail') . '">';
                        echo $pass ? 'Passed' : 'Failed';
                        echo '</span>';
                        echo '</div>';
                    }
                    ?>
                </div>
                <div class="text-end mt-4">
                    <button class="btn btn-install" id="btnNext1" onclick="goToStep(2)" <?php echo !$all_pass ? 'disabled' : ''; ?>>
                        Next <i class="fas fa-arrow-right ms-1"></i>
                    </button>
                </div>
            </div>
        </div>

        <!-- STEP 2: Database Configuration -->
        <div id="step2" class="step-panel" style="<?php echo $current_step === 2 ? '' : 'display:none;'; ?>">
            <div class="card-header-section">
                <h4><i class="fas fa-database me-2" style="color:#4a90d9;"></i>Database Configuration</h4>
                <p>Enter your MySQL database connection details.</p>
            </div>
            <div class="card-body-section">
                <form id="dbConfigForm" onsubmit="return false;">
                    <div class="row">
                        <div class="col-md-8 mb-3">
                            <label class="form-label">Database Host</label>
                            <input type="text" class="form-control" id="dbHost" value="localhost" required>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Port</label>
                            <input type="number" class="form-control" id="dbPort" value="3306">
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Database Name</label>
                        <input type="text" class="form-control" id="dbName" value="tap2order" required>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Username</label>
                            <input type="text" class="form-control" id="dbUser" value="root" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Password</label>
                            <input type="password" class="form-control" id="dbPass" value="">
                        </div>
                    </div>
                </form>
                <div id="testResult" class="test-result"></div>
                <div class="d-flex justify-content-between mt-4">
                    <button class="btn btn-secondary-install" onclick="goToStep(1)">
                        <i class="fas fa-arrow-left me-1"></i> Back
                    </button>
                    <div>
                        <button class="btn btn-secondary-install me-2" onclick="testConnection()">
                            <i class="fas fa-plug me-1"></i> Test Connection
                        </button>
                        <button class="btn btn-install" id="btnNext2" onclick="saveDbConfig()" disabled>
                            Next <i class="fas fa-arrow-right ms-1"></i>
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- STEP 3: Install Database -->
        <div id="step3" class="step-panel" style="<?php echo $current_step === 3 ? '' : 'display:none;'; ?>">
            <div class="card-header-section">
                <h4><i class="fas fa-cogs me-2" style="color:#4a90d9;"></i>Install Database</h4>
                <p>Click the button below to create the database tables and seed data.</p>
            </div>
            <div class="card-body-section">
                <div id="installProgress" class="install-progress">
                    <div class="progress mb-3">
                        <div class="progress-bar" id="installProgressBar" role="progressbar" style="width: 0%"></div>
                    </div>
                    <div class="progress-log" id="installLog"></div>
                </div>
                <div id="installSummary" style="display:none;"></div>
                <div class="text-end mt-4">
                    <button class="btn btn-secondary-install" onclick="goToStep(2)">
                        <i class="fas fa-arrow-left me-1"></i> Back
                    </button>
                    <button class="btn btn-success-install ms-2" id="btnInstallDb" onclick="installDatabase()">
                        <i class="fas fa-download me-1"></i> Install Database
                    </button>
                    <button class="btn btn-install ms-2" id="btnNext3" onclick="goToStep(4)" style="display:none;">
                        Next <i class="fas fa-arrow-right ms-1"></i>
                    </button>
                </div>
            </div>
        </div>

        <!-- STEP 4: Admin Account -->
        <div id="step4" class="step-panel" style="<?php echo $current_step === 4 ? '' : 'display:none;'; ?>">
            <div class="card-header-section">
                <h4><i class="fas fa-user-shield me-2" style="color:#4a90d9;"></i>Admin Account</h4>
                <p>Create the administrator account for managing your system.</p>
            </div>
            <div class="card-body-section">
                <form id="adminForm" onsubmit="return false;">
                    <div class="mb-3">
                        <label class="form-label">Admin Name</label>
                        <input type="text" class="form-control" id="adminName" value="Super Admin" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Email Address</label>
                        <input type="email" class="form-control" id="adminEmail" value="admin@tap2order.local" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Password</label>
                        <input type="password" class="form-control" id="adminPassword" value="Admin@123" required oninput="checkPasswordStrength()">
                        <div class="password-strength">
                            <div class="bar" id="strengthBar"></div>
                        </div>
                        <div class="strength-text" id="strengthText"></div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Confirm Password</label>
                        <input type="password" class="form-control" id="adminPasswordConfirm" value="Admin@123" required>
                    </div>
                </form>
                <div id="adminResult" class="test-result"></div>
                <div class="d-flex justify-content-between mt-4">
                    <button class="btn btn-secondary-install" onclick="goToStep(3)">
                        <i class="fas fa-arrow-left me-1"></i> Back
                    </button>
                    <button class="btn btn-install" id="btnNext4" onclick="saveAdmin()">
                        Next <i class="fas fa-arrow-right ms-1"></i>
                    </button>
                </div>
            </div>
        </div>

        <!-- STEP 5: Site Configuration -->
        <div id="step5" class="step-panel" style="<?php echo $current_step === 5 ? '' : 'display:none;'; ?>">
            <div class="card-header-section">
                <h4><i class="fas fa-cog me-2" style="color:#4a90d9;"></i>Site Configuration</h4>
                <p>Configure your site name and basic settings.</p>
            </div>
            <div class="card-body-section">
                <form id="siteForm" onsubmit="return false;">
                    <div class="mb-3">
                        <label class="form-label">Site Name</label>
                        <input type="text" class="form-control" id="siteName" value="Tap2Order" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Site URL</label>
                        <input type="url" class="form-control" id="siteUrl" value="<?php echo (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http') . '://' . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'localhost'); ?>" required>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Contact Number</label>
                            <input type="text" class="form-control" id="sitePhone" value="">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Contact Email</label>
                            <input type="email" class="form-control" id="siteEmail" value="admin@tap2order.local">
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Site Logo (Optional)</label>
                        <div class="logo-upload-area" onclick="document.getElementById('logoInput').click()">
                            <i class="fas fa-cloud-upload-alt d-block"></i>
                            <p>Click to upload logo (JPG, PNG, GIF)</p>
                        </div>
                        <input type="file" id="logoInput" accept="image/*" style="display:none;" onchange="previewLogo(this)">
                        <img id="logoPreview" alt="Logo Preview">
                    </div>
                </form>
                <div id="siteResult" class="test-result"></div>
                <div class="d-flex justify-content-between mt-4">
                    <button class="btn btn-secondary-install" onclick="goToStep(4)">
                        <i class="fas fa-arrow-left me-1"></i> Back
                    </button>
                    <button class="btn btn-install" id="btnNext5" onclick="saveSiteSettings()">
                        Next <i class="fas fa-arrow-right ms-1"></i>
                    </button>
                </div>
            </div>
        </div>

        <!-- STEP 6: Complete -->
        <div id="step6" class="step-panel" style="<?php echo $current_step === 6 ? '' : 'display:none;'; ?>">
            <div class="card-header-section">
                <h4><i class="fas fa-flag-checkered me-2" style="color:#28a745;"></i>Installation Complete</h4>
                <p>Tap2Order has been successfully installed on your server.</p>
            </div>
            <div class="card-body-section">
                <div class="complete-card">
                    <div class="complete-icon">
                        <i class="fas fa-check"></i>
                    </div>
                    <h4 style="color:#28a745;">Successfully Installed!</h4>
                    <p class="text-muted mt-2 mb-4">Your system is ready to use. Please save the admin credentials below.</p>

                    <div class="credentials-box">
                        <div class="cred-item">
                            <span class="cred-label">Admin Login URL:</span>
                            <span class="cred-value" id="credLoginUrl">-</span>
                        </div>
                        <div class="cred-item">
                            <span class="cred-label">Email:</span>
                            <span class="cred-value" id="credEmail">-</span>
                        </div>
                        <div class="cred-item">
                            <span class="cred-label">Password:</span>
                            <span class="cred-value" id="credPassword">-</span>
                        </div>
                    </div>

                    <div class="alert alert-warning text-start" style="font-size:13px;">
                        <i class="fas fa-exclamation-triangle me-1"></i>
                        <strong>Security Tip:</strong> Please delete the <code>install/</code> directory from your server for security purposes.
                    </div>

                    <a href="../login.php" class="btn btn-success-install btn-lg mt-2">
                        <i class="fas fa-sign-in-alt me-1"></i> Go to Admin Dashboard
                    </a>
                </div>
            </div>
        </div>

    </div>
</div>

<div class="install-footer">
    Powered by <a href="#">DigitalNext Gen</a> &mdash; Tap2Order v1.0.0
</div>

<div class="spinner-overlay" id="spinner">
    <div class="text-center">
        <div class="spinner-border text-primary" role="status" style="width:3rem;height:3rem;"></div>
        <p class="mt-2 text-muted" id="spinnerText">Processing...</p>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
let dbTested = false;

function goToStep(step) {
    document.querySelectorAll('.step-panel').forEach(function(p) { p.style.display = 'none'; });
    document.getElementById('step' + step).style.display = '';

    for (var i = 1; i <= 6; i++) {
        var dot = document.getElementById('dot' + i);
        dot.className = 'step-dot';
        if (i < step) {
            dot.className = 'step-dot completed';
            dot.innerHTML = '<i class="fas fa-check"></i><span class="step-label">' + dot.querySelector('.step-label').textContent + '</span>';
        } else if (i === step) {
            dot.className = 'step-dot active';
        }
        if (i < 6) {
            var line = document.getElementById('line' + i);
            line.className = i < step ? 'step-line completed' : 'step-line';
        }
    }

    fetch('index.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: 'set_step=' + step
    });

    window.scrollTo({top: 0, behavior: 'smooth'});
}

function showSpinner(text) {
    document.getElementById('spinnerText').textContent = text || 'Processing...';
    document.getElementById('spinner').classList.add('active');
}
function hideSpinner() {
    document.getElementById('spinner').classList.remove('active');
}

function testConnection() {
    var result = document.getElementById('testResult');
    result.className = 'test-result loading';
    result.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i> Testing connection...';
    result.style.display = 'block';
    document.getElementById('btnNext2').disabled = true;
    dbTested = false;

    var data = new URLSearchParams();
    data.append('host', document.getElementById('dbHost').value);
    data.append('dbname', document.getElementById('dbName').value);
    data.append('username', document.getElementById('dbUser').value);
    data.append('password', document.getElementById('dbPass').value);
    data.append('port', document.getElementById('dbPort').value);

    fetch('test.php', { method: 'POST', body: data })
        .then(function(r) { return r.json(); })
        .then(function(res) {
            if (res.success) {
                result.className = 'test-result success';
                result.innerHTML = '<i class="fas fa-check-circle me-1"></i> ' + res.message;
                dbTested = true;
                document.getElementById('btnNext2').disabled = false;
            } else {
                result.className = 'test-result error';
                result.innerHTML = '<i class="fas fa-times-circle me-1"></i> ' + res.message;
            }
        })
        .catch(function(e) {
            result.className = 'test-result error';
            result.innerHTML = '<i class="fas fa-times-circle me-1"></i> Connection error. Please try again.';
        });
}

function saveDbConfig() {
    if (!dbTested) {
        testConnection();
        return;
    }
    showSpinner('Saving configuration...');
    var data = new URLSearchParams();
    data.append('host', document.getElementById('dbHost').value);
    data.append('dbname', document.getElementById('dbName').value);
    data.append('username', document.getElementById('dbUser').value);
    data.append('password', document.getElementById('dbPass').value);
    data.append('port', document.getElementById('dbPort').value);

    fetch('save_config.php', { method: 'POST', body: data })
        .then(function(r) { return r.json(); })
        .then(function(res) {
            hideSpinner();
            if (res.success) { goToStep(3); }
            else {
                var result = document.getElementById('testResult');
                result.className = 'test-result error';
                result.innerHTML = '<i class="fas fa-times-circle me-1"></i> ' + res.message;
            }
        })
        .catch(function(e) {
            hideSpinner();
            alert('Error saving configuration.');
        });
}

function installDatabase() {
    document.getElementById('btnInstallDb').disabled = true;
    document.getElementById('btnInstallDb').innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i> Installing...';
    var prog = document.getElementById('installProgress');
    prog.classList.add('active');
    var log = document.getElementById('installLog');
    var bar = document.getElementById('installProgressBar');
    log.innerHTML = '<div class="log-line log-info">Starting database installation...</div>';

    var data = new URLSearchParams();
    data.append('host', document.getElementById('dbHost').value);
    data.append('dbname', document.getElementById('dbName').value);
    data.append('username', document.getElementById('dbUser').value);
    data.append('password', document.getElementById('dbPass').value);

    fetch('install_db.php', { method: 'POST', body: data })
        .then(function(r) { return r.json(); })
        .then(function(res) {
            bar.style.width = '100%';
            bar.classList.add('bg-success');
            if (res.success) {
                log.innerHTML += '<div class="log-line log-success"><i class="fas fa-check-circle"></i> ' + res.message + '</div>';
                if (res.data && res.data.tables) {
                    log.innerHTML += '<div class="log-line log-info">Tables created: ' + res.data.tables.length + '</div>';
                    res.data.tables.forEach(function(t) {
                        log.innerHTML += '<div class="log-line log-success">  &check; ' + t + '</div>';
                    });
                }
                document.getElementById('btnInstallDb').style.display = 'none';
                document.getElementById('btnNext3').style.display = '';
                var summary = document.getElementById('installSummary');
                summary.style.display = 'block';
                summary.innerHTML = '<div class="alert alert-success"><i class="fas fa-check-circle me-1"></i> Database installed successfully!</div>';
            } else {
                log.innerHTML += '<div class="log-line log-error"><i class="fas fa-times-circle"></i> ' + res.message + '</div>';
                document.getElementById('btnInstallDb').disabled = false;
                document.getElementById('btnInstallDb').innerHTML = '<i class="fas fa-download me-1"></i> Retry Installation';
            }
            log.scrollTop = log.scrollHeight;
        })
        .catch(function(e) {
            log.innerHTML += '<div class="log-line log-error"><i class="fas fa-times-circle"></i> Error: ' + e.message + '</div>';
            document.getElementById('btnInstallDb').disabled = false;
            document.getElementById('btnInstallDb').innerHTML = '<i class="fas fa-download me-1"></i> Retry Installation';
            log.scrollTop = log.scrollHeight;
        });
}

function checkPasswordStrength() {
    var pass = document.getElementById('adminPassword').value;
    var bar = document.getElementById('strengthBar');
    var txt = document.getElementById('strengthText');
    var strength = 0;
    if (pass.length >= 8) strength++;
    if (pass.length >= 12) strength++;
    if (/[A-Z]/.test(pass)) strength++;
    if (/[0-9]/.test(pass)) strength++;
    if (/[^A-Za-z0-9]/.test(pass)) strength++;

    var levels = [
        { width: '10%', color: '#dc3545', text: 'Very Weak' },
        { width: '25%', color: '#dc3545', text: 'Weak' },
        { width: '50%', color: '#ffc107', text: 'Fair' },
        { width: '75%', color: '#17a2b8', text: 'Strong' },
        { width: '100%', color: '#28a745', text: 'Very Strong' }
    ];
    var idx = Math.min(strength, 4);
    bar.style.width = levels[idx].width;
    bar.style.background = levels[idx].color;
    txt.textContent = pass.length > 0 ? levels[idx].text : '';
    txt.style.color = levels[idx].color;
}

function saveAdmin() {
    var name = document.getElementById('adminName').value;
    var email = document.getElementById('adminEmail').value;
    var pass = document.getElementById('adminPassword').value;
    var confirm = document.getElementById('adminPasswordConfirm').value;
    var result = document.getElementById('adminResult');

    if (!name || !email || !pass) {
        result.className = 'test-result error';
        result.innerHTML = '<i class="fas fa-times-circle me-1"></i> Please fill all fields.';
        return;
    }
    if (pass !== confirm) {
        result.className = 'test-result error';
        result.innerHTML = '<i class="fas fa-times-circle me-1"></i> Passwords do not match.';
        return;
    }
    if (pass.length < 6) {
        result.className = 'test-result error';
        result.innerHTML = '<i class="fas fa-times-circle me-1"></i> Password must be at least 6 characters.';
        return;
    }

    showSpinner('Saving admin account...');
    var data = new URLSearchParams();
    data.append('name', name);
    data.append('email', email);
    data.append('password', pass);

    fetch('save_admin.php', { method: 'POST', body: data })
        .then(function(r) { return r.json(); })
        .then(function(res) {
            hideSpinner();
            if (res.success) {
                document.getElementById('credEmail').textContent = email;
                document.getElementById('credPassword').textContent = pass;
                goToStep(5);
            } else {
                result.className = 'test-result error';
                result.innerHTML = '<i class="fas fa-times-circle me-1"></i> ' + res.message;
            }
        })
        .catch(function(e) {
            hideSpinner();
            result.className = 'test-result error';
            result.innerHTML = '<i class="fas fa-times-circle me-1"></i> Error saving admin account.';
        });
}

function previewLogo(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function(e) {
            var preview = document.getElementById('logoPreview');
            preview.src = e.target.result;
            preview.style.display = 'block';
        };
        reader.readAsDataURL(input.files[0]);
    }
}

function saveSiteSettings() {
    var name = document.getElementById('siteName').value;
    var url = document.getElementById('siteUrl').value;
    var phone = document.getElementById('sitePhone').value;
    var email = document.getElementById('siteEmail').value;
    var result = document.getElementById('siteResult');

    if (!name || !url) {
        result.className = 'test-result error';
        result.innerHTML = '<i class="fas fa-times-circle me-1"></i> Please fill required fields.';
        return;
    }

    showSpinner('Saving site settings...');
    var formData = new FormData();
    formData.append('site_name', name);
    formData.append('site_url', url);
    formData.append('contact_phone', phone);
    formData.append('contact_email', email);

    var logoInput = document.getElementById('logoInput');
    if (logoInput.files && logoInput.files[0]) {
        formData.append('logo', logoInput.files[0]);
    }

    fetch('save_site.php', { method: 'POST', body: formData })
        .then(function(r) { return r.json(); })
        .then(function(res) {
            hideSpinner();
            if (res.success) {
                document.getElementById('credLoginUrl').textContent = url + '/login.php';
                document.getElementById('credEmail').textContent = document.getElementById('adminEmail').value;
                document.getElementById('credPassword').textContent = document.getElementById('adminPassword').value;
                goToStep(6);
            } else {
                result.className = 'test-result error';
                result.innerHTML = '<i class="fas fa-times-circle me-1"></i> ' + res.message;
            }
        })
        .catch(function(e) {
            hideSpinner();
            result.className = 'test-result error';
            result.innerHTML = '<i class="fas fa-times-circle me-1"></i> Error saving site settings.';
        });
}
</script>
</body>
</html>
