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

$pdo = Database::getInstance();
$auth = new Auth($pdo);
$lang = new Language($_SESSION['lang'] ?? 'en');

// ✅ Функция за форматиране на размер
function formatBytes($bytes, $precision = 2) {
    if ($bytes === 0) return '0 Б';
    $units = ['Б', 'КБ', 'МБ', 'ГБ', 'ТБ'];
    $step = 1024;
    $i = 0;
    while ($bytes >= $step && $i < count($units) - 1) {
        $bytes /= $step;
        $i++;
    }
    return round($bytes, $precision) . ' ' . $units[$i];
}

// ✅ Вземи заявката за търсене
$searchQuery = trim($_GET['q'] ?? '');
$categoryIds = $_GET['categories'] ?? [];
$filterTitle = isset($_GET['filter_title']) ? 1 : 0;
$filterSubs = isset($_GET['filter_subs']) ? 1 : 0;
$filterAudio = isset($_GET['filter_audio']) ? 1 : 0;
$filterAuthor = isset($_GET['filter_author']) ? 1 : 0;

// ✅ Опитваме се да извлечем йерархични категории
$stmt = $pdo->query("
    SELECT c1.name as main_name, c2.id, c2.name as sub_name, c2.icon
    FROM categories c1
    JOIN categories c2 ON c1.id = c2.parent_id
    WHERE c1.parent_id IS NULL AND c2.parent_id IS NOT NULL AND c2.is_active = 1
    ORDER BY c1.id, c2.id
");
$subcategories = $stmt->fetchAll();

if (empty($subcategories)) {
    // ❌ Няма подкатегории → използваме всички категории като подкатегории
    $stmt = $pdo->query("SELECT id, name, icon FROM categories WHERE is_active = 1 ORDER BY id");
    $flatCategories = $stmt->fetchAll();
    $groups = ['Категории' => []];
    foreach ($flatCategories as $cat) {
        $groups['Категории'][] = [
            'main_name' => 'Категории',
            'id' => $cat['id'],
            'sub_name' => $cat['name'],
            'icon' => $cat['icon']
        ];
    }
} else {
    // ✅ Има подкатегории → групираме нормално
    $groups = [];
    foreach ($subcategories as $sub) {
        $groups[$sub['main_name']][] = $sub;
    }
}

// ✅ Подготви заявката за торенти
$sql = "
    SELECT 
        t.id, 
        t.name, 
        t.size, 
        t.seeders, 
        t.leechers, 
        t.uploaded_at,
        c.name as category_name,
        c.icon as category_icon,
        u.username as uploader_name,
        u.id as uploader_id
    FROM torrents t
    LEFT JOIN categories c ON t.category_id = c.id
    LEFT JOIN users u ON t.uploader_id = u.id
";

$where = "WHERE 1=1";
$params = [];

if (!empty($searchQuery)) {
    $where .= " AND (t.name LIKE ? OR t.description LIKE ? OR u.username LIKE ?)";
    $searchTerm = '%' . str_replace(' ', '%', $searchQuery) . '%';
    $params = [$searchTerm, $searchTerm, $searchTerm];
}

if (!empty($categoryIds)) {
    $placeholders = str_repeat('?,', count($categoryIds) - 1) . '?';
    $where .= " AND t.category_id IN ($placeholders)";
    $params = array_merge($params, $categoryIds);
}

if ($filterTitle) {
    $where .= " AND t.name LIKE ?";
    $params[] = "%$searchQuery%";
}
if ($filterSubs) {
    $where .= " AND t.description LIKE ?";
    $params[] = "%[SUBS]%";
}
if ($filterAudio) {
    $where .= " AND t.description LIKE ?";
    $params[] = "%[AUDIO]%";
}
if ($filterAuthor) {
    $where .= " AND u.username LIKE ?";
    $params[] = "%$searchQuery%";
}

$sql .= " $where ORDER BY t.uploaded_at DESC";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$torrents = $stmt->fetchAll();

require_once __DIR__ . '/templates/header.php';
?>

<style>
/* ✅ Стил за иконите на категориите в таблицата */
.torrent-category-icon {
    width: 50px;
    height: 30px;
    vertical-align: middle;
    margin-right: 0.3rem;
}

/* ✅ Tooltip стилове */
.torrent-tooltip {
    position: absolute;
    background: #2c2c2c;
    color: white;
    padding: 12px;
    border-radius: 8px;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.5);
    z-index: 10000;
    width: 240px;
    font-size: 13px;
    opacity: 0;
    visibility: hidden;
    transition: opacity 0.25s ease, visibility 0.25s ease;
    pointer-events: none;
}

