<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

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

require_once "config.php";

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$data = json_decode(file_get_contents("php://input"), true);
$email = $data['email'] ?? null;

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

// ===== Collation-safe SQL =====
$sql = "
SELECT 
    c.id AS follow_id,
    c.mastertrade,
    c.slavetrade,
    c.mastername,
    c.slavename,
    c.volumeselect,
    c.volume,
    c.copyid,
    c.followdate,

    la.trade_id AS slave_trade_id,
    la.account_type AS slave_account_type,
    la.server AS slave_server,
    la.Balance AS slave_balance,
    la.equity AS slave_equity,

    tm.tradeid AS master_tradeid,
    tm.name AS master_name,
    c.email AS master_email,
    tm.account AS master_account,
    tm.balance AS master_balance,
    tm.leverage AS master_leverage,

    ts.balance AS tblslave_balance,
    ts.account AS tblslave_account,
    ts.leverage AS tblslave_leverage

FROM copyaccounts c
INNER JOIN liveaccounts la 
    ON c.slavetrade COLLATE utf8mb4_general_ci = la.trade_id COLLATE utf8mb4_general_ci
LEFT JOIN (
    SELECT slavetrade, balance, account, leverage
    FROM tbl_slave
    GROUP BY slavetrade
) ts
    ON ts.slavetrade COLLATE utf8mb4_general_ci = c.slavetrade COLLATE utf8mb4_general_ci
LEFT JOIN (
    SELECT tradeid, name, account, balance, leverage
    FROM tbl_master
    GROUP BY tradeid
) tm
    ON tm.tradeid COLLATE utf8mb4_general_ci = c.mastertrade COLLATE utf8mb4_general_ci
WHERE la.email COLLATE utf8mb4_general_ci = ? COLLATE utf8mb4_general_ci
  AND c.status = 1
ORDER BY c.id DESC
";

// ===== Prepare & Execute =====
$stmt = $conn->prepare($sql);

if (!$stmt) {
    echo json_encode([
        "status" => "error",
        "message" => "SQL Prepare Failed",
        "error" => $conn->error
    ]);
    exit;
}

$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();

// ===== Fetch Rows =====
$rows = [];
while ($row = $result->fetch_assoc()) {
    $rows[] = $row;
}

// ===== Return Response =====
echo json_encode([
    "status" => "success",
    "total" => count($rows),
    "data" => $rows
]);
?>
