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

// ---------------- Handle JSON + Form-Data ----------------
$input = json_decode(file_get_contents("php://input"), true);
if ($input && is_array($input)) {
    $_POST = array_merge($_POST, $input);
}

// ---------------- Fetch Accounts for Dropdown ----------------
if (isset($_POST['action']) && $_POST['action'] === 'fetch_accounts') {
    $accounts = [];
    $user_id  = $_POST['user_id'] ?? 0;

    if (!$user_id) {
        echo json_encode(["success" => false, "error" => "Missing user_id"]);
        exit;
    }

    $stmt = $conn->prepare("SELECT trade_id, email, account_name, account_type 
                            FROM liveaccounts 
                            WHERE user_id=?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();

    while ($row = $result->fetch_assoc()) {
        $accounts[] = $row;
    }

    echo json_encode(["success" => true, "accounts" => $accounts]);
    exit;
}

// ---------------- Register as Strategy Provider ----------------
if (isset($_POST['action']) && $_POST['action'] === 'register_strategy') {
    $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'] ?? ''); // <--- Added
    $email           = trim($_POST['email'] ?? '');
    $strategyimage   = null;
    $updated_by      = $email;

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

    // ---------------- Handle Image Upload ----------------
    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;
        }
    }

    // ---------------- 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" => "No matching account found for this trade_id and email"]);
        exit;
    }

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

    // Bind parameters correctly (added max_drawdown)
    $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" => "Strategy registered successfully"]);
    } else {
        echo json_encode([
            "success" => false,
            "error" => "No rows updated. Check trade_id and email.",
            "trade_id" => $trade_id,
            "email" => $email
        ]);
    }

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

// ---------------- If no valid action ----------------
echo json_encode(["success" => false, "error" => "Invalid action"]);
exit;
?>