.torrent-tooltip img {
    width: 100%;
    border-radius: 4px;
    margin-bottom: 8px;
    display: block;
}

.torrent-tooltip .placeholder {
    width: 100%;
    height: 120px;
    background: #444;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #aaa;
    border-radius: 4px;
    margin-bottom: 8px;
}

.torrent-tooltip .stats {
    line-height: 1.5;
}

.torrent-tooltip .seeds { color: #4caf50; }
.torrent-tooltip .leechers { color: #f44336; }
.torrent-tooltip .size { color: #2196f3; }

.torrent-name-link {
    cursor: pointer;
    text-decoration: underline;
    color: #007bff;
    display: inline-block;
    max-width: 100%;
    word-break: break-word;
}

/* 📁 КАТЕГОРИИ — ЕДИН РЕД */
.category-filter-row {
    display: flex;
    flex-wrap: wrap;
    gap: 0.5rem;
    margin-bottom: 1.2rem;
    align-items: flex-start; /* ← ЕДИНСТВЕНАТА ПРОМЯНА */
}

.category-group-title {
    font-weight: bold;
    color: #000;
    font-size: 0.8rem;
    margin-right: 0.6rem;
    white-space: nowrap;
}

.category-item label {
    font-weight: normal;
    color: #000;
    font-size: 0.75rem;
    display: flex;
    align-items: center;
    gap: 0.25rem;
    padding: 0.15rem 0.3rem;
    border-radius: 3px;
    cursor: pointer;
}

.category-item label:hover {
    background-color: #f5f5f5;
}

.category-item input[type="checkbox"] {
    width: 12px;
    height: 12px;
    margin: 0;
}

.category-item img {
    width: 12px;
    height: 12px;
    margin: 0;
}

/* 🎯 Филтри + търсачка */
.filter-bar {
    display: flex;
    align-items: center;
    gap: 1rem;
    margin-bottom: 1.2rem;
    flex-wrap: wrap;
}

.filter-bar .filter-options {
    display: flex;
    align-items: center;
    gap: 0.8rem;
    margin: 0;
}

.filter-bar .filter-options label {
    display: flex;
    align-items: center;
    gap: 0.4rem;
    cursor: pointer;
    font-size: 0.8rem;
}

.filter-bar .search-box {
    display: flex;
    align-items: center;
    gap: 0.25rem;
    margin-left: auto;
}

.filter-bar .search-box .form-control {
    font-size: 0.8rem;
    padding: 0.2rem 0.4rem;
    height: auto;
}

.filter-bar .search-box .btn {
    font-size: 0.8rem;
    padding: 0.2rem 0.4rem;
    height: auto;
}

@media (max-width: 767px) {
    .filter-bar {
        flex-direction: column;
        align-items: stretch;
    }
    .filter-bar .search-box {
        margin-left: 0;
        width: 100%;
        justify-content: flex-end;
    }
}
</style>

<div class="container">
    <h2 class="mb-3"><?= $lang->get('torrents') ?></h2>

    <form method="GET" class="mb-4">
        <div class="category-filter-row">
            <?php foreach ($groups as $mainName => $subs): ?>
                <div class="category-group">
                    <span class="category-group-title"><?= htmlspecialchars($mainName) ?>:</span>
                    <?php foreach ($subs as $sub): ?>
                        <span class="category-item">
                            <label>
                                <input type="checkbox" name="categories[]" value="<?= $sub['id'] ?>"
                                    <?= in_array($sub['id'], $categoryIds) ? 'checked' : '' ?>>
                                <?php if ($sub['icon']): ?>
                                    <img src="/<?= htmlspecialchars($sub['icon']) ?>" alt="">
                                <?php endif; ?>
                                <?= htmlspecialchars($sub['sub_name']) ?>
                            </label>
                        </span>
                    <?php endforeach; ?>
                </div>
            <?php endforeach; ?>
        </div>

        <div class="filter-bar">
            <div class="filter-options">
                <label>
                    <input type="radio" name="filter_title" value="1" <?= $filterTitle ? 'checked' : '' ?>>
                    <?= $lang->get('title') ?>
                </label>
                <label>
                    <input type="radio" name="filter_subs" value="1" <?= $filterSubs ? 'checked' : '' ?>>
                    <?= $lang->get('subs') ?>
                </label>
                <label>
                    <input type="radio" name="filter_audio" value="1" <?= $filterAudio ? 'checked' : '' ?>>
                    <?= $lang->get('audio') ?>
                </label>
                <label>
                    <input type="radio" name="filter_author" value="1" <?= $filterAuthor ? 'checked' : '' ?>>
                    <?= $lang->get('shared_by_author') ?>
                </label>
            </div>

            <div class="search-box">
                <span class="input-group-text bg-light">🔍</span>
                <input type="text" name="q" class="form-control" value="<?= htmlspecialchars($searchQuery) ?>" placeholder="<?= $lang->get('search_placeholder') ?>">
                <button type="submit" class="btn btn-primary"><?= $lang->get('search_button') ?></button>
            </div>
        </div>
    </form>

    <?php if (empty($torrents)): ?>
        <div class="alert alert-info">
            <?php if (!empty($searchQuery)): ?>
                <?= $lang->get('no_results') ?>
            <?php else: ?>
                <?= $lang->get('no_torrents_yet') ?>
            <?php endif; ?>
        </div>
    <?php else: ?>
        <div class="table-responsive">
            <table class="table table-striped">
                <thead>
                    <tr>
                        <th><?= $lang->get('category') ?></th>
                        <th style="width: 35%; min-width: 200px;"><?= $lang->get('name') ?></th>
                        <th><?= $lang->get('size') ?></th>
                        <th><?= $lang->get('seeders') ?></th>
                        <th><?= $lang->get('leechers') ?></th>
                        <th><?= $lang->get('uploader') ?></th>
                        <th><?= $lang->get('uploaded') ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($torrents as $t): ?>
                        <tr data-torrent-id="<?= $t['id'] ?>">
                            <td>
                                <?php if (!empty($t['category_icon'])): ?>
                                    <img src="/<?= htmlspecialchars($t['category_icon']) ?>" 
                                         class="torrent-category-icon" 
                                         alt="<?= htmlspecialchars($t['category_name'] ?? '') ?>">
                                <?php endif; ?>
                                <?= htmlspecialchars($t['category_name'] ?? $lang->get('uncategorized')) ?>
                            </td>
                            <td>
                                <a href="/torrent.php?id=<?= $t['id'] ?>" 
                                   class="torrent-name-link"
                                   data-torrent-id="<?= $t['id'] ?>">
                                    <?= htmlspecialchars($t['name']) ?>
                                </a>
                            </td>
                            <td><?= formatBytes($t['size']) ?></td>
                            <td class="seeders"><span style="color: #28a745;"><?= $t['seeders'] ?></span></td>
                            <td class="leechers"><span style="color: #dc3545;"><?= $t['leechers'] ?></span></td>
                            <td>
                                <?php if (!empty($t['uploader_name'])): ?>
                                    <a href="/profile.php?id=<?= $t['uploader_id'] ?>" class="text-decoration-none">
                                        <?= htmlspecialchars($t['uploader_name']) ?>
                                    </a>
                                <?php else: ?>
                                    <?= $lang->get('unknown') ?>
                                <?php endif; ?>
                            </td>
                            <td><?= date('Y-m-d H:i', strtotime($t['uploaded_at'])) ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</div>

<div id="global-tooltip" class="torrent-tooltip"></div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const links = document.querySelectorAll('.torrent-name-link');
    let hoverTimeout = null;
    const tooltip = document.getElementById('global-tooltip');
    const currentLang = '<?= $_SESSION['lang'] ?? 'en' ?>';

    links.forEach(link => {
        link.addEventListener('mouseenter', () => {
            const torrentId = link.dataset.torrentId;
            hoverTimeout = setTimeout(() => {
                if (tooltip.dataset.currentId !== torrentId) {
                    fetch(`/ajax/torrent_tooltip.php?id=${torrentId}&lang=${currentLang}`)
                        .then(response => response.text())
                        .then(html => {
                            tooltip.innerHTML = html;
                            tooltip.dataset.currentId = torrentId;
                            positionTooltip(tooltip, link);
                            tooltip.style.opacity = '1';
                            tooltip.style.visibility = 'visible';
                        })
                        .catch(err => console.error('Tooltip error:', err));
                } else {
                    positionTooltip(tooltip, link);
                    tooltip.style.opacity = '1';
                    tooltip.style.visibility = 'visible';
                }
            }, 400);
        });

        link.addEventListener('mouseleave', () => {
            clearTimeout(hoverTimeout);
            tooltip.style.opacity = '0';
            tooltip.style.visibility = 'hidden';
        });
    });

    function positionTooltip(tooltip, link) {
        const rect = link.getBoundingClientRect();
        const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
        const scrollLeft = window.pageXOffset || document.documentElement.scrollLeft;
        let top = rect.top + scrollTop - tooltip.offsetHeight - 10;
        if (top < 0) top = rect.bottom + scrollTop + 10;
        tooltip.style.top = top + 'px';
        tooltip.style.left = (rect.left + scrollLeft) + 'px';
    }
});
</script>

<?php require_once __DIR__ . '/templates/footer.php'; ?>