<?php
session_start();
include 'config.php';

// Vérifie si l'utilisateur est connecté
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

// Gestion du formulaire pour changer le mot de passe
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $current_password = trim($_POST['current_password']);
    $new_password = trim($_POST['new_password']);

    if (!empty($current_password) && !empty($new_password)) {
        // Récupère le mot de passe actuel dans la base
        $sql = "SELECT password FROM Admin WHERE id = ?";
        $stmt = mysqli_prepare($conn, $sql);
        mysqli_stmt_bind_param($stmt, "i", $_SESSION['user_id']);
        mysqli_stmt_execute($stmt);
        $result = mysqli_stmt_get_result($stmt);

        if ($row = mysqli_fetch_assoc($result)) {
            if (password_verify($current_password, $row['password'])) {
                // Met à jour le mot de passe
                $new_password_hashed = password_hash($new_password, PASSWORD_DEFAULT);
                $update_sql = "UPDATE Admin SET password = ? WHERE id = ?";
                $update_stmt = mysqli_prepare($conn, $update_sql);
                mysqli_stmt_bind_param($update_stmt, "si", $new_password_hashed, $_SESSION['user_id']);
                mysqli_stmt_execute($update_stmt);

                echo "Mot de passe changé avec succès.";
            } else {
                echo "Mot de passe actuel incorrect.";
            }
        }

        mysqli_stmt_close($stmt);
    } else {
        echo "Tous les champs sont requis.";
    }
}
mysqli_close($conn);
?>

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <title>Changer le mot de passe</title>
</head>
<body>
    <h1>Changer le mot de passe</h1>
    <form action="change_password.php" method="POST">
        <label for="current_password">Mot de passe actuel :</label><br>
        <input type="password" id="current_password" name="current_password" required><br><br>

        <label for="new_password">Nouveau mot de passe :</label><br>
        <input type="password" id="new_password" name="new_password" required><br><br>

        <input type="submit" value="Changer le mot de passe">
    </form>
    <br>
    <a href="admin.php">Retour au menu Administrateur</a>
</body>
</html>
