<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

header("Access-Control-Allow-Origin: *"); 
header("Content-Type: application/json; charset=UTF-8"); 
header("Access-Control-Allow-Methods: POST, OPTIONS"); 
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");

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

require_once 'config.php';
require_once 'connection.php';

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

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

// Step 1: Get master details
$sqlMaster = "SELECT tradeid, name, email, balance, account, leverage FROM tbl_master WHERE tradeid = ?";
$stmtMaster = $conn->prepare($sqlMaster);
$stmtMaster->bind_param("i", $masterTradeId);
$stmtMaster->execute();
$resultMaster = $stmtMaster->get_result();
$master = $resultMaster->fetch_assoc();

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

// Step 2: Get all followers from tbl_slave
$sqlSlave = "SELECT id, name, email, slavetrade, balance, account, leverage, Date 
             FROM tbl_slave 
             WHERE mastertrade = ?";
$stmtSlave = $conn->prepare($sqlSlave);
$stmtSlave->bind_param("i", $master['tradeid']);
$stmtSlave->execute();
$resultSlave = $stmtSlave->get_result();

$followers = [];
while ($row = $resultSlave->fetch_assoc()) {
    $followers[] = [
        "id" => $row['id'],
        "slave_name" => $row['name'],
        "slave_email" => $row['email'],
        "slave_trade" => $row['slavetrade'],
        "balance" => $row['balance'],
        "account" => $row['account'],
        "leverage" => $row['leverage'],
        "joined_date" => $row['Date']
    ];
}

$stmtMaster->close();
$stmtSlave->close();

echo json_encode([
    "status" => "success",
    "master_tradeid" => $master['tradeid'],
    "master_name" => $master['name'],
    "followers_count" => count($followers),
    "followers" => $followers
]);
?>
