<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

require_once __DIR__ . '/config.php';
require_once __DIR__ . '/connection.php';
require_once __DIR__ . '/mt5_api/mt5_api.php';

// Input
$input = json_decode(file_get_contents('php://input'), true);
$follower_trade_id = intval($input['follower_trade_id'] ?? 0);
$follower_email = trim($input['follower_email'] ?? '');
$master_trade_id = intval($input['master_trade_id'] ?? 0);

if ($follower_trade_id <= 0 || $master_trade_id <= 0 || $follower_email === '') {
    echo json_encode(["success" => false, "message" => "Invalid input"]);
    exit;
}

// 1️⃣ Fetch slave account
$stmt = $conn->prepare("SELECT * FROM liveaccounts WHERE trade_id = ? AND email = ? LIMIT 1");
$stmt->bind_param("is", $follower_trade_id, $follower_email);
$stmt->execute();
$follower = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$follower || strtoupper($follower['account_type']) !== 'PAMM') {
    echo json_encode(["success" => false, "message" => "Follower PAMM account not found"]);
    exit;
}

// 2️⃣ Fetch master account
$stmt = $conn->prepare("SELECT * FROM liveaccounts WHERE trade_id = ? LIMIT 1");
$stmt->bind_param("i", $master_trade_id);
$stmt->execute();
$master = $stmt->get_result()->fetch_assoc();
$stmt->close();

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

// 3️⃣ Check approval for master if needed
if (intval($master['masteracc']) !== 2) {
    $stmt = $conn->prepare("SELECT status FROM copyaccounts WHERE slavetrade = ? AND mastertrade = ? ORDER BY id DESC LIMIT 1");
    $stmt->bind_param("ii", $follower_trade_id, $master_trade_id);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    if (!$row || intval($row['status']) !== 1) {
        echo json_encode(["success" => false, "message" => "Master not approved for follower"]);
        exit;
    }
}

$master_email = trim($master['email'] ?? '');
if ($master_email === '') {
    echo json_encode(["success" => false, "message" => "Master email missing"]);
    exit;
}

// 4️⃣ Fetch dynamic profit from pamm_profits
$stmt = $conn->prepare("
    SELECT profit_24h 
    FROM pamm_profits 
    WHERE slave_email = ? AND slave_trade_id = ? AND master_trade = ?
    ORDER BY id DESC LIMIT 1
");
$stmt->bind_param("sii", $follower_email, $follower_trade_id, $master_trade_id);
$stmt->execute();
$profitRow = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$profitRow || floatval($profitRow['profit_24h']) <= 0) {
    echo json_encode(["success" => false, "message" => "No profit available for distribution"]);
    exit;
}

$profit_amount = floatval($profitRow['profit_24h']); // dynamic profit
$event_uid = hash('sha256', $follower_trade_id . '|' . $master_trade_id . '|' . number_format($profit_amount, 8, '.', ''));

// 5️⃣ Check duplicate event
$stmt = $conn->prepare("SELECT id FROM pamm_profit_logs WHERE event_uid = ? LIMIT 1");
$stmt->bind_param("s", $event_uid);
$stmt->execute();
$dup = $stmt->get_result()->fetch_assoc();
$stmt->close();
if ($dup) {
    echo json_encode(["success" => false, "message" => "Duplicate event"]);
    exit;
}

// 6️⃣ Calculate shares
$user_share = round($profit_amount * 0.65, 8);
$master_share = round($profit_amount * 0.10, 8);

// //dynamic using master commission table
// // 6️⃣ Fetch master commission percentage (dynamic)
// $stmt = $conn->prepare("
//     SELECT commission_percent 
//     FROM pamm_master_commission 
//     WHERE master_trade_id = ? 
//     ORDER BY id DESC LIMIT 1
// ");
// $stmt->bind_param("i", $master_trade_id);
// $stmt->execute();
// $masterCommissionRow = $stmt->get_result()->fetch_assoc();
// $stmt->close();

// // If not found, default to 10%
// $master_percentage = $masterCommissionRow ? floatval($masterCommissionRow['commission_percent']) : 10.0;

// // Calculate dynamic shares
// $user_share = round($profit_amount * 0.65, 8);
// $master_share = round($profit_amount * ($master_percentage / 100), 8);


// 7️⃣ Fetch IB levels
$levels = [];
$q = $conn->query("SELECT level, percentage FROM pamm_ib_level_commission ORDER BY level ASC");
while ($r = $q->fetch_assoc()) {
    $levels[intval($r['level'])] = floatval($r['percentage']);
}

$ib_distributions = [];
$ib_total_share = 0.0;
for ($i = 1; $i <= 10; $i++) {
    $email = trim($follower['ib' . $i] ?? '');
    if ($email === '' || strtolower($email) === 'noib' || strtolower($email) === 'noibu') continue;
    if (!isset($levels[$i])) continue;
    $amt = round($profit_amount * ($levels[$i] / 100), 8);
    if ($amt <= 0) continue;
    $ib_distributions[] = ["level" => $i, "email" => $email, "amount" => $amt];
    $ib_total_share += $amt;
}

