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

if (!$mastertrade || !$slavetrade || !$mastername || !$slavename) {
    echo json_encode(["status"=>"error","message"=>"Missing required fields"]);
    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();

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