<?php
session_start();
include "connection.php";
// Process API requests
$action = $_GET['action'] ?? '';

// Check authentication
if (!isset($_SESSION['user_id'])) {
    die(json_encode(['status_code' => 401, 'message' => 'Unauthorized']));
}

// Stock information
$STOCK_INFO = [
    'AAPL' => ['image' => 'aapl.png', 'name' => 'Apple'],
    'MSFT' => ['image' => 'microsoft.png', 'name' => 'Microsoft'],
    'GOOGL' => ['image' => 'googl.png', 'name' => 'Alphabet'],
    'AMZN' => ['image' => 'amazon.png', 'name' => 'Amazon'],
    'TSLA' => ['image' => 'tesla.png', 'name' => 'Tesla'],
    'FB' => ['image' => 'meta.png', 'name' => 'Meta Platforms'],
    'NVDA' => ['image' => 'nvda.png', 'name' => 'NVIDIA'],
    'NFLX' => ['image' => 'netflix.png', 'name' => 'Netflix'],
    'PYPL' => ['image' => 'paypal.png', 'name' => 'PayPal'],
    'INTC' => ['image' => 'intel.png', 'name' => 'Intel']
];

// Route API requests
switch ($action) {
    case 'buy':
    case 'sell':
        handleTrade($action === 'buy' ? 1 : 2);
        break;
    case 'trade-list':
        getTradeHistory();
        break;
    case 'balance':
        getBalance();
        break;
    case 'deduct-time':
        deductTime();
        break;
    case 'switch':
        switchMode();
    default:
        echo json_encode(['status_code' => 404, 'message' => 'Invalid action']);
}


function switchMode(){
    if (!isset($_SESSION['mode'])) {
        $_SESSION['mode'] = 'demo';
    }
    $_SESSION['mode'] = $_SESSION['mode'] === 'demo' ? 'live' : 'demo';

    echo json_encode([
        'status' => 'success',
        'new_mode' => $_SESSION['mode']
    ]);
    exit;
}

// Handle trade (buy/sell)
function handleTrade($tradeSide) {
    global $conn, $STOCK_INFO;
    
    $data = json_decode(file_get_contents('php://input'), true);
    
    if (!validateTradeInput($data)) {
        die(json_encode(['status_code' => 400, 'message' => 'Invalid input']));
    }
    
    $userId = $_SESSION['user_id'];
    // $balance = getUserBalance($userId);
    $balance = $_SESSION['mode'] == "demo" ? getUserDemoBalance($userId) : getUserTotalBalance($userId);
    
    if ($balance < $data['amount']) {
        die(json_encode(['status_code' => 400, 'message' => 'Insufficient balance']));
    }
    
    $conn->begin_transaction();

    if($_SESSION['mode'] == 'live'){
        try {
            $profit = calculateProfit($data['amount']);
            $account = 'live';
            $symbol = $data['stock'];
            $time = $data['time'];
            $signal = getSignal($symbol, $time, $tradeSide);

            if($signal){
                $type = 1;
            }else{
                $type = 2;
            }

            // echo $type;

            $tradeId = insertTrade($userId, $data, $account, $tradeSide, $STOCK_INFO[$data['stock']]['image'], $profit, $type);
            updateUserTotalBalance($userId, $data['amount'], false);
            
            $conn->commit();
            
            echo json_encode([
                'status_code' => 200,
                'message' => 'Live Trade placed successfully',
                'trade_id' => $tradeId
            ]);
            
        } catch (Exception $e) {
            $conn->rollback();
            die(json_encode(['status_code' => 500, 'message' => 'Transaction failed']));
        }
    }else{
        try {
            $profit = calculateProfit($data['amount']);
            $type = determineTradeOutcome();
            $account = 'demo';
            $tradeId = insertTrade($userId, $data, $account, $tradeSide, $STOCK_INFO[$data['stock']]['image'], $profit, $type);
            updateUserDemoBalance($userId, $data['amount'], false);
            
            $conn->commit();
            
            echo json_encode([
                'status_code' => 200,
                'message' => 'Demo Trade placed successfully',
                'trade_id' => $tradeId
            ]);
            
        } catch (Exception $e) {
            $conn->rollback();
            die(json_encode(['status_code' => 500, 'message' => 'Transaction failed']));
        }
    }
    
    
}

// Get trade history
function getTradeHistory() {
    global $conn;
    
    $userId = $_SESSION['user_id'];
    $query = "SELECT * FROM demo_trades WHERE user_id = ? ORDER BY created_at DESC LIMIT 10";
    $stmt = $conn->prepare($query);
    $stmt->bind_param('i', $userId);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $trades = $result->fetch_all(MYSQLI_ASSOC);
    
    echo json_encode($trades);
}

// Get user balance
function getBalance() {
    $userId = $_SESSION['user_id'];
    $balance = $_SESSION['mode'] == "demo" ? getUserDemoBalance($userId) : getUserTotalBalance($userId);
    
    echo json_encode(['status_code' => 200, 'balance' => $balance]);
}

