<?php
header("Content-Type: application/json");
require 'db.php';

$data = $_SERVER['REQUEST_METHOD'] === 'POST' ? $_POST : $_GET;

$user_id = $data['user_id'] ?? '';
$password = $data['password'] ?? '';
$new_pin = $data['new_pin'] ?? '';

if (!$user_id || !$password || !$new_pin) {
    echo json_encode(['success' => false, 'message' => 'All fields are required']);
    exit;
}

// Get user
$stmt = $conn->prepare("SELECT password FROM users WHERE id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();

if ($user = $result->fetch_assoc()) {
    if (!password_verify($password, $user['password'])) {
        echo json_encode(['success' => false, 'message' => 'Password is incorrect']);
        exit;
    }

    $update = $conn->prepare("UPDATE users SET pin = ? WHERE id = ?");
    $update->bind_param("si", $new_pin, $user_id);
    $update->execute();

    echo json_encode(['success' => true, 'message' => 'PIN updated successfully']);
} else {
    echo json_encode(['success' => false, 'message' => 'User not found']);
}
exit;
