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

// ----------- READ JSON BODY -----------
$input = json_decode(file_get_contents("php://input"), true);

if (!$input) {
    echo json_encode(["success" => false, "error" => "Invalid JSON body"]);
    exit;
}

$trade_id = trim($input['trade_id'] ?? '');
$email    = trim($input['email'] ?? '');

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

// ----------- FETCH ACCOUNT (no masteracc restriction) -----------
$stmt = $conn->prepare("SELECT id, strategyimage FROM liveaccounts WHERE trade_id=? AND email=?");
$stmt->bind_param("ss", $trade_id, $email);
$stmt->execute();
$res = $stmt->get_result();

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

$row = $res->fetch_assoc();
$imagePath = $row['strategyimage'];

// ----------- DELETE IMAGE IF EXISTS -----------
if (!empty($imagePath)) {
    $fullPath = __DIR__ . '/' . $imagePath;
    if (file_exists($fullPath)) {
        unlink($fullPath);
    }
}

// ----------- CLEAR MASTER STRATEGY DATA -----------
$sql = "UPDATE liveaccounts SET 
            masteracc = 0,
            strategyname = NULL,
            strategyabout = NULL,
            strategyimage = NULL,
            commission = NULL,
            strategycountry = NULL,
            mindeposit = NULL,
            max_drawdown = NULL,
            updated_by = NULL
        WHERE trade_id = ? AND email = ?";

$stmt2 = $conn->prepare($sql);
$stmt2->bind_param("ss", $trade_id, $email);

// ----------- RESPONSE -----------
if ($stmt2->execute()) {
    echo json_encode(["success" => true, "message" => "Master strategy removed completely"]);
} else {
    echo json_encode(["success" => false, "error" => $stmt2->error]);
}

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