<?php
header("Access-Control-Allow-Origin: *"); 
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
header("Access-Control-Max-Age: 86400"); 

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

require_once 'config.php';        // $conn (mysqli)
require_once 'connection.php';    // keep as-is

// ===== Parse JSON =====
$data = json_decode(file_get_contents("php://input"), true);
$mastertrade = $data['mastertrade'] ?? null;
$slavetrade  = $data['slavetrade'] ?? null;
$mastername  = $data['mastername'] ?? null;
$slavename   = $data['slavename'] ?? null;
$email       = $data['email'] ?? null;
$volumeselect = $data['volumeselect'] ?? 'fixed';
$volume = isset($data['volume']) ? floatval($data['volume']) : 1.0;
$copyid = $data['copyid'] ?? uniqid("copy_");

// ===== Validate required fields =====
if (!$mastertrade || !$slavetrade || !$mastername || !$slavename) {
    echo json_encode(["status"=>"error","message"=>"Missing required fields"]);
    exit;
}

// ===== Fetch account types from liveaccounts =====
$masterAccTypeResult = $conn->query("SELECT account_type FROM liveaccounts WHERE trade_id = '$mastertrade' LIMIT 1");
$slaveAccTypeResult  = $conn->query("SELECT account_type FROM liveaccounts WHERE trade_id = '$slavetrade' LIMIT 1");

$masterAccType = $masterAccTypeResult->fetch_assoc()['account_type'] ?? null;
$slaveAccType  = $slaveAccTypeResult->fetch_assoc()['account_type'] ?? null;

// ===== Cent-to-Cent restriction =====
if ($masterAccType === 'Cent' && $slaveAccType !== 'Cent') {
    echo json_encode([
        "status" => "error",
        "message" => "Cent slaves can only follow Cent master accounts."
    ]);
    exit;
}

if ($masterAccType !== 'Cent' && $slaveAccType === 'Cent') {
    echo json_encode([
        "status" => "error",
        "message" => "Cent accounts cannot follow non-Cent master accounts."
    ]);
    exit;
}

// ===== Insert pending request into main DB (status = 0 pending) =====
$stmt = $conn->prepare("INSERT INTO copyaccounts 
    (email, mastername, mastertrade, slavename, slavetrade, copyid, volumeselect, volume, status) 
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0)");

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

$stmt->bind_param("sssssssd",
    $email, $mastername, $mastertrade, $slavename, $slavetrade, $copyid, $volumeselect, $volume
);

if (!$stmt->execute()) {
    echo json_encode(["status"=>"error","message"=>"Execute failed: ".$stmt->error]);
    exit;
}

$request_id = $stmt->insert_id;
$stmt->close();

// ===== Response =====
echo json_encode([
    "status" => "pending",
    "message" => "Investment request created. Awaiting admin approval.",
    "request_id" => $request_id,
    "master" => $mastertrade,
    "slave" => $slavetrade
]);
?>
