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

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $userID = $_SESSION['userID']; // Assume userID is stored in session
    $currentPassword = $_POST['currentPassword'];
    $newPassword = $_POST['newPassword'];
    $confirmPassword = $_POST['confirmPassword'];

    if ($newPassword !== $confirmPassword) {
        echo 'New passwords do not match.';
        exit;
    }

    // Fetch current password from database
    $sql = "SELECT password FROM users WHERE userID = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('i', $userID);
    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($storedPassword);
    $stmt->fetch();

    // Verify current password
    if ($currentPassword !== $storedPassword) {
        echo 'Current password is incorrect.';
        exit;
    }

    // Update password in database
    $updateSql = "UPDATE users SET password = ? WHERE userID = ?";
    $updateStmt = $conn->prepare($updateSql);
    $updateStmt->bind_param('si', $newPassword, $userID);

    if ($updateStmt->execute()) {
        echo 'Password changed successfully.';
    } else {
        echo 'Failed to change password.';
    }

    $stmt->close();
    $updateStmt->close();
    $conn->close();
}
?>