// Deduct time from trade
function deductTime() {
    global $conn;
    
    $tradeId = $_GET['id'] ?? null;
    if (!$tradeId) {
        die(json_encode(['status_code' => 400, 'message' => 'Trade ID required']));
    }
    
    $trade = getTradeInfo($tradeId);
    
    if (!$trade) {
        die(json_encode(['status_code' => 404, 'message' => 'Trade not found']));
    }
    
    if ($trade['time'] > 0) {
        $newTime = $trade['time'] - 1;
        updateTradeTime($tradeId, $newTime);
        
        if ($newTime === 0) {
            processTradeOutcome($trade);
        }
        
        echo json_encode(['status_code' => 200, 'time_remaining' => $newTime]);
    } else {
        echo json_encode(['status_code' => 200, 'time_remaining' => 0]);
    }
}

// Helper functions
function validateTradeInput($data) {
    global $STOCK_INFO;
    
    if (!isset($data['stock']) || !isset($data['amount']) || !isset($data['time'])) {
        return false;
    }
    
    if (!array_key_exists($data['stock'], $STOCK_INFO)) {
        return false;
    }
    
    $validTimes = [5, 15, 30, 60, 300, 600, 1800];
    if (!in_array($data['time'], $validTimes)) {
        return false;
    }
    
    if (!is_numeric($data['amount']) || $data['amount'] <= 0) {
        return false;
    }
    
    return true;
}

function getUserTotalBalance($userId) {
    global $conn;
    
    $query = "SELECT total_balance FROM users WHERE id = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param('i', $userId);
    $stmt->execute();
    $result = $stmt->get_result();
    return $result->fetch_assoc()['total_balance'];
}

function getUserDemoBalance($userId) {
    global $conn;
    
    $query = "SELECT demo_balance FROM users WHERE id = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param('i', $userId);
    $stmt->execute();
    $result = $stmt->get_result();
    return $result->fetch_assoc()['demo_balance'];
}

function calculateProfit($amount) {
    $profitPercentage = 81;
    return ($profitPercentage / 100) * $amount;
}

function determineTradeOutcome() {
    return rand(1, 2);
}

function insertTrade($userId, $data, $account, $tradeSide, $image, $profit, $type) {
    global $conn;
    
    $query = "INSERT INTO demo_trades (user_id, symbol, account, amount, time, trade_side, image, profit, type) 
               VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
    $stmt = $conn->prepare($query);
    $stmt->bind_param('issdiisdi', 
        $userId, 
        $data['stock'], 
        $account,
        $data['amount'], 
        $data['time'], 
        $tradeSide, 
        $image, 
        $profit, 
        $type
    );
    $stmt->execute();
    return $conn->insert_id;
}

function updateUserTotalBalance($userId, $amount, $increase = true) {
    global $conn;
    
    $query = "UPDATE users SET total_balance = total_balance " . ($increase ? '+' : '-') . " ? WHERE id = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param('di', $amount, $userId);
    $stmt->execute();
}

function updateUserDemoBalance($userId, $amount, $increase = true) {
    global $conn;
    
    $query = "UPDATE users SET demo_balance = demo_balance " . ($increase ? '+' : '-') . " ? WHERE id = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param('di', $amount, $userId);
    $stmt->execute();
}

function getSignal($symbol, $time, $trade_side) {
    global $conn;
    
    $query = "SELECT * FROM signals WHERE symbol = ? AND time = ? AND trade_side = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param('sss', $symbol, $time, $trade_side);
    $stmt->execute();
    $result = $stmt->get_result();
    return $result->fetch_assoc();
}

function getTradeInfo($tradeId) {
    global $conn;
    
    $query = "SELECT * FROM demo_trades WHERE id = ? AND user_id = ?";
    $stmt = $conn->prepare($query);
    $userId = $_SESSION['user_id'];
    $stmt->bind_param('ii', $tradeId, $userId);
    $stmt->execute();
    $result = $stmt->get_result();
    return $result->fetch_assoc();
}

function updateTradeTime($tradeId, $newTime) {
    global $conn;
    
    $query = "UPDATE demo_trades SET time = ? WHERE id = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param('ii', $newTime, $tradeId);
    $stmt->execute();
}

function processTradeOutcome($trade) {
    global $conn;
    
    if ($trade['type'] == 1) { // Winning trade
        if($trade['account'] == 'live'){
            $conn->begin_transaction();
         
            try {
                $totalWin = $trade['amount'] + $trade['profit'];
                updateUserTotalBalance($trade['user_id'], $totalWin, true);
                
                $conn->commit();
            } catch (Exception $e) {
                $conn->rollback();
            }
        }else{
            $conn->begin_transaction();
        
            try {
                $totalWin = $trade['amount'] + $trade['profit'];
                updateUserDemoBalance($trade['user_id'], $totalWin, true);
                
                $conn->commit();
            } catch (Exception $e) {
                $conn->rollback();
            }
        }
        
    }
}

// Close database connection
$conn->close();
?>