<?php
// delete-inflow.php

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

// Get the raw POST data
$input = file_get_contents('php://input');
$data = json_decode($input, true);

// Validate input
if (!isset($data['user_id']) || !isset($data['index'])) {
    echo json_encode(['success' => false, 'message' => 'Invalid input']);
    exit;
}

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

// Load your JSON data (adjust path as needed)
$jsonFile = '../data.json';
$jsonData = json_decode(file_get_contents($jsonFile), true);

// Check if user exists and has inflows
if (!isset($jsonData[$userId]) || !isset($jsonData[$userId]['user_tax_payments'])) {
    echo json_encode(['success' => false, 'message' => 'User not found']);
    exit;
}

// Validate the index
if ($index < 0 || $index >= count($jsonData[$userId]['user_tax_payments'])) {
    echo json_encode(['success' => false, 'message' => 'Invalid index']);
    exit;
}

// Remove the inflow record
array_splice($jsonData[$userId]['user_tax_payments'], $index, 1);

// Save the updated JSON back to file
if (file_put_contents($jsonFile, json_encode($jsonData, JSON_PRETTY_PRINT))) {
    echo json_encode(['success' => true]);
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to save data']);
}