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

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");

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

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

if (!$conn) {
    echo json_encode(["status" => false, "message" => "Database connection failed"]);
    exit;
}

// Input
$input = json_decode(file_get_contents("php://input"), true);
if (!isset($input['email']) || empty($input['email'])) {
    echo json_encode(["status" => false, "message" => "Email required"]);
    exit;
}

$slaveEmail = $conn->real_escape_string($input['email']);
define('DEAL_ENTRY_OUT', 1);

// Helper function for volume conversion
function lot($raw) { return round(((float)$raw) * 0.0001, 2); }

try {
    // 1️⃣ Get slave PAMM account info
    $stmt = $conn->prepare("SELECT account_name, trade_id FROM liveaccounts WHERE email = ? AND account_type = 'PAMM' ORDER BY id DESC LIMIT 1");
    $stmt->bind_param("s", $slaveEmail);
    $stmt->execute();
    $res = $stmt->get_result();

    if ($res->num_rows === 0) {
        echo json_encode(["status" => false, "message" => "No PAMM slave account found"]);
        exit;
    }

    $slaveRow = $res->fetch_assoc();
    $slaveAccount = $slaveRow['account_name'];
    $slaveTradeId = (int)$slaveRow['trade_id'];
    $stmt->close();

    // 2️⃣ Get master trade from copyaccounts
    $stmt2 = $conn->prepare("SELECT mastertrade FROM copyaccounts WHERE slavename = ? ORDER BY id DESC LIMIT 1");
    $stmt2->bind_param("s", $slaveAccount);
    $stmt2->execute();
    $res2 = $stmt2->get_result();

    if ($res2->num_rows === 0) {
        echo json_encode(["status" => false, "message" => "No master found for this slave"]);
        exit;
    }

    $copyRow = $res2->fetch_assoc();
    $masterTradeId = (int)$copyRow['mastertrade'];
    $stmt2->close();

    // 3️⃣ Get master email from liveaccounts
    $stmt3 = $conn->prepare("SELECT email, account_name FROM liveaccounts WHERE trade_id = ? LIMIT 1");
    $stmt3->bind_param("i", $masterTradeId);
    $stmt3->execute();
    $res3 = $stmt3->get_result();

    if ($res3->num_rows === 0) {
        echo json_encode(["status" => false, "message" => "Master account not found in liveaccounts"]);
        exit;
    }

    $masterRow = $res3->fetch_assoc();
    $masterEmail = $masterRow['email'];
    $masterAccount = $masterRow['account_name'];
    $stmt3->close();

    // 4️⃣ Connect to MT5
    $api = new MTWebAPI("WebAPITesterLocal", "./logs", false);
    $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(["status" => false, "message" => "MT5 connection failed", "error_code" => $ret]);
        exit;
    }

    // 5️⃣ Fetch deals and calculate profit
    $totalDeals = 0;
    $retTotal = $api->DealGetTotal($slaveTradeId, 0, 0, $totalDeals);
    $profit24 = 0;
    $profitAll = 0;
    $last24 = time() - 86400;

    if ($retTotal == MTRetCode::MT_RET_OK && $totalDeals > 0) {
        $deals = [];
        $retPage = $api->DealGetPage($slaveTradeId, 0, 0, 0, $totalDeals, $deals);
        if ($retPage == MTRetCode::MT_RET_OK) {
            foreach ($deals as $deal) {
                $vol = isset($deal->VolumeClosed) ? lot($deal->VolumeClosed) : 0;
                if ($vol <= 0) continue; // skip invalid / non-closing deals

                $profitVal = (float)($deal->Profit ?? 0);
                $timeVal = (int)($deal->Time ?? 0);

                $profitAll += $profitVal;
                if ($timeVal >= $last24) $profit24 += $profitVal;
            }
        }
    }

    $api->Disconnect();
    // Insert the fetched profit into pamm_profits table
$insertStmt = $conn->prepare("
    INSERT INTO pamm_profits 
    (slave_email, slave_account, slave_trade_id, master_email, master_account, master_trade, profit_24h, profit_all)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    ON DUPLICATE KEY UPDATE
        profit_24h = VALUES(profit_24h),
        profit_all = VALUES(profit_all),
        created_at = CURRENT_TIMESTAMP
");


$profit24Rounded = round($profit24, 2);
$profitAllRounded = round($profitAll, 2);

$insertStmt->bind_param(
    "ssisssdd",
    $slaveEmail,
    $slaveAccount,
    $slaveTradeId,
    $masterEmail,
    $masterAccount,
    $masterTradeId,
    $profit24Rounded,
    $profitAllRounded
);

$insertStmt->execute();
$insertStmt->close();


    // 6️⃣ Return response
    echo json_encode([
        "status" => true,
        "message" => "PAMM profit fetched",
        "slave_email" => $slaveEmail,
        "slave_account" => $slaveAccount,
        "slave_trade_id" => $slaveTradeId,
        "master_email" => $masterEmail,
        "master_account" => $masterAccount,
        "master_trade" => $masterTradeId,
        "profit_24h" => round($profit24, 2),
        "profit_all" => round($profitAll, 2)
    ]);

} catch (Throwable $e) {
    echo json_encode(["status" => false, "message" => "Exception: " . $e->getMessage()]);
}
?>
