<?php
header("Content-Type: application/json");
require_once 'db.php'; // your connection file

$response = ["status" => false, "message" => "Invalid request"];

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $user_id = $_POST['user_id'] ?? '';
    $old_password = $_POST['old_password'] ?? '';
    $new_password = $_POST['new_password'] ?? '';

    if (empty($user_id) || empty($old_password) || empty($new_password)) {
        $response["message"] = "All fields are required";
        echo json_encode($response);
        exit;
    }

    // Sanitize input
    $user_id = intval($user_id);

    // Fetch user by ID
    $stmt = $conn->prepare("SELECT password FROM users WHERE id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $stmt->store_result();

    if ($stmt->num_rows === 0) {
        $response["message"] = "User not found";
        echo json_encode($response);
        exit;
    }

    $stmt->bind_result($hashed_password);
    $stmt->fetch();

    if (!password_verify($old_password, $hashed_password)) {
        $response["message"] = "Old password is incorrect";
        echo json_encode($response);
        exit;
    }

    // Hash new password
    $new_hashed = password_hash($new_password, PASSWORD_DEFAULT);

    // Update password
    $update = $conn->prepare("UPDATE users SET password = ? WHERE id = ?");
    $update->bind_param("si", $new_hashed, $user_id);

    if ($update->execute()) {
        $response["status"] = true;
        $response["message"] = "Password updated successfully";
    } else {
        $response["message"] = "Failed to update password";
    }

    $update->close();
    $stmt->close();
} else {
    $response["message"] = "Invalid request method";
}

echo json_encode($response);
$conn->close();
