<?php
session_start();
include 'includes/dbconn.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$userID = $_SESSION['user_id'];
$currentPassword = $_POST['currentPassword'];
$newPassword = $_POST['newPassword'];
$confirmPassword = $_POST['confirmPassword'];

if ($newPassword !== $confirmPassword) {
    $_SESSION['error'] = "New passwords do not match.";
    header('Location: change_password.php');
    exit();
}

// Fetch the current password hash from the database
$stmt = $conn->prepare("SELECT password_hash FROM users WHERE user_id = ?");
$stmt->bind_param("i", $userID);
$stmt->execute();
$result = $stmt->get_result();
$userData = $result->fetch_assoc();
$stmt->close();

if (password_verify($currentPassword, $userData['password_hash'])) {
    // Proceed with changing the password
    $newPasswordHash = password_hash($newPassword, PASSWORD_DEFAULT);
    $updateStmt = $conn->prepare("UPDATE users SET password_hash = ?, last_password_change = CURRENT_TIMESTAMP WHERE user_id = ?");
    $updateStmt->bind_param("si", $newPasswordHash, $userID);
    $updateStmt->execute();
    $updateStmt->close();
    
    $_SESSION['success'] = "Password changed successfully.";
    header('Location: change_password.php');
    exit();
} else {
    $_SESSION['error'] = "Current password is incorrect.";
    header('Location: change_password.php');
    exit();
}
?>
