<?php
session_start();
include "../../connect/db.php"; // Database connection file
csrf_verify();

// Check if POST data is available for password reset
if (isset($_POST['cpassword']) && isset($_POST['npassword']) && isset($_POST['cnpassword'])) {
    $user = $_SESSION['chap']; // Assume user is stored in session
    $cpassword = mysqli_real_escape_string($mysqli, $_POST['cpassword']);
    $npassword = mysqli_real_escape_string($mysqli, $_POST['npassword']);
    $cnpassword = mysqli_real_escape_string($mysqli, $_POST['cnpassword']);

    // Validate new password
    if ($npassword !== $cnpassword) {
        echo "Passwords do not match.";
        exit;
    }

    // Fetch current password for the user
    $query = "SELECT password FROM users WHERE email = ?";
    $stmt = $mysqli->prepare($query);
    $stmt->bind_param('s', $user);
    $stmt->execute();
    $stmt->bind_result($currentPassword);
    $stmt->fetch();
    $stmt->close();

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

    // Update password in the database
    $updateQuery = "UPDATE users SET password = ? WHERE email = ?";
    $updateStmt = $mysqli->prepare($updateQuery);
    $updateStmt->bind_param('ss', $npassword, $user);
    if ($updateStmt->execute()) {
        echo "success"; // Return success response
    } else {
        echo "error"; // Return error response
    }
    $updateStmt->close();
}
?>
