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

// Define the path to the JSON file
$jsonFilePath = '../data.json';

// Function to fetch JSON data
function fetchData($filePath) {
    if (!file_exists($filePath)) {
        return ['error' => 'Data file not found'];
    }
    $jsonContent = file_get_contents($filePath);
    return json_decode($jsonContent, true);
}

// Function to save JSON data
function saveData($filePath, $data) {
    return file_put_contents($filePath, json_encode($data, JSON_PRETTY_PRINT));
}

// Get POST data
$userId = $_POST['user_id'] ?? null;
$amount = $_POST['amount'] ?? null;
$date = $_POST['date'] ?? date('d/m/Y'); // Default to current date if not provided

// Validate required fields
if (!$userId) {
    echo json_encode(['success' => false, 'message' => 'User ID not provided']);
    exit;
}

if (!$amount || !is_numeric($amount)) {
    echo json_encode(['success' => false, 'message' => 'Valid amount is required']);
    exit;
}

// Load existing data
$data = fetchData($jsonFilePath);
if (isset($data['error'])) {
    echo json_encode(['success' => false, 'message' => $data['error']]);
    exit;
}

// Verify user exists
if (!isset($data[$userId])) {
    echo json_encode(['success' => false, 'message' => 'User not found']);
    exit;
}

// Create new inflow record
$newInflow = [
    'amount' => $amount,
    'date' => $date
];

// Initialize user_inflows array if it doesn't exist
if (!isset($data[$userId]['user_inflows'])) {
    $data[$userId]['user_inflows'] = [];
}

// Add new inflow to the beginning of the array (most recent first)
array_unshift($data[$userId]['user_inflows'], $newInflow);

// Save the updated data
if (saveData($jsonFilePath, $data)) {
    echo json_encode([
        'success' => true,
        'message' => 'Inflow added successfully',
        'newInflow' => $newInflow
    ]);
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to save data']);
}
?>