<?php
session_start();

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

    // Include your database connection
    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 hr_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 with a prepared statement to avoid SQL injection
                $updateSql = "UPDATE hr_login SET password = ? WHERE id = ?";
                $stmt = $conn->prepare($updateSql);
                $stmt->bind_param("si", $newPassword, $user_id);

                if ($stmt->execute()) {
                    // Redirect back to the change password page with a success message
                    header("Location: change-password.php?success=Password updated successfully");
                    exit();
                } else {
                    // Redirect back to the change password page with an error message
                    header("Location: change-password.php?error=" . urlencode("Error updating password: " . $conn->error));
                    exit();
                }
            } else {
                // Redirect back to the change password page with an error message
                header("Location: change-password.php?error=" . urlencode("New password and confirmation do not match"));
                exit();
            }
        } else {
            // Redirect back to the change password page with an error message
            header("Location: change-password.php?error=" . urlencode("Current password is incorrect"));
            exit();
        }
    } else {
        // Redirect back to the change password page with an error message
        header("Location: change-password.php?error=" . urlencode("User not found or multiple users with the same ID"));
        exit();
    }

    $stmt->close();
    $conn->close();
} else {
    // Redirect back to the change password page with an error message
    header("Location: change-password.php?error=" . urlencode("User not authenticated"));
    exit();
}
?>
