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

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

// ---------------- Fetch All Strategies ----------------
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 = [];

    if ($result && $result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $row['profitvalue'] = $row['profitvalue'] ? explode(",", $row['profitvalue']) : [];
            // Count followers
            $stmt = $conn->prepare("SELECT COUNT(*) as followers FROM copyaccounts WHERE mastertrade=? AND status=2");
            $stmt->bind_param("s", $row['trade_id']);
            $stmt->execute();
            $followerRes = $stmt->get_result()->fetch_assoc();
            $row['followers'] = $followerRes['followers'] ?? 0;
            $stmt->close();

            $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;
    }

    // Fetch strategy details
    $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;
    }

    // Insert into watchlist
    $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;
?>
