<?php
require_once '../config.php';
require_once '../classes/Security.php';
require_once '../classes/Trading.php';
require_once '../classes/KYC.php';

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

// Check authentication
if (!Security::isAuthenticated()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$action = $_POST['action'] ?? '';

switch ($action) {
    case 'create_sell_order':
        $kyc = new KYC();
        $kycCheck = $kyc->canUserTrade($_SESSION['user_id']);
        
        if (!$kycCheck['can_trade']) {
            echo json_encode(['success' => false, 'message' => $kycCheck['message']]);
            exit;
        }
        
        $cryptoId = $_POST['crypto_id'] ?? '';
        $amount = $_POST['amount'] ?? 0;
        $pricePerUnit = $_POST['price_per_unit'] ?? 0;
        $paymentMethod = $_POST['payment_method'] ?? '';
        $paymentDetails = $_POST['payment_details'] ?? '';
        
        if (!$cryptoId || $amount <= 0 || $pricePerUnit <= 0 || !$paymentMethod || !$paymentDetails) {
            echo json_encode(['success' => false, 'message' => 'All fields are required']);
            exit;
        }
        
        $trading = new Trading();
        $result = $trading->createSellOrder(
            $_SESSION['user_id'],
            $cryptoId,
            $amount,
            $pricePerUnit,
            $paymentMethod,
            $paymentDetails
        );
        echo json_encode($result);
        break;
        
    case 'create_buy_order':
        $kyc = new KYC();
        $kycCheck = $kyc->canUserTrade($_SESSION['user_id']);
        
        if (!$kycCheck['can_trade']) {
            echo json_encode(['success' => false, 'message' => $kycCheck['message']]);
            exit;
        }
        
        $tradeId = $_POST['trade_id'] ?? '';
        
        if (!$tradeId) {
            echo json_encode(['success' => false, 'message' => 'Trade ID required']);
            exit;
        }
        
        $trading = new Trading();
        $result = $trading->createBuyOrder($_SESSION['user_id'], $tradeId);
        echo json_encode($result);
        break;
        
    case 'get_trades':
        $cryptoId = $_GET['crypto_id'] ?? null;
        $limit = $_GET['limit'] ?? 50;
        
        $trading = new Trading();
        $trades = $trading->getAvailableTrades($cryptoId, $limit);
        echo json_encode(['success' => true, 'trades' => $trades]);
        break;
        
    case 'get_user_trades':
        $status = $_GET['status'] ?? null;
        
        $trading = new Trading();
        $trades = $trading->getUserTrades($_SESSION['user_id'], $status);
        echo json_encode(['success' => true, 'trades' => $trades]);
        break;
        
    default:
        echo json_encode(['success' => false, 'message' => 'Invalid action']);
}
?>