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

$jsonFile = '../js/database/ongoing-trade-information.json';

// Read current data
function readTradeData() {
    global $jsonFile;
    if (!file_exists($jsonFile)) {
        file_put_contents($jsonFile, '{}');
        return [];
    }
    $data = file_get_contents($jsonFile);
    return json_decode($data, true) ?: [];
}

// Write data
function writeTradeData($data) {
    global $jsonFile;
    file_put_contents($jsonFile, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
}

// Get request data
$input = json_decode(file_get_contents('php://input'), true);
$action = $input['action'] ?? '';

switch ($action) {
    case 'save':
        // Save trade payout info
        $tradeId = $input['tradeId'] ?? '';
        $assetName = $input['assetName'] ?? '';
        $payoutPercentage = $input['payoutPercentage'] ?? 0;
        $timestamp = $input['timestamp'] ?? time();
        $expiryTime = $input['expiryTime'] ?? 0;
        
        if (empty($tradeId)) {
            echo json_encode(['success' => false, 'message' => 'Trade ID required']);
            exit;
        }
        
        $data = readTradeData();
        $data[$tradeId] = [
            'tradeId' => $tradeId,
            'assetName' => $assetName,
            'payoutPercentage' => $payoutPercentage,
            'timestamp' => $timestamp,
            'expiryTime' => $expiryTime
        ];
        
        writeTradeData($data);
        echo json_encode(['success' => true, 'message' => 'Trade info saved']);
        break;
        
    case 'get':
        // Get trade payout info by ID
        $tradeId = $input['tradeId'] ?? '';
        
        if (empty($tradeId)) {
            echo json_encode(['success' => false, 'message' => 'Trade ID required']);
            exit;
        }
        
        $data = readTradeData();
        if (isset($data[$tradeId])) {
            echo json_encode(['success' => true, 'data' => $data[$tradeId]]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Trade not found']);
        }
        break;
        
    case 'delete':
        // Delete trade payout info
        $tradeId = $input['tradeId'] ?? '';
        
        if (empty($tradeId)) {
            echo json_encode(['success' => false, 'message' => 'Trade ID required']);
            exit;
        }
        
        $data = readTradeData();
        if (isset($data[$tradeId])) {
            unset($data[$tradeId]);
            writeTradeData($data);
            echo json_encode(['success' => true, 'message' => 'Trade info deleted']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Trade not found']);
        }
        break;
        
    case 'cleanup':
        // Auto-cleanup expired trades (5 seconds after expiry)
        $data = readTradeData();
        $currentTime = time();
        $cleaned = false;
        
        foreach ($data as $tradeId => $tradeInfo) {
            $expiryTime = $tradeInfo['expiryTime'] ?? 0;
            if ($expiryTime > 0 && ($currentTime - $expiryTime) >= 5) {
                unset($data[$tradeId]);
                $cleaned = true;
            }
        }
        
        if ($cleaned) {
            writeTradeData($data);
        }
        
        echo json_encode(['success' => true, 'message' => 'Cleanup completed']);
        break;
        
    default:
        echo json_encode(['success' => false, 'message' => 'Invalid action']);
}
?>
