<?php
header('Content-Type: application/json');

try {
    $input = json_decode(file_get_contents('php://input'), true);
    if (!$input || !isset($input['user_id'], $input['index'])) {
        throw new Exception('Missing required parameters');
    }

    $jsonFile = '../data.json';
    $jsonData = json_decode(file_get_contents($jsonFile), true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new Exception('Invalid data format');
    }

    $userId = $input['user_id'];
    $index = (int)$input['index'];

    if (!isset($jsonData[$userId]['user_withdrawals'][$index])) {
        throw new Exception('Withdrawal record not found');
    }

    $jsonData[$userId]['user_withdrawals'][$index]['status'] = 'failed';
    
    $result = file_put_contents($jsonFile, json_encode($jsonData, JSON_PRETTY_PRINT));
    if ($result === false) {
        throw new Exception('Failed to save data');
    }

    echo json_encode(['success' => true, 'message' => 'Status updated']);
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>