<?php
require_once __DIR__ . '/includes/schema_basic_install.php';
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);

session_start();

$configDir = __DIR__ . '/config';

$configFile = $configDir . '/config.php';
$databaseConfigFile = $configDir . '/database.php';

$currentUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$baseUrl = str_replace('/install.php', '', $currentUrl);

if (file_exists($configFile)) {
    // Temporarily include to check for BASE_URL without full parsing risk
    // This is a simple check; more robust would be to parse defines if needed
    $configContentCheck = file_get_contents($configFile);
    if ($configContentCheck && preg_match("/define\s*\(\s*['\"]BASE_URL['\"]\s*,\s*['\"](.+?)['\"]\s*\)/", $configContentCheck, $matches)) {
        if (!empty($matches[1])) {
            // Attempt to include it properly to get constants if needed for redirect
            // However, for redirection, the regex match is enough.
            // @include $configFile; // Suppress errors if file is incomplete during dev
            // if (defined('BASE_URL') && BASE_URL !== '') {
            header('Location: ' . $matches[1] . '/index');
            exit;
            // }
        }
    }
}

$errors = [];
$success = false;
$output = '';

// --- Persist submitted form data and reload from session ---
$form_fields_to_persist = ['db_host', 'db_name', 'db_user', 'db_pass', 'site_name', 'admin_email', 'create_db'];
$session_form_data = $_SESSION['install_form_data'] ?? [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    foreach ($form_fields_to_persist as $field) {
        if (isset($_POST[$field])) {
            $_SESSION['install_form_data'][$field] = $_POST[$field];
        }
    }
    $session_form_data = $_SESSION['install_form_data'] ?? []; // Re-load after potential update
}

// --- Determine which step to display ---
$step_to_display = 1;
if (isset($_SESSION['db_connection_verified']) && $_SESSION['db_connection_verified']) {
    $step_to_display = 2;
}

// Handle "Previous" button click from Step 2 to Step 1
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['prev_to_1'])) {
    $step_to_display = 1;
    // Optional: If going back should force re-verification of DB
    // unset($_SESSION['db_connection_verified']);
} elseif (isset($_POST['step']) && !isset($_POST['check_db']) && !isset($_POST['setup_db'])) {
    // This handles if the hidden step input suggests a previous step
    // (e.g., JS changed it, and it's not a primary action submission)
    $posted_step = (int) $_POST['step'];
    if ($posted_step === 1 && $step_to_display === 2) {
        $step_to_display = 1;
    }
}


// --- Helper functions for modifying PHP file content ---

/**
 * Updates or adds a define() statement in a PHP content string.
 * Preserves existing indentation if the define is found and replaced.
 * Ensures the content starts with <?php if it was initially empty or lacked the tag.
 * Appends before a closing ?> tag if present at the end, otherwise appends to the end.
 */
function updateOrAddPhpDefine(&$phpContent, $constantName, $constantValue)
{
    $escapedValue = addslashes($constantValue);
    $newDefineLine = "define('$constantName', '$escapedValue');";
    // Regex to find an existing define statement, capturing leading whitespace
    $pattern = "/^([\t ]*)define\s*\(\s*['\"]" . preg_quote($constantName, '/') . "['\"]\s*,\s*['\"].*?['\"]\s*\)\s*;/m";

    $count = 0;
    $phpContent = preg_replace_callback($pattern, function ($matches) use ($newDefineLine) {
        return $matches[1] . $newDefineLine; // Prepend captured leading whitespace to new line
    }, $phpContent, 1, $count);

    if ($count === 0) { // Constant not found, append it
        $trimmedContent = rtrim(str_replace("\r\n", "\n", $phpContent)); // Normalize EOL and rtrim

        $closingTag = '?>';
        if (substr($trimmedContent, -strlen($closingTag)) === $closingTag) {
            // Ends with PHP closing tag
            $contentBeforeTag = rtrim(substr($trimmedContent, 0, -strlen($closingTag)));
            if (!empty($contentBeforeTag) && substr($contentBeforeTag, -1) !== "\n") {
                $contentBeforeTag .= "\n";
            }
            $phpContent = $contentBeforeTag . $newDefineLine . "\n" . $closingTag . "\n";
        } else {
            // No closing tag at the very end
            if (!empty($trimmedContent) && substr($trimmedContent, -1) !== "\n") {
                $phpContent = $trimmedContent . "\n";
            } elseif (empty($trimmedContent) && strpos($phpContent, "<?php") === 0 && strlen(trim($phpContent)) <= 6) {
                // Handles cases like "<?php" or "<?php\n" to ensure define is on next line
                $phpContent = rtrim($phpContent) . "\n";
            }
            $phpContent .= $newDefineLine . "\n";
        }
    }
}

