<?php
require_once __DIR__ . '/includes/Database.php';

$pdo = Database::getInstance();

function getSetting($pdo, $name, $default = '') {
    $stmt = $pdo->prepare("SELECT value FROM settings WHERE name = ?");
    $stmt->execute([$name]);
    return $stmt->fetchColumn() ?: $default;
}

// ... (bdecode функцията може да я махнеш, ако не се използва)

if (!isset($_GET['info_hash'])) {
    die('d14:failure reason20:Missing info_hashe');
}

$infoHash = $_GET['info_hash'];
$peerId = $_GET['peer_id'] ?? '';
$port = (int)($_GET['port'] ?? 6881);
$uploaded = (int)($_GET['uploaded'] ?? 0);
$downloaded = (int)($_GET['downloaded'] ?? 0);
$left = (int)($_GET['left'] ?? 1);
$ip = $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1';
$seeder = ($left == 0) ? 1 : 0;

// Валидации
if (strlen($infoHash) !== 20 || strlen($peerId) < 10 || $port < 1 || $port > 65535 || !filter_var($ip, FILTER_VALIDATE_IP)) {
    die('d14:failure reason18:Invalid request datae');
}

$infoHashHex = bin2hex($infoHash);

// Винаги записваме в peers; torrent_id се попълва само ако съществува
$stmt = $pdo->prepare("
    INSERT INTO peers (torrent_id, info_hash, peer_id, ip, port, seeder, uploaded, downloaded, `left`, last_announce)
    VALUES (
        (SELECT id FROM torrents WHERE info_hash = ? LIMIT 1),
        ?, ?, ?, ?, ?, ?, ?, ?, NOW()
    )
    ON DUPLICATE KEY UPDATE
        seeder = VALUES(seeder),
        uploaded = VALUES(uploaded),
        downloaded = VALUES(downloaded),
        `left` = VALUES(`left`),
        last_announce = NOW()
");
$stmt->execute([$infoHashHex, $infoHashHex, $peerId, $ip, $port, $seeder, $uploaded, $downloaded, $left]);

// Почистване
$pdo->exec("DELETE FROM peers WHERE last_announce < NOW() - INTERVAL 30 MINUTE");

// Вземи peers по info_hash (работи и за вътрешни, и за външни)
$stmt = $pdo->prepare("
    SELECT ip, port FROM peers 
    WHERE info_hash = ? AND peer_id != ? 
    ORDER BY RAND() LIMIT 50
");
$stmt->execute([$infoHashHex, $peerId]);
$peers = $stmt->fetchAll();

// ... (останалата част за формиране на отговора — същата)

$ipv4List = '';
$ipv6List = [];
foreach ($peers as $p) {
    $ipAddr = $p['ip'];
    $portNum = (int)$p['port'];
    if (filter_var($ipAddr, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
        $ipv4List .= inet_pton($ipAddr) . pack('n', $portNum);
    } elseif (filter_var($ipAddr, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
        $ipv6List[] = ['ip' => $ipAddr, 'port' => $portNum];
    }
}

$peersPart = strlen($ipv4List) . ':' . $ipv4List;
$peers6Part = '';
if (!empty($ipv6List)) {
    $peers6Encoded = 'l';
    foreach ($ipv6List as $peer) {
        $peers6Encoded .= 'd2:ip' . strlen($peer['ip']) . ':' . $peer['ip'] . '4:porti' . $peer['port'] . 'ee';
    }
    $peers6Encoded .= 'e';
    $peers6Part = '6:peers6' . strlen($peers6Encoded) . ':' . $peers6Encoded;
}

$interval = 1800;
$minInterval = 900;
$response = "d8:intervali{$interval}e12:min intervali{$minInterval}e5:peers{$peersPart}{$peers6Part}e";
echo $response;
exit;