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

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

include_once __DIR__ . "/config.php";
include_once __DIR__ . "/connection.php";

// ---------------- Fetch All Strategies ----------------
$input = file_get_contents("php://input");
$data  = json_decode($input, true);

if (isset($data['action']) && $data['action'] === 'fetch_strategies') {
    $sql = "SELECT trade_id, strategyname, strategyabout, strategyimage, 
                   strategycountry, commission, mindeposit, Balance, equity, totalprofit, profitvalue
            FROM liveaccounts
            WHERE masteracc = 2";

    $result = $conn->query($sql);
    $strategies = [];

    // Initialize MT5 connection
    $mt5 = new MT5Connection();
    $mt_connected = $mt5->connect();

    if ($result && $result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {

            // ---------------- Calculate Maximum Drawdown ----------------
            $profit_values = $row['profitvalue'] ? explode(",", $row['profitvalue']) : [];
            $max_equity = 0;
            $max_drawdown = 0;
            foreach ($profit_values as $p) {
                $p = floatval($p);
                if ($p > $max_equity) $max_equity = $p;
                $dd = $max_equity - $p;
                if ($dd > $max_drawdown) $max_drawdown = $dd;
            }
            $row['max_drawdown'] = $max_drawdown;

            // ---------------- Count Followers & Calculate Strategy Equity (followers only) ----------------
            $stmt = $conn->prepare("SELECT slavetrade FROM copyaccounts WHERE mastertrade=? AND status=1");
            $stmt->bind_param("s", $row['trade_id']);
            $stmt->execute();
            $followers_res = $stmt->get_result();

            $followers_count = 0;
            $strategyEquity = 0; // followers only
            while ($f = $followers_res->fetch_assoc()) {
                $followers_count++;

                // Fetch MT5 balance of follower account
                if ($mt_connected) {
                    $f_account = [];
                    if ($mt5->api->UserAccountGet(intval($f['slavetrade']), $f_account) === MTRetCode::MT_RET_OK) {
                        $strategyEquity += $f_account->Balance; // only followers
                    }
                }
            }
            $stmt->close();

            $row['followers'] = $followers_count;

            // Fetch live Balance, Equity, TotalProfit from MT5 for master account (for display only, do NOT add to strategyEquity)
            if ($mt_connected) {
                $account = null;
                if ($mt5->api->UserAccountGet($row['trade_id'], $account) === MTRetCode::MT_RET_OK) {
                    $row['Balance'] = $account->Balance;
                    $row['equity'] = $account->Equity;
                    $row['totalprofit'] = $account->Profit;
                }
            }

            $row['strategyEquity'] = $strategyEquity; // followers only

            $strategies[] = $row;
        }

        echo json_encode(["status" => "success", "data" => $strategies]);
    } else {
        echo json_encode(["status" => "error", "message" => "No strategies found"]);
    }

    $conn->close();
    exit;
}

// ---------------- Add to Watchlist ----------------
if (isset($data['action']) && $data['action'] === 'add_watchlist') {
    $email    = $data['email'] ?? null;
    $trade_id = $data['trade_id'] ?? null;

    if (!$email || !$trade_id) {
        echo json_encode(["status" => "error", "message" => "Missing parameters"]);
        exit;
    }

    $stmt = $conn->prepare("SELECT strategyname, strategyabout, strategyimage, strategycountry, commission, totalprofit, profitvalue, Balance, equity 
                            FROM liveaccounts WHERE trade_id=? LIMIT 1");
    $stmt->bind_param("s", $trade_id);
    $stmt->execute();
    $strategy = $stmt->get_result()->fetch_assoc();
    $stmt->close();

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

    $stmt = $conn->prepare("INSERT INTO tbl_favourite 
                            (email, tradeid, strategyname, strategyabout, strategyimage, strategycountry, commission, totalprofit, profitvalue, Balance, equity)
                            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("sssssssssss",
                      $email, $trade_id, $strategy['strategyname'], $strategy['strategyabout'], 
                      $strategy['strategyimage'], $strategy['strategycountry'], $strategy['commission'], 
                      $strategy['totalprofit'], $strategy['profitvalue'], $strategy['Balance'], $strategy['equity']);

    if ($stmt->execute()) {
        echo json_encode(["status" => "success", "message" => "Added to watchlist"]);
    } else {
        echo json_encode(["status" => "error", "message" => "Failed to add to watchlist"]);
    }

    $stmt->close();
    $conn->close();
    exit;
}

// ---------------- Remove from Watchlist ----------------
if (isset($data['action']) && $data['action'] === 'remove_watchlist') {
    $email    = $data['email'] ?? null;
    $trade_id = $data['trade_id'] ?? null;

    if (!$email || !$trade_id) {
        echo json_encode(["status" => "error", "message" => "Missing parameters"]);
        exit;
    }

    $stmt = $conn->prepare("DELETE FROM tbl_favourite WHERE email=? AND tradeid=?");
    $stmt->bind_param("ss", $email, $trade_id);

    if ($stmt->execute()) {
        echo json_encode(["status" => "success", "message" => "Removed from watchlist"]);
    } else {
        echo json_encode(["status" => "error", "message" => "Failed to remove from watchlist"]);
    }

    $stmt->close();
    $conn->close();
    exit;
}

// ---------------- Invalid Action ----------------
echo json_encode(["status" => "error", "message" => "Invalid action"]);
exit;
?>
