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

// For JSON requests (not used for form-data)
$input = json_decode(file_get_contents("php://input"), true);
if ($input) $_POST = array_merge($_POST, $input);

// ----------- REQUIRED FIELDS -----------
$trade_id        = trim($_POST['trade_id'] ?? '');
$email           = trim($_POST['email'] ?? '');
$strategyname    = trim($_POST['strategyname'] ?? '');
$strategyabout   = trim($_POST['strategyabout'] ?? '');
$commission      = trim($_POST['commission'] ?? '');
$strategycountry = trim($_POST['strategycountry'] ?? '');
$mindeposit      = trim($_POST['mindeposit'] ?? '');
$max_drawdown    = trim($_POST['max_drawdown'] ?? '');
$updated_by      = $email;

if (!$trade_id || !$email) {
    echo json_encode(["success" => false, "error" => "trade_id and email are required"]);
    exit;
}

// ----------- CHECK IF MASTER ACCOUNT EXISTS -----------
$stmt = $conn->prepare("SELECT id FROM liveaccounts WHERE trade_id=? AND email=? AND masteracc > 0");
$stmt->bind_param("ss", $trade_id, $email);
$stmt->execute();
$res = $stmt->get_result();

if ($res->num_rows == 0) {
    echo json_encode(["success" => false, "error" => "Master account not found"]);
    exit;
}

// ----------- IMAGE UPLOAD -----------
$strategyimage = null;
if (isset($_FILES['strategyimage']) && $_FILES['strategyimage']['error'] === UPLOAD_ERR_OK) {
    $uploadDir = __DIR__ . '/uploads/';
    if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);

    $fileName = time() . '_' . basename($_FILES['strategyimage']['name']);
    $filePath = $uploadDir . $fileName;

    if (move_uploaded_file($_FILES['strategyimage']['tmp_name'], $filePath)) {
        $strategyimage = "uploads/" . $fileName;
    }
}

// --------------------------------------
// Build dynamic SQL safely
// --------------------------------------
$fields = "strategyname=?, strategyabout=?, commission=?, strategycountry=?, mindeposit=?, max_drawdown=?, updated_by=?";
$params = [$strategyname, $strategyabout, $commission, $strategycountry, $mindeposit, $max_drawdown, $updated_by];
$types  = "sssssss";

if ($strategyimage) {
    $fields .= ", strategyimage=?";
    $params[] = $strategyimage;
    $types   .= "s";
}

$fields .= " WHERE trade_id=? AND email=?";
$params[] = $trade_id;
$params[] = $email;
$types   .= "ss";

$sql = "UPDATE liveaccounts SET $fields";
$stmt2 = $conn->prepare($sql);

// Bind params dynamically
$stmt2->bind_param($types, ...$params);

// Execute
if ($stmt2->execute()) {
    echo json_encode(["success" => true, "message" => "Master account updated successfully"]);
} else {
    echo json_encode(["success" => false, "error" => $stmt2->error]);
}

$stmt2->close();
$conn->close();
?>