/**
 * Updates or adds a variable assignment (e.g., $var = 'value';) in a PHP content string.
 * Preserves existing indentation if the variable is found and replaced.
 * Ensures the content starts with <?php if it was initially empty or lacked the tag.
 * Appends before a closing ?> tag if present at the end, otherwise appends to the end.
 */
function updateOrAddPhpVariable(&$phpContent, $variableName, $variableValue)
{
    $escapedValue = addslashes($variableValue);
    $newVariableLine = "\$$variableName = '$escapedValue';";
    // Regex to find an existing variable assignment, capturing leading code/whitespace
    $pattern = "/^(.*)\\$" . preg_quote($variableName, '/') . "\s*=\s*['\"].*?['\"]\s*;/m";

    $count = 0;
    $phpContent = preg_replace_callback($pattern, function ($matches) use ($newVariableLine) {
        return $matches[1] . $newVariableLine; // Prepend captured leading whitespace
    }, $phpContent, 1, $count);

    if ($count === 0) { // Variable not found, append it
        $trimmedContent = rtrim(str_replace("\r\n", "\n", $phpContent)); // Normalize EOL and rtrim

        $closingTag = '?>';
        if (substr($trimmedContent, -strlen($closingTag)) === $closingTag) {
            $contentBeforeTag = rtrim(substr($trimmedContent, 0, -strlen($closingTag)));
            if (!empty($contentBeforeTag) && substr($contentBeforeTag, -1) !== "\n") {
                $contentBeforeTag .= "\n";
            }
            $phpContent = $contentBeforeTag . $newVariableLine . "\n" . $closingTag . "\n";
        } else {
            if (!empty($trimmedContent) && substr($trimmedContent, -1) !== "\n") {
                $phpContent = $trimmedContent . "\n";
            } elseif (empty($trimmedContent) && strpos($phpContent, "<?php") === 0 && strlen(trim($phpContent)) <= 6) {
                $phpContent = rtrim($phpContent) . "\n";
            }
            $phpContent .= $newVariableLine . "\n";
        }
    }
}

/** @return array<int, mixed> */
function installerPdoOptions(bool $withFetchAssoc = false): array
{
    $opts = [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci',
    ];
    if ($withFetchAssoc) {
        $opts[PDO::ATTR_DEFAULT_FETCH_MODE] = PDO::FETCH_ASSOC;
    }
    return $opts;
}

function installerMysqlDsn(string $host, ?string $dbName = null): string
{
    $dsn = 'mysql:host=' . $host . ';charset=utf8mb4';
    if ($dbName !== null && $dbName !== '') {
        $dsn .= ';dbname=' . $dbName;
    }
    return $dsn;
}

function installColumnExists(PDO $pdo, string $table, string $column): bool
{
    $stmt = $pdo->prepare(
        'SELECT COUNT(*) FROM information_schema.COLUMNS
         WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?'
    );
    $stmt->execute([$table, $column]);
    return (int) $stmt->fetchColumn() > 0;
}

