<?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 "config.php";

// ---------- Read JSON if sent ----------
$input = json_decode(file_get_contents("php://input"), true);
if ($input && is_array($input)) {
    $_POST = array_merge($_POST, $input);
}

// ---------- Required fields ----------
$trade_id        = trim($_POST['trade_id'] ?? '');
$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'] ?? '');
$email           = trim($_POST['email'] ?? '');
$updated_by      = "admin";
$strategyimage   = null;

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

// ---------- Check if account exists ----------
$stmtCheck = $conn->prepare("SELECT id FROM liveaccounts WHERE trade_id=? AND email=?");
$stmtCheck->bind_param("ss", $trade_id, $email);
$stmtCheck->execute();
$resCheck = $stmtCheck->get_result();

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

// ---------- Upload Image ----------
if (isset($_FILES['strategyimage']) && $_FILES['strategyimage']['error'] === UPLOAD_ERR_OK) {

    $uploadDir = __DIR__ . '/uploads/';
    if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);

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

    if (move_uploaded_file($fileTmpPath, $targetFile)) {
        $strategyimage = 'uploads/' . $fileName;
    } else {
        echo json_encode(["success" => false, "error" => "Failed to upload image"]);
        exit;
    }
}

// ---------- Update as Approved Master ----------
$stmt = $conn->prepare("
    UPDATE liveaccounts 
    SET strategyname=?, strategyabout=?, strategyimage=?, 
        commission=?, strategycountry=?, mindeposit=?, 
        max_drawdown=?, masteracc=2, updated_by=? 
    WHERE trade_id=? AND email=?
");

$stmt->bind_param(
    "ssssssssss",
    $strategyname,
    $strategyabout,
    $strategyimage,
    $commission,
    $strategycountry,
    $mindeposit,
    $max_drawdown,
    $updated_by,
    $trade_id,
    $email
);

if ($stmt->execute() && $stmt->affected_rows > 0) {
    echo json_encode(["success" => true, "message" => "Master created successfully"]);
} else {
    echo json_encode(["success" => false, "error" => "Failed to update account"]);
}

$stmt->close();
$conn->close();
exit;
?>
