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

// Get JSON input
$input = file_get_contents("php://input");
$data  = json_decode($input, true);

$email = $data['email'] ?? null;

if (!$email) {
    echo json_encode(["status" => "error", "message" => "Email is required"]);
    exit;
}

// Fetch live accounts for this email
$stmt = $conn->prepare("SELECT trade_id, strategyname, strategyabout, strategyimage, strategycountry, commission, mindeposit, Balance, equity, totalprofit, profitvalue 
                        FROM liveaccounts 
                        WHERE email = ? AND masteracc = 2");
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();

$accounts = [];

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
        $stmt2 = $conn->prepare("SELECT COUNT(*) as followers_count FROM copyaccounts WHERE mastertrade=? AND status=1");
        $stmt2->bind_param("s", $row['trade_id']);
        $stmt2->execute();
        $followers_res = $stmt2->get_result()->fetch_assoc();
        $row['followers'] = $followers_res['followers_count'] ?? 0;
        $stmt2->close();

        $accounts[] = $row;
    }

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

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