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

// Read 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 user watchlist
$stmt = $conn->prepare("SELECT id, tradeid, strategyname, strategyabout, strategyimage, 
                               strategycountry, commission, totalprofit, profitvalue, 
                               Balance, equity, Date 
                        FROM tbl_favourite 
                        WHERE email=? 
                        ORDER BY Date DESC");
$stmt->bind_param("s", $email);
$stmt->execute();

$result = $stmt->get_result();
$watchlist = [];

if ($result && $result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        // Convert profitvalue to array if comma-separated
        $row['profitvalue'] = $row['profitvalue'] ? explode(",", $row['profitvalue']) : [];
        $watchlist[] = $row;
    }
    echo json_encode(["status" => "success", "data" => $watchlist]);
} else {
    echo json_encode(["status" => "error", "message" => "No watchlist found"]);
}

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