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

$input = file_get_contents("php://input");
$data  = json_decode($input, true);

$mastertrade = isset($data['mastertrade']) ? trim($data['mastertrade']) : null;
$slavetrade  = isset($data['slavetrade']) ? trim($data['slavetrade']) : null;

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

// Check if follower exists
// $stmt = $conn->prepare("
//     SELECT id, executed, status 
//     FROM copyaccounts 
//     WHERE TRIM(mastertrade) = ? 
//       AND TRIM(slavetrade) = ? 
//       AND status IN (0,1)
// ");
// $stmt->bind_param("ss", $mastertrade, $slavetrade);

$email = isset($data['email']) ? trim($data['email']) : null;

if (!$email) {
    echo json_encode([
        "status" => "error",
        "message" => "Missing email address"
    ]);
    exit;
}

$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_rows = $result->fetch_all(MYSQLI_ASSOC);
$stmt->close();

if (empty($follower_rows)) {
    echo json_encode([
        "status" => "error",
        "message" => "Follower relationship not found or already inactive/rejected"
    ]);
    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 (count($parts) >= 2) {
            if (!(trim($parts[0]) === $mastertrade && trim($parts[1]) === $slavetrade)) {
                $newLines[] = $line;
            }
        }
    }
    file_put_contents($posFile, implode(PHP_EOL, $newLines) . PHP_EOL);
}

// **New minimal change: notify remote server to remove pair**
try {
    $remote_url = "https://server.qfx-markets.com/trade_copier_qfx/update_user_txt.php"; // change to your remote URL
    $postData = [
        'mastertradeid' => $mastertrade,
        'slavetradeid' => $slavetrade,
        'action' => 'remove'
    ];

    $ch = curl_init($remote_url);
    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("user_txt_error.log", $e->getMessage() . "\n", FILE_APPEND);
}

// Update status to unfollowed
$update = $conn->prepare("
    UPDATE copyaccounts 
    SET status = 2, executed = 0 
    WHERE TRIM(mastertrade) = ? 
      AND TRIM(slavetrade) = ? 
      AND status IN (0,1)
");
$update->bind_param("ss", $mastertrade, $slavetrade);

if ($update->execute()) {
    echo json_encode([
        "status" => "success",
        "message" => "Successfully unfollowed the account. Copy stopped.",
        "mastertrade" => $mastertrade,
        "slavetrade" => $slavetrade,
        "rows_affected" => $update->affected_rows
    ]);
} else {
    echo json_encode([
        "status" => "error",
        "message" => "Failed to update follower status",
        "error" => $conn->error
    ]);
}
?>
