<?php

// Display all errors
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (isset($_SESSION['last_activity']) && time() - $_SESSION['last_activity'] > 120) {
    session_unset();
    session_destroy();
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }
    $_SESSION['etape'] = 0;
}

$_SESSION['last_activity'] = time();

$etape = isset($_SESSION['etape']) ? $_SESSION['etape'] : 1;
$erreur = '';
$succes = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    if (isset($_POST['retour']) && $_POST['retour'] == '1') {
        if (isset($_POST['etape'])) {

            $_SESSION['etape'] = max(1, $_POST['etape'] - 1);
            $etape = $_SESSION['etape'];
        } else {
            $_SESSION['etape'] = 1;
            $etape = 1;
        }
    }

    if ($etape === 0) {
        $minVersion = '8.2.12';
        $messages = [];
        $allOk = true;

        // PHP Version check
        if (version_compare(PHP_VERSION, $minVersion, '<')) {
            $messages[] = "❌ PHP version must be $minVersion or higher. Current: " . PHP_VERSION;
            $allOk = false;
        } else {
            $messages[] = "✅ PHP version is OK: " . PHP_VERSION;
        }

        // MySQLnd check
        if (!function_exists('mysqli_get_client_stats') || !defined('MYSQLI_CLIENT_SSL')) {
            $messages[] = "❌ MySQLnd is not available.";
            $allOk = false;
        } else {
            $mysqlndFullVersion = mysqli_get_client_info(); // e.g. "mysqlnd 8.2.12"
            preg_match('/([\d\.]+)/', $mysqlndFullVersion, $matches);
            $mysqlndVersion = $matches[1] ?? '0.0.0';

            if (version_compare($mysqlndVersion, $minVersion, '<')) {
                $messages[] = "❌ MySQLnd version must be $minVersion or higher. Current: $mysqlndFullVersion";
                $allOk = false;
            } else {
                $messages[] = "✅ MySQLnd version is OK: $mysqlndFullVersion";
            }
        }

        // Extension checks
        $requiredExtensions = ['ldap', 'curl', 'mysqli'];
        foreach ($requiredExtensions as $ext) {
            if (!extension_loaded($ext)) {
                $messages[] = "❌ Extension <strong>$ext</strong> is not enabled.";
                $allOk = false;
            } else {
                $messages[] = "✅ Extension <strong>$ext</strong> is enabled.";
            }
        }

        // Final decision
        if ($allOk) {
            $_SESSION['etape'] = 1;
            $etape = 1;
        } else {
            $etape = 0;
        }
    }

    // Étape 1 : Connexion BDD
    elseif (isset($_POST['etape']) && $_POST['etape'] == 1) {
        $_SESSION['db_host'] = isset($_POST['db_host']) ? $_POST['db_host'] : 'localhost';
        $_SESSION['db_name'] = isset($_POST['db_name']) ? $_POST['db_name'] : '';
        $_SESSION['db_user'] = isset($_POST['db_user']) ? $_POST['db_user'] : 'root';
        $_SESSION['db_pass'] = isset($_POST['db_pass']) ? $_POST['db_pass'] : '';

        $_SESSION['site_name'] = addslashes(strtolower(trim($_POST['site_name'] ?? '')));

        $_SESSION['admin_user']   = trim($_POST['admin_user'] ?? '');
        $_SESSION['admin_pass']   = trim($_POST['admin_pass'] ?? '');
        $_SESSION['admin_nom']    = trim($_POST['admin_nom'] ?? '');
        $_SESSION['admin_prenom'] = trim($_POST['admin_prenom'] ?? '');
        $_SESSION['admin_email']  = trim($_POST['admin_email'] ?? '');


        mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
        try {
            $mysqli = new mysqli($_SESSION['db_host'], $_SESSION['db_user'], $_SESSION['db_pass'], $_SESSION['db_name']);
            $mysqli->set_charset("utf8mb4");
            $succes = "✅ Connexion à la base de données réussie !";
            $_SESSION['etape'] = 2;
            $etape = 2;
        } catch (mysqli_sql_exception $e) {
            $erreur = "❌ Erreur de connexion à la base de données : " . htmlspecialchars($e->getMessage());
            $_SESSION['etape'] = 1;
            $etape = 1;
        }
    }

    // Étape 2 : Config site
    elseif (isset($_POST['etape']) && $_POST['etape'] == 2) {
        $_SESSION['site_name'] = isset($_POST['site_name']) ? addslashes(strtolower(trim($_POST['site_name']))) : '';

        // Création du fichier config.php
        $config = "<?php\n";
        $config .= "define('DB_SYSTEM', 'mysql');\n";
        $config .= "define('DB_HOST', '{$_SESSION['db_host']}');\n";
        $config .= "define('DB_NAME', '{$_SESSION['db_name']}');\n";
        $config .= "define('DB_USER', '{$_SESSION['db_user']}');\n";
        $config .= "define('DB_PASS', '{$_SESSION['db_pass']}');\n";
        $config .= "define('SITE_NAME', '{$_SESSION['site_name']}');\n";
        file_put_contents(__DIR__ . '/../config.php', $config);

        // Connexion MySQL
        $mysqli = new mysqli($_SESSION['db_host'], $_SESSION['db_user'], $_SESSION['db_pass'], $_SESSION['db_name']);

        // Import .sql
        $sqlFile = __DIR__ . '/../src/database.sql';
        if (file_exists($sqlFile)) {
            $sql = file_get_contents($sqlFile);
            if ($sql) {
                $mysqli->multi_query($sql);
                while ($mysqli->more_results() && $mysqli->next_result()) {
                }
            }
        } else {
            $erreur = "⚠️ Le fichier <code>src/database.sql</code> est introuvable. Veuillez vérifier son emplacement.";
            $_SESSION['etape'] = 2;
            $etape = 2;
            return;
        }

        // Mise à jour nom du site
        $stmt = $mysqli->prepare("UPDATE parametres SET nom_site_cap = ? ;");
        if ($stmt) {
            $stmt->bind_param("s", $_SESSION['site_name']);
            $stmt->execute();
            $stmt->close();
        }

        $_SESSION['site_name'] = stripcslashes($_SESSION['site_name']);
        $_SESSION['etape'] = 3;
        $etape = 3;
    } elseif (isset($_POST['etape']) && $_POST['etape'] == 3) {
        $_SESSION['site_name'] = isset($_POST['site_name']) ? addslashes(strtolower(trim($_POST['site_name']))) : '';

        $_SESSION['use_ldap'] = $_POST['use_ldap'] ?? 'non';

        if ($_SESSION['use_ldap'] === 'oui') {
            $_SESSION['ldap_host'] = $_POST['ldap_host'] ?? '';
            $_SESSION['ldap_port'] = $_POST['ldap_port'] ?? '636';
            $_SESSION['bind_dn'] = $_POST['bind_dn'] ?? '';
            $_SESSION['bind_pass'] = $_POST['bind_pass'] ?? '';
            $_SESSION['base_dn'] = $_POST['base_dn'] ?? '';
        }

        $config = "<?php\n";
        $config .= "define('SHOW_PARAM', 'true');\n";
        $config = "\n";
        $config .= "define('DB_SYSTEM', 'mysql');\n";
        $config .= "define('DB_HOST', '{$_SESSION['db_host']}');\n";
        $config .= "define('DB_NAME', '{$_SESSION['db_name']}');\n";
        $config .= "define('DB_USER', '{$_SESSION['db_user']}');\n";
        $config .= "define('DB_PASS', '{$_SESSION['db_pass']}');\n";
        $config .= "define('SITE_NAME', '{$_SESSION['site_name']}');\n";
        $config .= "define('USE_LDAP', '" . ($_SESSION['use_ldap'] === 'oui' ? 'true' : 'false') . "');\n";
        if ($_SESSION['use_ldap'] === 'oui') {
            $config .= "define('LDAP_HOST', '{$_SESSION['ldap_host']}');\n";
            $config .= "define('LDAP_PORT', {$_SESSION['ldap_port']});\n";
            $config .= "define('BIND_DN', '{$_SESSION['bind_dn']}');\n";
            $config .= "define('BIND_PASS', '{$_SESSION['bind_pass']}');\n";
            $config .= "define('BASE_DN', '{$_SESSION['base_dn']}');\n";
        }
        file_put_contents(__DIR__ . '/../config.php', $config);

        $mysqli = new mysqli($_SESSION['db_host'], $_SESSION['db_user'], $_SESSION['db_pass'], $_SESSION['db_name']);
        $sqlFile = __DIR__ . '/../src/database.sql';
        if (file_exists($sqlFile)) {
            $sql = file_get_contents($sqlFile);
            if ($sql) {
                $mysqli->multi_query($sql);
                while ($mysqli->more_results() && $mysqli->next_result()) {
                }
            }
        } else {
            $erreur = "⚠️ Le fichier <code>src/database.sql</code> est introuvable.";
            $_SESSION['etape'] = 2;
            $etape = 2;
            return;
        }

        $stmt = $mysqli->prepare("UPDATE parametres SET nom_site_cap = ?;");
        if ($stmt) {
            $stmt->bind_param("s", $_SESSION['site_name']);
            $stmt->execute();
            $stmt->close();
        }

        $_SESSION['site_name'] = stripcslashes($_SESSION['site_name']);
        $_SESSION['etape'] = 4;
        $etape = 4;
    } elseif (isset($_POST['etape']) && $_POST['etape'] == 4) {
        $_SESSION['admin_user'] = trim($_POST['admin_user'] ?? '');
        $_SESSION['admin_pass'] = trim($_POST['admin_pass'] ?? '');
        $_SESSION['admin_nom'] = trim($_POST['admin_nom'] ?? '');
        $_SESSION['admin_prenom'] = trim($_POST['admin_prenom'] ?? '');
        $_SESSION['admin_email'] = trim($_POST['admin_email'] ?? '');

        $mysqli = new mysqli($_SESSION['db_host'], $_SESSION['db_user'], $_SESSION['db_pass'], $_SESSION['db_name']);

        $nom = 'Sécurité';
        $stmt = $mysqli->prepare("INSERT INTO `departements` (`id_departement`, `nom_departement`, `commentaire`, `lastmod_departement`, `creation_departement`) 
        VALUES
        (1, 'Sécurité', '', current_timestamp(), current_timestamp());");
        $stmt->bind_param("s", $nom);
        $stmt->execute();
        $stmt->close();

        $value = '1';
        $stmt = $mysqli->prepare("INSERT INTO `departement_user` (`id_departement_user`, `id_user`, `id_departement`, `lastmod_departement_user`, `creation_departement_user`) 
        VALUES 
        (NULL, ?, ?, current_timestamp(), current_timestamp());");
        $stmt->bind_param("ss",  $value,  $value);
        $stmt->execute();
        $stmt->close();

        $hashed_pass = password_hash($_SESSION['admin_pass'], PASSWORD_DEFAULT);
        $stmt = $mysqli->prepare("INSERT INTO users (username, password, lastname, firstname, email) VALUES (?, ?, ?, ?, ?)");
        $stmt->bind_param("sssss", $_SESSION['admin_user'], $hashed_pass, $_SESSION['admin_nom'], $_SESSION['admin_prenom'], $_SESSION['admin_email']);
        $stmt->execute();
        $stmt->close();

        $stmt = $mysqli->prepare("INSERT INTO `roles` (`id_role`, `role_name`, `role_comment`, `creation`, `lastmod`) VALUES
        (1, 'Administrateur', '', current_timestamp(), current_timestamp()),
        (2, 'Pilote', '', current_timestamp(), current_timestamp()),
        (3, 'Gestionnaire', '', current_timestamp(), current_timestamp());");
        $stmt->bind_param("ss",  $value,  $value);
        $stmt->execute();
        $stmt->close();

        $stmt = $mysqli->prepare("INSERT INTO `users_roles` (`id_ur`, `id_user`, `id_role`, `creation`, `lastmod`) VALUES
        (1, 1, 1, current_timestamp(), current_timestamp()),
        (2, 1, 2, current_timestamp(), current_timestamp()),
        (3, 1, 3, current_timestamp(), current_timestamp());");
        $stmt->bind_param("ss",  $value,  $value);
        $stmt->execute();
        $stmt->close();

        session_destroy();
        header('Location: ../index.php');
        exit;
    }
}
?>

<!DOCTYPE html>
<html lang="fr">

<head>
    <meta charset="UTF-8">
    <title>Taghilt - Installation de l'application</title>
    <link href="assets/vendor/bootstrap-5.3.3/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .spinner-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100vw;
            height: 100vh;
            background: rgba(255, 255, 255, 0.7);
            z-index: 9999;
            justify-content: center;
            align-items: center;
        }
    </style>
</head>

<body class="bg-light">
    <div class="spinner-overlay" id="spinner">
        <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">Chargement...</span>
        </div>
        <div class="ms-3 fw-bold">Installation en cours, veuillez patienter...</div>
    </div>

    <div class="container py-5">
        <div class="row justify-content-center">
            <div class="col-md-8 col-lg-6">
                <div class="card shadow-lg">
                    <div class="card-header bg-primary text-white">
                        <h3 class="mb-0">🛠 Assistant d'installation de l'application</h3>
                    </div>
                    <div class="card-body">
                        <?php if ($erreur): ?>
                            <div class="alert alert-danger"><?= $erreur ?></div>
                        <?php elseif ($succes): ?>
                            <div class="alert alert-success"><?= $succes ?></div>
                        <?php endif; ?>

                        <div class="mb-4">
                            <div class="progress">
                                <div class="progress-bar progress-bar-striped" role="progressbar"
                                    style="width: <?= $etape * 25 ?>%;" aria-valuenow="<?= $etape * 25 ?>"
                                    aria-valuemin="0" aria-valuemax="100">
                                    <?= "Étape $etape sur 4" ?>
                                </div>
                            </div>
                        </div>

                        <?php if ($etape === 0): ?>
                            <form method="POST">
                                <input type="hidden" name="etape" value="0">
                                <h5>🔎 System Check</h5>
                                <p class="text-muted">Checking PHP version, MySQLnd, and required PHP extensions...</p>

                                <?php if (!empty($messages)): ?>
                                    <div class="system-check-results">
                                        <?php foreach ($messages as $msg): ?>
                                            <p><?= $msg ?></p>
                                        <?php endforeach; ?>
                                    </div>
                                <?php endif; ?>
                                <?php if (!empty($errors)): ?>
                                    <div class="alert alert-danger">
                                        <ul>
                                            <?php foreach ($errors as $err): ?>
                                                <li><?= htmlspecialchars($err) ?></li>
                                            <?php endforeach; ?>
                                        </ul>
                                        <p>Please fix these issues before proceeding.</p>
                                    </div>
                                <?php else: ?>
                                    <div class="alert alert-success">
                                        ✅ All system requirements are met.
                                    </div>
                                    <button type="submit" class="btn btn-primary">Continue ➡</button>
                                <?php endif; ?>
                            </form>

                        <?php elseif ($etape === 1): ?>
                            <form method="POST">
                                <input type="hidden" name="etape" value="1">
                                <h5>🔌 Étape 1 : Connexion à la base de données</h5>
                                <p class="text-muted">Veuillez renseigner les informations de connexion à votre base de données MySQL.</p>

                                <div class="mb-3">
                                    <label class="form-label">Hôte de la base de données <span style="color: red; font-weight: bold;">*</span></label>
                                    <input type="text" name="db_host" class="form-control" required value="<?= $_SESSION['db_host'] ?? '' ?>">
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">Nom de la base <span style="color: red; font-weight: bold;">*</span></label>
                                    <input type="text" name="db_name" class="form-control" value="<?= $_SESSION['db_name'] ?? '' ?>" required>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">Nom d'utilisateur <span style="color: red; font-weight: bold;">*</span></label>
                                    <input type="text" name="db_user" class="form-control" value="<?= $_SESSION['db_user'] ?? '' ?>" required>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">Mot de passe</label>
                                    <input type="password" name="db_pass" class="form-control">
                                </div>
                                <button type="submit" name="retour" value="1" class="btn btn-secondary" formnovalidate>⬅ Retour</button>
                                <button type="submit" class="btn btn-primary">Suivant ➡</button>
                            </form>

                        <?php elseif ($etape === 2): ?>
                            <form method="POST" onsubmit="document.getElementById('spinner').style.display='flex';">
                                <input type="hidden" name="etape" value="2">
                                <h5>🏷️ Étape 2 : Configuration du site</h5>
                                <p class="text-muted">Choisissez un nom pour votre site.</p>

                                <div class="mb-3">
                                    <label class="form-label">Nom du site <span style="color: red; font-weight: bold;">*</span></label>
                                    <input type="text" name="site_name" class="form-control" value="<?= $_SESSION['site_name'] ?? '' ?>" required>
                                    <small class="form-text text-muted">Exemple : MonSite → enregistré comme <strong>monsite</strong></small>
                                </div>

                                <div class="d-flex justify-content-between">
                                    <button type="submit" name="retour" value="1" class="btn btn-secondary" formnovalidate>⬅ Retour</button>
                                    <button type="submit" class="btn btn-success">Suivant ➡</button>
                                </div>
                            </form>

                        <?php elseif ($etape === 3): ?>
                            <form method="POST" onsubmit="document.getElementById('spinner').style.display='flex';">
                                <input type="hidden" name="etape" value="3">
                                <h5>🏷️ Étape 3 : Configuration du site</h5>

                                <div class="mb-3">
                                    <label class="form-label">Souhaitez-vous utiliser la connexion Active Directory ?</label>
                                    <select class="form-select" name="use_ldap" id="use_ldap" onchange="toggleLdapFields()" required>
                                        <option value="non" <?= ($_SESSION['use_ldap'] ?? '') === 'non' ? 'selected' : '' ?>>Non</option>
                                        <option value="oui" <?= ($_SESSION['use_ldap'] ?? '') === 'oui' ? 'selected' : '' ?>>Oui</option>
                                    </select>
                                </div>

                                <div id="ldap-fields" style="display: none;">
                                    <div class="mb-3">
                                        <label class="form-label">LDAP Host <span style="color: red; font-weight: bold;">*</span></label>
                                        <input type="text" name="ldap_host" class="form-control" value="<?= $_SESSION['ldap_host'] ?? '' ?>" required>
                                    </div>
                                    <div class="mb-3">
                                        <label class="form-label">LDAP Port <span style="color: red; font-weight: bold;">*</span></label>
                                        <input type="number" name="ldap_port" class="form-control" value="<?= $_SESSION['ldap_port'] ?? '389' ?>" required>
                                    </div>
                                    <div class="mb-3">
                                        <label class="form-label">Bind DN <span style="color: red; font-weight: bold;">*</span></label>
                                        <input type="text" name="bind_dn" class="form-control" value="<?= $_SESSION['bind_dn'] ?? '' ?>" required>
                                    </div>
                                    <div class="mb-3">
                                        <label class="form-label">Bind Password <span style="color: red; font-weight: bold;">*</span></label>
                                        <input type="password" name="bind_pass" class="form-control" required>
                                    </div>
                                    <div class="mb-3">
                                        <label class="form-label">Base DN <span style="color: red; font-weight: bold;">*</span></label>
                                        <input type="text" name="base_dn" class="form-control" value="<?= $_SESSION['base_dn'] ?? '' ?>" required>
                                    </div>
                                </div>

                                <div class="d-flex justify-content-between">
                                    <button type="submit" name="retour" value="1" class="btn btn-secondary" formnovalidate>⬅ Retour</button>
                                    <button type="submit" class="btn btn-success">Suivant ➡</button>
                                </div>
                            </form>

                            <script>
                                function toggleLdapFields() {
                                    const useLdap = document.getElementById('use_ldap').value;
                                    document.getElementById('ldap-fields').style.display = useLdap === 'oui' ? 'block' : 'none';
                                }
                                window.addEventListener('DOMContentLoaded', toggleLdapFields);
                            </script>

                        <?php elseif ($etape === 4): ?>
                            <form method="POST">
                                <input type="hidden" name="etape" value="4">
                                <h5>👤 Étape 4 : Création de l'administrateur</h5>
                                <p class="text-muted">Définissez l'utilisateur par défaut qui aura un accès administrateur.</p>

                                <div class="mb-3">
                                    <label class="form-label">Nom d'utilisateur <span style="color: red; font-weight: bold;">*</span></label>
                                    <input type="text" name="admin_user" class="form-control" required>
                                </div>

                                <div class="mb-3">
                                    <label class="form-label">Mot de passe <span style="color: red; font-weight: bold;">*</span></label>
                                    <input type="password" name="admin_pass" class="form-control" value="<?= $_SESSION['admin_pass'] ?? '' ?>" required>
                                </div>

                                <div class="row mb-3">
                                    <div class="col-md-6">
                                        <label class="form-label">Prénom <span style="color: red; font-weight: bold;">*</span></label>
                                        <input type="text" name="admin_prenom" class="form-control" value="<?= $_SESSION['admin_prenom'] ?? '' ?>" required>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Nom <span style="color: red; font-weight: bold;">*</span></label>
                                        <input type="text" name="admin_nom" class="form-control" value="<?= $_SESSION['admin_nom'] ?? '' ?>" required>
                                    </div>
                                </div>

                                <div class="mb-3">
                                    <label class="form-label">Adresse e-mail <span style="color: red; font-weight: bold;">*</span></label>
                                    <input type="email" name="admin_email" class="form-control" value="<?= $_SESSION['admin_email'] ?? '' ?>" required>
                                </div>

                                <div class="d-flex justify-content-between">
                                    <button type="submit" name="retour" value="1" class="btn btn-secondary" formnovalidate>⬅ Retour</button>
                                    <button type="submit" class="btn btn-success">Terminer ✅</button>
                                </div>
                            </form>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>

</html>


