<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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;

require_once 'config.php';
require_once 'connection.php';

// ===== Parse input =====
$data = json_decode(file_get_contents("php://input"), true);
$masterTrade = isset($data['mastertrade']) ? trim($data['mastertrade']) : null;
$slaveTrade  = isset($data['slavetrade']) ? trim($data['slavetrade']) : null;
$email       = isset($data['email']) ? trim($data['email']) : null;

if (!$masterTrade || !$slaveTrade || !$email) {
    echo json_encode([
        "status" => "error",
        "message" => "Missing mastertrade, slavetrade or email"
    ]);
    exit;
}

// ===== Check if follower exists =====
$stmt = $conn->prepare("
    SELECT id, executed, status 
    FROM copyaccounts 
    WHERE TRIM(mastertrade) = ? 
      AND TRIM(slavetrade) = ? 
      AND TRIM(email) = ? 
      AND status IN (0,1)
");
$stmt->bind_param("sss", $masterTrade, $slaveTrade, $email);
$stmt->execute();
$result = $stmt->get_result();
$follower = $result->fetch_assoc();
$stmt->close();

if (!$follower) {
    echo json_encode([
        "status" => "error",
        "message" => "Follower relationship not found or already inactive"
    ]);
    exit;
}

// ===== Remove from PositionPairs.txt =====
$posFile = __DIR__ . "/PositionPairs.txt";
if (file_exists($posFile)) {
    $lines = file($posFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    $newLines = [];
    foreach ($lines as $line) {
        $parts = explode(",", $line);
        if (!(trim($parts[0]) === $masterTrade && trim($parts[1]) === $slaveTrade)) {
            $newLines[] = $line;
        }
    }
    file_put_contents($posFile, implode(PHP_EOL, $newLines) . PHP_EOL);
}

// ===== Notify remote server =====
try {
    $remoteUrl = "https://server.vistafxsolutions.com/trade_copier_vistafx/update_user_txt.php"; 
    $postData = [
        'mastertradeid' => $masterTrade,
        'slavetradeid'  => $slaveTrade,
        'action'        => 'remove'
    ];

    $ch = curl_init($remoteUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
    curl_exec($ch);
    curl_close($ch);
} catch (Exception $e) {
    file_put_contents("admin_remove_follower_error.log", $e->getMessage() . "\n", FILE_APPEND);
}

// ===== Update follower status =====
$update = $conn->prepare("
    UPDATE copyaccounts 
    SET status = 2, executed = 0 
    WHERE TRIM(mastertrade) = ? 
      AND TRIM(slavetrade) = ? 
      AND TRIM(email) = ? 
      AND status IN (0,1)
");
$update->bind_param("sss", $masterTrade, $slaveTrade, $email);

if ($update->execute()) {
    echo json_encode([
        "status" => "success",
        "message" => "Follower successfully removed. Copy stopped.",
        "mastertrade" => $masterTrade,
        "slavetrade"  => $slaveTrade,
        "rows_affected" => $update->affected_rows
    ]);
} else {
    echo json_encode([
        "status" => "error",
        "message" => "Failed to remove follower",
        "error" => $conn->error
    ]);
}
?>
