<?php
session_start();

if (isset($_SESSION['user_id'])) {
    $user_id = $_SESSION['user_id'];

    // $_SESSION["user_id"] = $row["id"]; // Remove this line
include('connection.php');

    $currentPassword = $_POST['currentPassword'];
    $newPassword = $_POST['newPassword'];
    $confirmNewPassword = $_POST['confirmNewPassword'];

    // Sanitize user input (you should implement better input validation)
    $currentPassword = mysqli_real_escape_string($conn, $currentPassword);
    $newPassword = mysqli_real_escape_string($conn, $newPassword);
    $confirmNewPassword = mysqli_real_escape_string($conn, $confirmNewPassword);

    // Fetch the current password from the database
    $sql = "SELECT password FROM admin_login WHERE id = '$user_id'";
    $result = $conn->query($sql);

    if ($result && $result->num_rows == 1) {
        $row = $result->fetch_assoc();
        $db_password = $row["password"];

        // Compare the current password
        if ($currentPassword === $db_password) {
            if ($newPassword === $confirmNewPassword) {
                // Update the password
                $updateSql = "UPDATE admin_login SET password = '$newPassword' WHERE id = '$user_id'";
                if ($conn->query($updateSql) === TRUE) {
                    // header("Location: index.php?success=Password updated successfully!");
                    echo 'Password updated successfully!';
                    exit();
                } else {
                    echo "Error updating password: " . $conn->error;
                }
            } else {
                echo "New password and confirmation do not match.";
            }
        } else {
            echo "Current password is incorrect.";
        }
    } else {
        echo "User not found or multiple users with the same ID.";
    }

    $conn->close();
} else {
    echo "User not authenticated.";
}

?>