function installForeignKeyOnColumnExists(PDO $pdo, string $table, string $column): bool
{
    $stmt = $pdo->prepare(
        'SELECT COUNT(*) FROM information_schema.KEY_COLUMN_USAGE
         WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?
         AND REFERENCED_TABLE_NAME IS NOT NULL'
    );
    $stmt->execute([$table, $column]);
    return (int) $stmt->fetchColumn() > 0;
}


// --- Process Actions ---

if (isset($_POST['check_db'])) {
    $db_host = $session_form_data['db_host'] ?? '';
    $db_name = $session_form_data['db_name'] ?? '';
    $db_user = $session_form_data['db_user'] ?? '';
    $db_pass = $session_form_data['db_pass'] ?? '';
    $create_db = isset($session_form_data['create_db']) && $session_form_data['create_db'] === '1';

    if (empty($db_host) || empty($db_name) || empty($db_user) || !isset($db_pass)) {
        $errors[] = "Database host, name, and username are required. Password must be provided (can be empty).";
        $_SESSION['db_connection_verified'] = false;
        $step_to_display = 1;
    } else {
        try {
            // First, try to connect to the specific database
            $connected_to_db = false;

            try {
                $pdo = new PDO(
                    installerMysqlDsn($db_host, $db_name),
                    $db_user,
                    $db_pass,
                    installerPdoOptions(true)
                );
                // Set the timezone for the database session to UTC for consistency
                $pdo->exec("SET time_zone = '+00:00'");
                $connected_to_db = true;

            } catch (PDOException $e) {
                // If database doesn't exist and create_db is checked, try to create it
                if ($create_db && (strpos($e->getMessage(), 'Unknown database') !== false)) {
                    try {
                        // Connect without specifying database
                        $pdo_create = new PDO(
                            installerMysqlDsn($db_host),
                            $db_user,
                            $db_pass,
                            installerPdoOptions()
                        );

                        // Create the database
                        $pdo_create->exec("CREATE DATABASE IF NOT EXISTS `{$db_name}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");

                        // Now try to connect to the newly created database
                        $pdo = new PDO(
                            installerMysqlDsn($db_host, $db_name),
                            $db_user,
                            $db_pass,
                            installerPdoOptions(true)
                        );
                        // Set the timezone for the database session to UTC for consistency
                        $pdo->exec("SET time_zone = '+00:00'");
                        $connected_to_db = true;

                        // Add success message about database creation
                        $_SESSION['db_created_message'] = "Database '{$db_name}' was created successfully!";

                    } catch (PDOException $create_error) {
                        throw new PDOException("Failed to create database: " . $create_error->getMessage());
                    }
                } else {
                    // Re-throw the original error
                    throw $e;
                }
            }

            if ($connected_to_db) {
                $_SESSION['db_connection_verified'] = true;
                $step_to_display = 2;
            }

        } catch (PDOException $e) {
            // Sanitize error message to prevent information disclosure
            $safe_error = "Database connection failed. Please ensure the database exists and credentials are correct.";
            if (strpos($e->getMessage(), 'Access denied') !== false) {
                $safe_error .= " (Access denied - check username/password)";
            } elseif (strpos($e->getMessage(), 'Unknown database') !== false) {
                if ($create_db) {
                    $safe_error = "Failed to create database. Please check if the user has CREATE privileges.";
                } else {
                    $safe_error .= " (Database not found - check database name or enable 'Create database if it doesn't exist')";
                }
            } elseif (strpos($e->getMessage(), "Can't connect") !== false) {
                $safe_error .= " (Cannot connect to server - check host/port)";
            } elseif (strpos($e->getMessage(), 'Failed to create database') !== false) {
                $safe_error = $e->getMessage(); // This is already a safe error message we created
            }
            $errors[] = $safe_error;
            error_log("Database connection error: " . $e->getMessage()); // Log full error for debugging
            $_SESSION['db_connection_verified'] = false;
            $step_to_display = 1;
        }
    }
} elseif (isset($_POST['setup_db'])) {
    $site_name = $session_form_data['site_name'] ?? '';
    $admin_email = $session_form_data['admin_email'] ?? '';
    $admin_password_plain = $_POST['admin_password'] ?? ''; // Keep plain for createTables
    $confirm_password = $_POST['confirm_password'] ?? '';

    if (!isset($_SESSION['db_connection_verified']) || !$_SESSION['db_connection_verified']) {
        $errors[] = "Database connection not verified. Please complete Step 1 first.";
        $step_to_display = 1;
    } elseif (empty($site_name) || empty($admin_email) || empty($admin_password_plain)) {
        $errors[] = "Site name, admin email, and admin password are required.";
        $step_to_display = 2;
    } elseif (!filter_var($admin_email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Please provide a valid admin email address.";
        $step_to_display = 2;
    } elseif (strlen($admin_password_plain) < 8) {
        $errors[] = "Admin password must be at least 8 characters long.";
        $step_to_display = 2;
    } elseif ($admin_password_plain !== $confirm_password) {
        $errors[] = "Admin passwords do not match.";
        $step_to_display = 2;
    } else {
        // Create config directory if it doesn't exist
        if (!is_dir($configDir)) {
            if (!@mkdir($configDir, 0755, true) && !is_dir($configDir)) {
                $errors[] = "Failed to create config directory ($configDir). Please ensure the parent directory ('" . dirname($configDir) . "') is writable by the web server.";
                $step_to_display = 2;
            }
        } elseif (!is_writable($configDir)) {
            $errors[] = "Config directory ($configDir) is not writable. Please check permissions.";
            $step_to_display = 2;
        }

        // Handle config.php
        if (empty($errors)) {
            $configContent = "";
            if (file_exists($configFile)) {
                $configContent = file_get_contents($configFile);
                if ($configContent === false) {
                    $errors[] = "Failed to read existing config file ($configFile). Will attempt to create a new one.";
                    $configContent = "<?php\n";
                } elseif (empty(trim($configContent))) { // File exists but is empty
                    $configContent = "<?php\n";
                } elseif (strpos(ltrim($configContent), '<?php') !== 0 && strpos(ltrim($configContent), '<?=') !== 0) {
                    $configContent = "<?php\n" . ltrim($configContent); // Prepend <?php if missing
                }
            } else {
                $configContent = "<?php\n"; // New file
            }

            if (empty($errors)) { // Proceed if no prior error and content is ready
                updateOrAddPhpDefine($configContent, 'BASE_URL', $baseUrl);
                updateOrAddPhpDefine($configContent, 'SITE_NAME', $site_name);

                if (file_put_contents($configFile, $configContent) === false) {
                    $error_info = error_get_last();
                    $errors[] = "Failed to write config file ($configFile). " . ($error_info['message'] ?? 'Unknown error') . ". Please check directory permissions.";
                    error_log("Installation Error: Failed to write to $configFile. Error: " . print_r($error_info, true));
                } else {
                    @chmod($configFile, 0640);
                }
            }
        }

        // Handle database.php
        if (empty($errors)) {
            $dbConfigContent = "";
            if (file_exists($databaseConfigFile)) {
                $dbConfigContent = file_get_contents($databaseConfigFile);
                if ($dbConfigContent === false) {
                    $errors[] = "Failed to read existing database config file ($databaseConfigFile). Will attempt to create a new one.";
                    $dbConfigContent = "<?php\n";
                } elseif (empty(trim($dbConfigContent))) { // File exists but is empty
                    $dbConfigContent = "<?php\n";
                } elseif (strpos(ltrim($dbConfigContent), '<?php') !== 0 && strpos(ltrim($dbConfigContent), '<?=') !== 0) {
                    $dbConfigContent = "<?php\n" . ltrim($dbConfigContent); // Prepend <?php if missing
                }
            } else {
                $dbConfigContent = "<?php\n"; // New file
            }

            if (empty($errors)) { // Proceed if no prior error
                updateOrAddPhpVariable($dbConfigContent, 'host', $session_form_data['db_host'] ?? '');
                updateOrAddPhpVariable($dbConfigContent, 'dbname', $session_form_data['db_name'] ?? '');
                updateOrAddPhpVariable($dbConfigContent, 'username', $session_form_data['db_user'] ?? '');
                updateOrAddPhpVariable($dbConfigContent, 'password', $session_form_data['db_pass'] ?? '');

                if (file_put_contents($databaseConfigFile, $dbConfigContent) === false) {
                    $error_info = error_get_last();
                    $errors[] = "Failed to write database config file ($databaseConfigFile). " . ($error_info['message'] ?? 'Unknown error') . ". Please check directory permissions.";
                    error_log("Installation Error: Failed to write to $databaseConfigFile. Error: " . print_r($error_info, true));
                } else {
                    @chmod($databaseConfigFile, 0640);
                }
            }
        }

        // Create database tables and admin user
        if (empty($errors)) {
            ob_start(); // Start output buffering for createTables messages
            try {
                // Use verified DB credentials from session for setup
                $db_host = $session_form_data['db_host'] ?? '';
                $db_name = $session_form_data['db_name'] ?? '';
                $db_user = $session_form_data['db_user'] ?? '';
                $db_pass = $session_form_data['db_pass'] ?? '';

                $pdo = new PDO(
                    installerMysqlDsn($db_host, $db_name),
                    $db_user,
                    $db_pass,
                    installerPdoOptions()
                );
                // Set the timezone for the database session to UTC for table creation
                $pdo->exec("SET time_zone = '+00:00'");

                $detailed_output_from_function = createTablesBasic($pdo, $admin_email, $admin_password_plain);
                $output .= $detailed_output_from_function; // Append to the main output

                $success = true;
                $_SESSION['install_final_admin_email'] = $admin_email;

                // NOW mark the application as fully installed after successful database setup
                if (file_exists($configFile)) {
                    $configContent = file_get_contents($configFile);
                    if ($configContent !== false) {
                        updateOrAddPhpDefine($configContent, 'APP_INSTALLED', 'true');
                        updateOrAddPhpDefine($configContent, 'SETUP_DONE', 'true');
                        if (file_put_contents($configFile, $configContent) === false) {
                            error_log("Installation Warning: Failed to update setup state in $configFile");
                        }
                        @chmod($configFile, 0640);
                    }
                }

                // Clean up session data after successful installation
                unset($_SESSION['install_form_data']);
                unset($_SESSION['db_connection_verified']);

            } catch (PDOException $e) { // Catch PDO connection errors for table creation phase
                $stray_echoes = ob_get_clean(); // Clean the buffer first
                if (!empty($stray_echoes)) {
                    $output .= $stray_echoes;
                }

                // Ensure any orphaned transaction is rolled back
                try {
                    if (isset($pdo) && $pdo->inTransaction()) {
                        $pdo->rollback();
                    }
                } catch (Exception $rollbackException) {
                    error_log("Transaction rollback failed: " . $rollbackException->getMessage());
                }

                $errors[] = "Database operation failed during table setup. Please verify your database user has sufficient privileges and try again.";
                $success = false;
                error_log("PDO Error during table setup: " . $e->getMessage());
            } catch (Exception $e) { // Catch general exceptions from createTables
                $stray_echoes = ob_get_clean(); // Clean the buffer first
                if (!empty($stray_echoes)) {
                    $output .= $stray_echoes;
                }

                // Ensure any orphaned transaction is rolled back
                try {
                    if (isset($pdo) && $pdo->inTransaction()) {
                        $pdo->rollback();
                    }
                } catch (Exception $rollbackException) {
                    error_log("Transaction rollback failed: " . $rollbackException->getMessage());
                }

                $errors[] = "An unexpected error occurred during database setup. Please check the server error log and try again.";
                $success = false;
                error_log("General Error during table setup: " . $e->getMessage());
            }

            // Final cleanup of any remaining output buffer
            if (ob_get_level() > 0) {
                $remaining_output = ob_get_clean();
                if (!empty($remaining_output)) {
                    $output .= "<p>Additional output: " . htmlspecialchars($remaining_output) . "</p>";
                }
            }
        }
        if (!empty($errors)) { // If any error occurred during this block
            $step_to_display = 2; // Stay on step 2 to show errors
        }
    }
}


// Schema: createTablesBasic() in includes/schema_basic_install.php

?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Installation Wizard</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .step {
            display: none;
        }

        .step.active {
            display: block;
        }

        .form-group {
            margin-bottom: 1rem;
        }

        .card-body .alert+.progress,
        .card-body .alert+form .progress {
            margin-top: 1.5rem;
        }

        /* Add space after error alert */
    </style>
</head>

<body class="bg-light">
    <div class="container py-5">
        <center>
            <h4>SupportEngine Basic - Installation</h4>
            <p><a href="https://supportengine.cloud/help/ticket_create" target="_blank">Contact us</a> if you need
                assistance</p>
        </center>
        <div class="row justify-content-center">
            <div class="col-md-8 col-lg-6">
                <div class="card shadow">
                    <div class="card-header bg-primary text-white">
                        <h4 class="mb-0">Installation Wizard</h4>
                    </div>
                    <div class="card-body">
                        <?php if (!empty($errors)): ?>
                            <div class="alert alert-danger">
                                <?php foreach ($errors as $error): ?>
                                    <p class="mb-1"><?php echo htmlspecialchars($error); ?></p>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>

                        <?php if (isset($_SESSION['db_created_message'])): ?>
                            <div class="alert alert-success">
                                <i class="bi bi-check-circle-fill"></i>
                                <?php echo htmlspecialchars($_SESSION['db_created_message']); ?>
                            </div>
                            <?php unset($_SESSION['db_created_message']); // Clear the message after displaying ?>
                        <?php endif; ?>

                        <?php if (!empty($output) && !$success && !empty($errors)): // Show output log if errors occurred during setup_db ?>
                            <div class="alert alert-info mt-3">
                                <h6>Setup Log:</h6>
                                <pre
                                    style="white-space: pre-wrap; word-wrap: break-word; max-height: 200px; overflow-y: auto; background-color: #f8f9fa; padding: 10px; border-radius: 4px; border: 1px solid #dee2e6;"><?php echo htmlspecialchars(strip_tags($output)); // strip_tags to remove any HTML from createTables echoes ?></pre>
                            </div>
                        <?php endif; ?>


                        <?php if ($success): ?>
                            <div class="alert alert-success">
                                <h5>Installation Completed Successfully!</h5>
                                <?php if (!empty($output))
                                    echo "<div class='mt-3 p-3 bg-light rounded'><p><strong>Setup Details:</strong></p>" . strip_tags($output, '<p>') . "</div>"; ?>
                                <div class="mt-4 p-3 bg-light rounded">
                                    <h6>Admin Account Details:</h6>
                                    <p><strong>Email:</strong>
                                        <?php echo htmlspecialchars($_SESSION['install_final_admin_email'] ?? 'N/A'); ?></p>
                                    <p><strong>Password:</strong> The password you provided during installation</p>
                                    <p class="text-danger"><strong>Important:</strong> Delete the <code>install.php</code>
                                        file from your server.</p>
                                </div>
                                <div class="mt-3">
                                    <a href="<?php echo htmlspecialchars($baseUrl); ?>/index" class="btn btn-primary">Go to
                                        Homepage</a>
                                   
                                </div>
                            </div>
                        <?php else: ?>
                            <div class="progress mb-4">
                                <?php
                                if ($success) {
                                    $progress_percentage = 100;
                                } elseif ($step_to_display === 2) {
                                    $progress_percentage = 75;
                                } else {
                                    $progress_percentage = 50;
                                }
                                ?>
                                <div class="progress-bar" role="progressbar"
                                    style="width: <?php echo $progress_percentage; ?>%"
                                    aria-valuenow="<?php echo $progress_percentage; ?>" aria-valuemin="0"
                                    aria-valuemax="100">Step <?php echo $step_to_display; ?> of 2</div>
                            </div>

                            <form method="post" id="installForm" action="install.php" novalidate>

                                <!-- Step 1: Database Configuration -->
                                <div class="step <?php echo $step_to_display === 1 ? 'active' : ''; ?>" id="step1">
                                    <h5 class="mb-4">Step 1: MySQL Database Configuration</h5>
                                    <p>Configure your database connection. If the database doesn't exist, you can check the
                                        option below to create it automatically.</p>
                                    <div class="form-group">
                                        <label for="db_host" class="form-label">Database Host</label>
                                        <input type="text" class="form-control" id="db_host" name="db_host"
                                            value="<?php echo htmlspecialchars($session_form_data['db_host'] ?? 'localhost'); ?>"
                                            required>
                                    </div>
                                    <div class="form-group">
                                        <label for="db_name" class="form-label">Database Name</label>
                                        <input type="text" class="form-control" id="db_name" name="db_name"
                                            value="<?php echo htmlspecialchars($session_form_data['db_name'] ?? ''); ?>"
                                            required>
                                    </div>
                                    <div class="form-group">
                                        <label for="db_user" class="form-label">Database Username</label>
                                        <input type="text" class="form-control" id="db_user" name="db_user"
                                            value="<?php echo htmlspecialchars($session_form_data['db_user'] ?? 'root'); ?>"
                                            required>
                                    </div>
                                    <div class="form-group">
                                        <label for="db_pass" class="form-label">Database Password</label>
                                        <input type="password" class="form-control" id="db_pass" name="db_pass"
                                            value="<?php echo htmlspecialchars($session_form_data['db_pass'] ?? ''); ?>">
                                        <small class="form-text text-muted">Can be empty if your database user has no
                                            password.</small>
                                    </div>
                                    <div class="form-group">
                                        <div class="form-check">
                                            <input type="checkbox" class="form-check-input" id="create_db" name="create_db"
                                                value="1" <?php echo (!empty($session_form_data['create_db']) && $session_form_data['create_db'] === '1') ? 'checked' : ''; ?>>
                                            <label class="form-check-label" for="create_db">
                                                Create database if it doesn't exist
                                            </label>
                                            <small class="form-text text-muted d-block">Check this if you want the installer
                                                to create the database automatically. Requires CREATE privileges for the
                                                database user.</small>
                                        </div>
                                    </div>
                                    <div class="mt-4">
                                        <button type="submit" class="btn btn-primary" name="check_db" id="nextBtn1">Next
                                            →</button>
                                    </div>
                                </div>

                                <!-- Step 2: Site Configuration -->
                                <div class="step <?php echo $step_to_display === 2 ? 'active' : ''; ?>" id="step2">
                                    <h5 class="mb-4">Step 2: Site & Admin User Configuration</h5>
                                    <div class="form-group">
                                        <label for="site_name" class="form-label">Site Name</label>
                                        <input type="text" class="form-control" id="site_name" name="site_name"
                                            value="<?php echo htmlspecialchars($session_form_data['site_name'] ?? 'My Site'); ?>"
                                            required>
                                    </div>
                                    <div class="form-group">
                                        <label for="admin_email" class="form-label">Admin Email</label>
                                        <input type="email" class="form-control" id="admin_email" name="admin_email"
                                            value="<?php echo htmlspecialchars($session_form_data['admin_email'] ?? ''); ?>"
                                            required>
                                    </div>
                                    <div class="form-group">
                                        <label for="admin_password" class="form-label">Admin Password</label>
                                        <input type="password" class="form-control" id="admin_password"
                                            name="admin_password" required>
                                    </div>
                                    <div class="form-group">
                                        <label for="confirm_password" class="form-label">Confirm Password</label>
                                        <input type="password" class="form-control" id="confirm_password"
                                            name="confirm_password" required>
                                    </div>
                                    <div class="mt-4">
                                        <button type="submit" class="btn btn-secondary" id="prevBtn2" name="prev_to_1">←
                                            Previous</button>
                                        <button type="submit" class="btn btn-primary" id="setupBtn" name="setup_db">Complete
                                            Installation</button>
                                    </div>
                                </div>
                                <input type="hidden" name="step" value="<?php echo $step_to_display; ?>">
                            </form>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const installForm = document.getElementById('installForm');
            if (!installForm) return;

            // Step 1 validation
            const step1Div = document.getElementById('step1');
            if (step1Div) {
                const dbHost = document.getElementById('db_host');
                const dbName = document.getElementById('db_name');
                const dbUser = document.getElementById('db_user');
                // const dbPass = document.getElementById('db_pass'); // Password not strictly required for button enabling
                const nextBtn1 = document.getElementById('nextBtn1');

                function validateStep1Form() {
                    if (!nextBtn1 || !dbHost || !dbName || !dbUser) return;
                    // Basic check: host, name, user must not be empty. Password can be empty.
                    const isValid = dbHost.value.trim() !== '' &&
                        dbName.value.trim() !== '' &&
                        dbUser.value.trim() !== '';
                    nextBtn1.disabled = !isValid;
                }

                [dbHost, dbName, dbUser].forEach(input => {
                    if (input) input.addEventListener('input', validateStep1Form);
                });
                if (step1Div.classList.contains('active')) {
                    validateStep1Form(); // Initial check
                }
            }

            // Step 2 validation
            const step2Div = document.getElementById('step2');
            if (step2Div) {
                const siteNameInput = document.getElementById('site_name');
                const adminEmailInput = document.getElementById('admin_email');
                const adminPasswordInput = document.getElementById('admin_password');
                const confirmPasswordInput = document.getElementById('confirm_password');
                const setupBtn = document.getElementById('setupBtn');

                function validateStep2Form() {
                    if (!setupBtn || !siteNameInput || !adminEmailInput || !adminPasswordInput || !confirmPasswordInput) return;

                    let allValid = true;
                    if (siteNameInput.value.trim() === '') allValid = false;
                    if (adminEmailInput.value.trim() === '' || !adminEmailInput.checkValidity()) allValid = false; // Use HTML5 email validation
                    if (adminPasswordInput.value.trim() === '') allValid = false;
                    if (confirmPasswordInput.value.trim() === '') allValid = false;

                    if (adminPasswordInput.value !== confirmPasswordInput.value) {
                        allValid = false;
                        confirmPasswordInput.setCustomValidity("Passwords don't match.");
                    } else {
                        confirmPasswordInput.setCustomValidity("");
                    }

                    // Report validity for confirm password field if it has been touched and is invalid
                    if (document.activeElement === confirmPasswordInput || confirmPasswordInput.value !== "") {
                        confirmPasswordInput.reportValidity();
                    }

                    setupBtn.disabled = !allValid;
                }

                [siteNameInput, adminEmailInput, adminPasswordInput, confirmPasswordInput].forEach(input => {
                    if (input) input.addEventListener('input', validateStep2Form);
                });

                if (step2Div.classList.contains('active')) {
                    validateStep2Form(); // Initial check
                }
            }

            // Previous button handling (submits the form, PHP handles step change)
            const prevBtn2 = document.getElementById('prevBtn2');
            if (prevBtn2) {
                prevBtn2.addEventListener('click', function (e) {
                    // The button is type="submit" and has name="prev_to_1".
                    // PHP will handle the logic.
                    // If we wanted to ensure the hidden 'step' input is also set:
                    let stepHiddenInput = installForm.querySelector('input[name="step"]');
                    if (stepHiddenInput) {
                        stepHiddenInput.value = '1';
                    }
                    // Form submission will happen naturally due to type="submit".
                    // e.preventDefault(); // Not needed if PHP handles it purely on `prev_to_1`
                    // installForm.submit(); // Also not strictly needed if button is type="submit"
                });
            }
        });
    </script>
</body>

</html>