<?php

$filePath = __DIR__ . DIRECTORY_SEPARATOR . 'ips.txt';

if (isset($_GET['check'])) {
    header('Content-Type: text/plain');

    if (file_exists($filePath)) {
        readfile($filePath);
    } else {
        echo "";
    }
    exit;
}

if (isset($_GET['delete'])) {
    if (!isset($_POST['ip'])) {
        echo "Aucune IP à supprimer.";
        exit;
    }

    $ipToDelete = trim($_POST['ip']);

    if (!file_exists($filePath)) {
        echo "Fichier introuvable.";
        exit;
    }

    $fileContent = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

    $file = fopen($filePath, 'w');
    if (!$file) {
        echo "Erreur lors de l'ouverture du fichier pour modification.";
        exit;
    }

    $prefixPipe = $ipToDelete . '|';
    $prefixLegacy = $ipToDelete . ':';
    foreach ($fileContent as $line) {
        $line = rtrim($line, "\r\n");
        if ($line === '' || (strncmp($line, $prefixPipe, strlen($prefixPipe)) !== 0 && strncmp($line, $prefixLegacy, strlen($prefixLegacy)) !== 0)) {
            fwrite($file, $line . PHP_EOL);
        }
    }

    fclose($file);
    echo "IP supprimée.";
}
