<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

header("Access-Control-Allow-Origin: *"); 
header("Content-Type: application/json; charset=UTF-8"); 
header("Access-Control-Allow-Methods: POST, OPTIONS"); 
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') exit(0);

require_once 'config.php';
require_once 'connection.php';

$data = json_decode(file_get_contents("php://input"), true);
$masterTradeId = $data['tradeid'] ?? null;
$masterEmail = $data['email'] ?? null;

if (!$masterTradeId || !$masterEmail) {
    echo json_encode(["status" => "error", "message" => "Master tradeid and email are required"]);
    exit;
}

// Step 1: Get master details including commission percentage
$sqlMaster = "SELECT tradeid, name, email, commission_percent FROM tbl_master WHERE tradeid = ? AND email = ?";
$stmtMaster = $conn->prepare($sqlMaster);
$stmtMaster->bind_param("is", $masterTradeId, $masterEmail);
$stmtMaster->execute();
$resultMaster = $stmtMaster->get_result();
$master = $resultMaster->fetch_assoc();

if (!$master) {
    echo json_encode(["status" => "error", "message" => "Master not found"]);
    exit;
}

// Step 2: Get all slave accounts linked to this master
$sqlSlave = "SELECT id, name, email, slavetrade FROM tbl_slave WHERE mastertrade = ?";
$stmtSlave = $conn->prepare($sqlSlave);
$stmtSlave->bind_param("i", $master['tradeid']);
$stmtSlave->execute();
$resultSlave = $stmtSlave->get_result();

$slaves = [];
while ($row = $resultSlave->fetch_assoc()) {
    $slaves[] = $row;
}

// Step 3: Connect to MT5 server
$mt5 = new MTWebAPI();
$connectResult = $mt5->Connect(MT5_SERVER_IP, MT5_SERVER_PORT, 30, MT5_LOGIN, MT5_PASSWORD);
if ($connectResult != 0) {
    echo json_encode(["status" => "error", "message" => "Failed to connect to MT5 server"]);
    exit;
}

// Step 4: Fetch profit of each slave and calculate commission
$totalCommission = 0;
$slaveDetails = [];

foreach ($slaves as $slave) {
    $login = $slave['slavetrade'];

    // Fetch total profit for slave from MT5 history (using timestamp for today or last processed)
    $fromTime = strtotime("today 00:00:00");
    $toTime = time();
    $totalDeals = 0;
    $mt5->DealGetTotal($login, $fromTime, $toTime, $totalDeals);

    $deals = [];
    if ($totalDeals > 0) {
        $mt5->DealGetPage($login, $fromTime, $toTime, 0, $totalDeals, $deals);
    }

    $profit = 0;
    foreach ($deals as $deal) {
        $profit += $deal['profit']; // accumulate profit
    }

    // Calculate commission
    $commission = $profit * ($master['commission_percent'] / 100);
    $totalCommission += $commission;

    // Store commission in DB (tbl_master_commission)
    $stmtInsert = $conn->prepare("INSERT INTO tbl_master_commission (master_tradeid, slave_tradeid, profit, commission, created_at) VALUES (?, ?, ?, ?, NOW())");
    $stmtInsert->bind_param("iidd", $master['tradeid'], $login, $profit, $commission);
    $stmtInsert->execute();

    $slaveDetails[] = [
        "slave_trade" => $login,
        "slave_name" => $slave['name'],
        "slave_email" => $slave['email'],
        "profit" => $profit,
        "commission" => $commission
    ];
}

// Step 5: Disconnect MT5
$mt5->Disconnect();

echo json_encode([
    "status" => "success",
    "master_tradeid" => $master['tradeid'],
    "master_name" => $master['name'],
    "commission_percent" => $master['commission_percent'],
    "total_commission" => $totalCommission,
    "slaves" => $slaveDetails
]);

$stmtMaster->close();
$stmtSlave->close();
$conn->close();
?>