// 8️⃣ Connect MT5
$api = new MTWebAPI("WebAPITesterLocal", "./logs", true);
$ret = $api->Connect(MT5_SERVER_IP, MT5_SERVER_PORT, 5, MT5_SERVER_WEB_LOGIN, MT5_SERVER_WEB_PASSWORD);
if ($ret != MTRetCode::MT_RET_OK) {
    echo json_encode(["success" => false, "message" => "MT5 connection failed"]);
    exit;
}

$followerMT5 = new MTUser();
$retUGF = $api->UserGet((int)$follower_trade_id, $followerMT5);
$masterMT5 = new MTUser();
$retUGM = $api->UserGet((int)$master_trade_id, $masterMT5);

if ($retUGF != MTRetCode::MT_RET_OK || $retUGM != MTRetCode::MT_RET_OK) {
    $api->Disconnect();
    echo json_encode(["success" => false, "message" => "Follower or Master not found in MT5"]);
    exit;
}

// Handle Cent accounts
$followerCentMult = ($follower['account_type'] === 'Cent') ? 0.01 : 1.0;
$masterCentMult = ($master['account_type'] === 'Cent') ? 0.01 : 1.0;
$followerAmountMT5 = $user_share / $followerCentMult;
$masterAmountMT5 = $master_share / $masterCentMult;

// Credit MT5 accounts
// $ticketF = 0;
// $retTF = $api->TradeBalance($followerMT5->Login, MTEnDealAction::DEAL_BALANCE, $followerAmountMT5, "PAMM profit", $ticketF);
$ticketM = 0;
$retTM = $api->TradeBalance($masterMT5->Login, MTEnDealAction::DEAL_BALANCE, $masterAmountMT5, "PAMM master profit", $ticketM);

if ($retTM != MTRetCode::MT_RET_OK) {
    $api->Disconnect();
    echo json_encode(["success" => false, "message" => "MT5 credit failed"]);
    exit;
}

$api->Disconnect();

// 9️⃣ Log to database
$conn->begin_transaction();

$stmt = $conn->prepare("INSERT INTO pamm_profit_logs 
(event_uid, follower_trade_id, follower_email, master_trade_id, master_email, profit_amount, user_share, master_share, ib_total_share, status) 
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'credited')");
$stmt->bind_param("sssssdddd", $event_uid, $follower_trade_id, $follower_email, $master_trade_id, $master_email, $profit_amount, $user_share, $master_share, $ib_total_share);
$stmt->execute();
$stmt->close();

// User distribution
$stmtDist = $conn->prepare("INSERT INTO pamm_profit_distribution (event_uid, entity_type, level, email, trade_id, amount) VALUES (?, ?, ?, ?, ?, ?)");
$etype = 'user';
$nullLevel = null;
$stmtDist->bind_param("ssissd", $event_uid, $etype, $nullLevel, $follower_email, $follower_trade_id, $user_share);
$stmtDist->execute();

// User wallet log
$stmtWallet = $conn->prepare("INSERT INTO pamm_wallet_logs (email, trade_id, source, amount) VALUES (?, ?, 'pamm_profit', ?)");
$stmtWallet->bind_param("ssd", $follower_email, $follower_trade_id, $user_share);
$stmtWallet->execute();

// Master distribution
$etype = 'master';
$stmtDist->bind_param("ssissd", $event_uid, $etype, $nullLevel, $master_email, $master_trade_id, $master_share);
$stmtDist->execute();

// Master wallet log
$stmtWallet->bind_param("ssd", $master_email, $master_trade_id, $master_share);
$stmtWallet->execute();

// IB distributions
$etype = 'ib';
$stmtIbAgg = $conn->prepare("INSERT INTO ib_total_profit_commission (ib_email, total_profit_commission, available_profit_commission) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE total_profit_commission = total_profit_commission + VALUES(total_profit_commission), available_profit_commission = available_profit_commission + VALUES(available_profit_commission)");
foreach ($ib_distributions as $d) {
    $lvl = intval($d['level']);
    $email = $d['email'];
    $amt = floatval($d['amount']);
    $stmtDist->bind_param("ssissd", $event_uid, $etype, $lvl, $email, $follower_trade_id, $amt);
    $stmtDist->execute();
    $stmtWallet->bind_param("ssd", $email, $follower_trade_id, $amt);
    $stmtWallet->execute();
    $stmtIbAgg->bind_param("sdd", $email, $amt, $amt);
    $stmtIbAgg->execute();
}

$stmtDist->close();
$stmtWallet->close();
$stmtIbAgg->close();
$conn->commit();

// 10️⃣ Response
echo json_encode([
    "success" => true,
    "event_uid" => $event_uid,
    "profit_amount" => round($profit_amount, 8),
    "user_share" => $user_share,
    "master_share" => $master_share,
    "ib_total_share" => $ib_total_share,
    "ib_breakdown" => $ib_distributions
]);
?>
