<?php
// mt5_profit_service.php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type");
header("Content-Type: application/json");

include "config.php";
include "/mt5_api/mt5_api.php"; // Include the MT5 API

$data = json_decode(file_get_contents("php://input"), true);
$user_id = $data['user_id'] ?? 0;

if (!$user_id) {
    echo json_encode(["success" => false, "message" => "Missing user id"]);
    exit;
}

// Get all trade IDs for this user
$stmt = $conn->prepare("SELECT trade_id FROM liveaccounts WHERE user_id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();
$trade_ids = [];
while($row = $result->fetch_assoc()) {
    $trade_ids[] = $row['trade_id'];
}

// MT5 Server connection details
$mt5_ip = "access.tgshost.org";
$mt5_port = 26043;
$mt5_login = "7020";
$mt5_password = "Aa@123456";

// Initialize MT5 API
$api = new MTWebAPI();
$profit_data = [];

try {
    // Connect to MT5 server
    $ret_code = $api->Connect($mt5_ip, $mt5_port, 5, $mt5_login, $mt5_password);
    
    if ($ret_code != MTRetCode::MT_RET_OK) {
        echo json_encode(["success" => false, "message" => "Failed to connect to MT5 server"]);
        exit;
    }
    
    // For each trade ID, get account information and calculate profit
    foreach ($trade_ids as $trade_id) {
        $login = intval($trade_id);
        
        // Get account information
        $account_info = null;
        $ret_code = $api->UserAccountGet($login, $account_info);
        
        if ($ret_code == MTRetCode::MT_RET_OK && $account_info) {
            // Calculate profit (Equity - Balance)
            $profit = $account_info->Equity - $account_info->Balance;
            
            $profit_data[$trade_id] = [
                'balance' => $account_info->Balance,
                'equity' => $account_info->Equity,
                'profit' => $profit,
                'margin' => $account_info->Margin,
                'free_margin' => $account_info->MarginFree
            ];
            
            // Update the cache table
            updateProfitCache($conn, $trade_id, $profit, $account_info->Equity);
        }
    }
    
    $api->Disconnect();
    
    echo json_encode([
        "success" => true,
        "profit_data" => $profit_data,
        "updated_at" => time()
    ]);
    
} catch (Exception $e) {
    echo json_encode(["success" => false, "message" => "Error: " . $e->getMessage()]);
}

// Function to update profit cache in database
function updateProfitCache($conn, $trade_id, $profit, $equity) {
    $stmt = $conn->prepare("
        INSERT INTO account_profits (trade_id, total_profit, equity, updated_at) 
        VALUES (?, ?, ?, NOW())
        ON DUPLICATE KEY UPDATE 
        total_profit = VALUES(total_profit), 
        equity = VALUES(equity), 
        updated_at = NOW()
    ");
    $stmt->bind_param("sdd", $trade_id, $profit, $equity);
    $stmt->execute();
}
?>