<?php
/**
 * dns_users.php — Show all devices registered under a specific DNS server with NXS Panel dynamic light/dark style.
 */

declare(strict_types=1);

require_once __DIR__ . '/lib/auth.php';
require_once __DIR__ . '/lib/db.php';
require_once __DIR__ . '/lib/helpers.php';
require_once __DIR__ . '/lib/i18n.php';

require_login();

$pdo = db();
$dnsId = (int) ($_GET['dns_id'] ?? 0);

// Fetch selected DNS server
$dnsStmt = $pdo->prepare('SELECT id, title, url FROM dns WHERE id = ? LIMIT 1');
$dnsStmt->execute([$dnsId]);
$dns = $dnsStmt->fetch();

if (!$dns) {
    header('Location: dns.php');
    exit;
}

// Unlink / Delete Playlist action
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'delete_playlist') {
    csrf_check();
    $playlistId = (int) ($_POST['playlist_id'] ?? 0);
    if ($playlistId > 0) {
        $delStmt = $pdo->prepare('DELETE FROM playlists WHERE id = ?');
        $delStmt->execute([$playlistId]);
        header('Location: dns_users.php?dns_id=' . $dnsId . '&deleted=1');
        exit;
    }
}

// Fetch users/devices connected to this DNS
$stmt = $pdo->prepare('
    SELECT p.id as playlist_id, p.username, p.password, p.type, p.url, d.id as device_id, d.mac, d.device_key, d.account_name
    FROM playlists p
    INNER JOIN devices d ON p.device_id = d.id
    WHERE p.url = ? OR p.url LIKE ?
    ORDER BY p.id DESC
');
$stmt->execute([$dns['url'], '%' . $dns['url'] . '%']);
$userList = $stmt->fetchAll();
$totalUsers = count($userList);

$pageTitle = __('users_for', 'Users for') . ' ' . $dns['title'] . ' — LEGENDS PANEL';
require __DIR__ . '/lib/header.php';
?>

<!-- NXS Panel Dynamic Theme Stilleri (Light & Dark Uyumlu) -->
<style>
    .glass-card {
        background: #ffffff !important;
        border: 1px solid #e5e7eb !important;
        border-radius: 16px !important;
        box-shadow: 0 4px 15px rgba(0, 0, 0, 0.02) !important;
        overflow: hidden;
        margin-bottom: 24px;
        transition: background 0.3s ease, border-color 0.3s ease;
    }

    .filter-bar {
        padding: 20px 24px;
        border-bottom: 1px solid #e5e7eb;
        background: #f8fafc;
        display: flex;
        align-items: center;
        gap: 16px;
        flex-wrap: wrap;
        transition: background 0.3s ease, border-color 0.3s ease;
    }

    .filter-bar .search-input-group {
        flex: 1;
        min-width: 280px;
        position: relative;
    }

    .filter-bar .search-input-group i {
        position: absolute;
        left: 14px;
        top: 50%;
        transform: translateY(-50%);
        color: #9ca3af;
        font-size: 18px;
    }

    .filter-bar .search-input-group input {
        width: 100%;
        padding: 10px 14px 10px 42px;
        border: 1px solid #e5e7eb;
        border-radius: 10px;
        font-size: 0.9rem;
        background: #ffffff;
        color: #1f2937;
        outline: none;
        transition: border-color 0.2s, background 0.3s ease, color 0.3s ease;
    }

    .filter-bar .search-input-group input:focus {
        border-color: #7c3aed;
    }

    .filter-select {
        padding: 10px 16px;
        border: 1px solid #e5e7eb;
        border-radius: 10px;
        font-size: 0.9rem;
        background: #ffffff;
        color: #374151;
        outline: none;
        font-weight: 500;
        transition: border-color 0.2s, background 0.3s ease, color 0.3s ease;
    }

    .text-device-name {
        color: #111827 !important;
        font-weight: 600;
    }

    .code-badge {
        font-family: 'SFMono-Regular', Consolas, Menlo, monospace;
        background: #f3f4f6;
        padding: 4px 8px;
        border-radius: 6px;
        border: 1px solid #e5e7eb;
        color: #7c3aed;
        font-weight: 600;
        font-size: 0.85rem;
    }

    .badge-user-count {
        background: #f5f3ff;
        color: #7c3aed;
        border: 1px solid #ddd6fe;
        font-size: 0.8rem;
        font-weight: 700;
        padding: 0.35em 0.75em;
        border-radius: 2rem;
    }

    .copy-btn {
        background: none;
        border: none;
        color: #9ca3af;
        cursor: pointer;
        padding: 2px 4px;
        font-size: 0.85rem;
        transition: all 0.2s ease;
    }

    .copy-btn:hover {
        color: #7c3aed;
    }

    .titan-table {
        margin-bottom: 0;
        color: #1f2937;
        width: 100%;
    }

    .titan-table th {
        font-size: 0.75rem;
        font-weight: 700;
        letter-spacing: 0.8px;
        text-transform: uppercase;
        color: #4b5563;
        background: #f8fafc;
        border-bottom: 2px solid #e5e7eb;
        padding: 14px 20px;
        white-space: nowrap;
        transition: background 0.3s ease, color 0.3s ease, border-color 0.3s ease;
    }

    .titan-table td {
        border-bottom: 1px solid #e5e7eb !important;
        padding: 14px 20px;
        vertical-align: middle;
        font-size: 0.9rem;
        color: #374151;
        white-space: nowrap !important;
        transition: background 0.3s ease, color 0.3s ease, border-color 0.3s ease;
    }

    .titan-table tbody tr:hover {
        background: #f8fafc;
    }

    .pagination-container {
        padding: 16px 24px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        background: #f8fafc;
        border-top: 1px solid #e5e7eb;
        flex-wrap: wrap;
        gap: 12px;
    }

    /* --- Dark Mode (Koyu Tema) Uyarlamaları --- */
    [data-bs-theme="dark"] .glass-card {
        background: #171426 !important;
        border-color: rgba(255, 255, 255, 0.08) !important;
        color: #f3f4f6 !important;
    }

    [data-bs-theme="dark"] .filter-bar,
    [data-bs-theme="dark"] .pagination-container {
        background: #141122 !important;
        border-color: rgba(255, 255, 255, 0.08) !important;
    }

    [data-bs-theme="dark"] .filter-bar .search-input-group input,
    [data-bs-theme="dark"] .filter-select {
        background: #171426 !important;
        border-color: rgba(255, 255, 255, 0.1) !important;
        color: #f3f4f6 !important;
    }

    [data-bs-theme="dark"] .titan-table th {
        background: #141122 !important;
        color: #9ca3af !important;
        border-bottom-color: rgba(255, 255, 255, 0.08) !important;
    }

    [data-bs-theme="dark"] .titan-table td {
        background: #171426 !important;
        color: #f3f4f6 !important;
        border-bottom-color: rgba(255, 255, 255, 0.08) !important;
    }

    [data-bs-theme="dark"] .titan-table tbody tr:hover {
        background: rgba(255, 255, 255, 0.02) !important;
    }

    [data-bs-theme="dark"] .text-device-name {
        color: #f3f4f6 !important;
    }

    [data-bs-theme="dark"] .code-badge {
        background: rgba(255, 255, 255, 0.05) !important;
        border-color: rgba(255, 255, 255, 0.1) !important;
        color: #a78bfa !important;
    }

    [data-bs-theme="dark"] .badge-user-count {
        background: rgba(124, 58, 237, 0.15);
        color: #a78bfa;
        border-color: rgba(124, 58, 237, 0.3);
    }
</style>

<!-- Top Title & Navigation -->
<div class="d-flex flex-wrap justify-content-between align-items-center gap-3 mb-4">
    <div>
        <h1 class="h3 mb-1 fw-bold text-dark d-flex align-items-center gap-2">
            <?= __('users_for', 'Users for') ?> <?= e($dns['title']) ?>
            <span class="badge badge-user-count" id="userBadge"><?= $totalUsers ?> <?= $totalUsers !== 1 ? __('users', 'Users') : __('user', 'User') ?></span>
        </h1>
        <p class="text-muted font-monospace mb-0 d-flex align-items-center gap-2" style="font-size: 0.88rem;">
            <?= e($dns['url']) ?>
            <button class="copy-btn" onclick="copyToClipboard('<?= e($dns['url']) ?>', this)" title="<?= __('copy_dns_url', 'Copy DNS URL') ?>">
                <i class="la la-copy"></i>
            </button>
        </p>
    </div>
    <a href="dns.php" class="btn btn-outline-secondary rounded-3 px-3"><i class="la la-arrow-left me-1"></i> <?= __('back_to_dns', 'Back to DNS List') ?></a>
</div>

<?php if (isset($_GET['deleted'])): ?>
    <div class="alert alert-success alert-dismissible fade show glass-card mb-4 text-success" role="alert">
        <i class="la la-check-circle me-1 fs-5"></i> <?= __('playlist_removed', 'Playlist removed successfully.') ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
<?php endif; ?>

<!-- Data Table Card -->
<div class="glass-card">
    <div class="filter-bar">
        <div class="search-input-group">
            <i class="la la-search"></i>
            <input type="text" id="dnsUserSearch" placeholder="<?= __('search_device_placeholder', 'Search by Device Name, MAC, or Device Key...') ?>">
        </div>
        
        <!-- Sayfa Başına Kayıt Seçici -->
        <select id="rowsPerPage" class="filter-select">
            <option value="25" selected>25</option>
            <option value="50">50</option>
            <option value="100">100</option>
            <option value="all"><?= __('all', 'All') ?></option>
        </select>
    </div>

    <?php if ($totalUsers === 0): ?>
        <div class="text-center py-5">
            <i class="la la-plug fs-1 d-block mb-2 text-muted"></i>
            <p class="text-muted mb-0"><?= __('no_devices_found_dns', 'No devices or playlists found for this DNS server.') ?></p>
        </div>
    <?php else: ?>
        <div class="table-responsive">
            <table class="table titan-table" id="usersTable">
                <thead>
                    <tr>
                        <th style="width: 50px;">#</th>
                        <th><?= __('device_name', 'DEVICE NAME') ?></th>
                        <th><?= __('mac_address', 'MAC ADDRESS') ?></th>
                        <th><?= __('device_key', 'DEVICE KEY') ?></th>
                        <th><?= __('username', 'USERNAME') ?></th>
                        <th><?= __('type', 'TYPE') ?></th>
                        <th class="text-end"><?= __('actions', 'ACTIONS') ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($userList as $index => $u): ?>
                        <?php 
                            $typeLower = strtolower((string)$u['type']);
                            $badgeStyle = ($typeLower === 'm3u') ? 'background: #10b981; color: #fff;' : 'background: #7c3aed; color: #fff;';

                            $displayUser = trim((string)$u['username']);
                            
                            if ($displayUser === '' && !empty($u['url'])) {
                                $parsedUrl = parse_url($u['url']);
                                if (isset($parsedUrl['query'])) {
                                    parse_str($parsedUrl['query'], $queryParams);
                                    $displayUser = (string)($queryParams['username'] ?? $queryParams['user'] ?? '');
                                }
                                if ($displayUser === '') {
                                    $displayUser = $u['url'];
                                }
                            }

                            if ($displayUser === '') {
                                $displayUser = 'M3U Link';
                            }

                            $searchHaystack = strtolower(
                                ($u['account_name'] ?? '') . ' ' . 
                                $u['mac'] . ' ' . 
                                ($u['device_key'] ?? '') . ' ' . 
                                $displayUser . ' ' . 
                                $u['type']
                            );
                        ?>
                        <tr class="user-row" data-search="<?= e($searchHaystack) ?>">
                            <td class="text-muted fw-bold row-index" style="font-size: 0.85rem;"><?= $index + 1 ?></td>
                            <td>
                                <a href="device_edit.php?id=<?= (int)$u['device_id'] ?>" class="text-decoration-none text-device-name">
                                    <?= e($u['account_name'] ?: '—') ?>
                                </a>
                            </td>
                            <td>
                                <span class="code-badge"><?= e($u['mac']) ?></span>
                                <button class="copy-btn ms-1" onclick="copyToClipboard('<?= e($u['mac']) ?>', this)" title="<?= __('copy_mac', 'Copy MAC') ?>">
                                    <i class="la la-copy"></i>
                                </button>
                            </td>
                            <td>
                                <span class="code-badge" style="color: #6366f1;"><?= e($u['device_key'] ?: '—') ?></span>
                                <?php if ($u['device_key']): ?>
                                    <button class="copy-btn ms-1" onclick="copyToClipboard('<?= e($u['device_key']) ?>', this)" title="<?= __('copy_key', 'Copy Key') ?>">
                                        <i class="la la-copy"></i>
                                    </button>
                                <?php endif; ?>
                            </td>
                            <td class="text-truncate" style="max-width: 200px; color: #4b5563;">
                                <?= e($displayUser) ?>
                            </td>
                            <td>
                                <span class="badge" style="<?= $badgeStyle ?> font-weight: 500; padding: 5px 10px; border-radius: 6px;">
                                    <?= strtoupper(e($u['type'])) ?>
                                </span>
                            </td>
                            <td class="text-end">
                                <a class="btn btn-sm btn-warning py-1 px-2 text-dark" href="playlist_edit.php?id=<?= (int)$u['playlist_id'] ?>&ref_dns=<?= $dnsId ?>" style="background: #f59e0b; border-color: #f59e0b; color: #fff !important;">
                                    <i class="la la-edit"></i> <?= __('edit', 'Edit') ?>
                                </a>
                                <form method="post" action="dns_users.php?dns_id=<?= $dnsId ?>" class="d-inline m-0" onsubmit="return confirm('<?= __('confirm_remove_playlist', 'Are you sure you want to remove this playlist from this DNS?') ?>');">
                                    <?= csrf_field() ?>
                                    <input type="hidden" name="action" value="delete_playlist">
                                    <input type="hidden" name="playlist_id" value="<?= (int)$u['playlist_id'] ?>">
                                    <button type="submit" class="btn btn-sm btn-danger py-1 px-2" style="background: #ef4444; border-color: #ef4444;">
                                        <i class="la la-trash"></i> <?= __('unlink', 'Unlink') ?>
                                    </button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            <div id="noMatchMessage" class="text-center py-5 d-none">
                <i class="la la-search-minus fs-1 d-block mb-2 text-muted"></i>
                <p class="text-muted mb-0"><?= __('no_devices_matching_search', 'No devices found matching your search.') ?></p>
            </div>
        </div>

        <!-- Sayfalama Alt Barı -->
        <div class="pagination-container">
            <div class="text-muted" style="font-size: 0.85rem;" id="paginationInfo">
                <?= __('showing_entries', 'Showing 0 to 0 of 0 entries') ?>
            </div>
            <nav>
                <ul class="pagination pagination-sm mb-0" id="paginationNav"></ul>
            </nav>
        </div>
    <?php endif; ?>
</div>

<!-- JavaScript Engine (Search + Pagination) -->
<script>
document.addEventListener('DOMContentLoaded', function () {
    const searchInput = document.getElementById('dnsUserSearch');
    const rowsPerPageSelect = document.getElementById('rowsPerPage');
    const allRows = Array.from(document.querySelectorAll('#usersTable tbody tr.user-row'));
    const noMatchMsg = document.getElementById('noMatchMessage');
    const userBadge = document.getElementById('userBadge');
    const paginationNav = document.getElementById('paginationNav');
    const paginationInfo = document.getElementById('paginationInfo');

    if (!allRows.length) return;

    let currentPage = 1;

    function renderTable() {
        const query = searchInput ? searchInput.value.toLowerCase().trim() : '';
        const limitValue = rowsPerPageSelect ? rowsPerPageSelect.value : '25';

        const filteredRows = allRows.filter(row => {
            const haystack = row.getAttribute('data-search') || '';
            return haystack.includes(query);
        });

        const totalFiltered = filteredRows.length;
        const perPage = limitValue === 'all' ? totalFiltered : parseInt(limitValue, 10);
        const totalPages = Math.max(1, Math.ceil(totalFiltered / perPage));

        if (currentPage > totalPages) currentPage = totalPages;

        const startIndex = (currentPage - 1) * perPage;
        const endIndex = limitValue === 'all' ? totalFiltered : Math.min(startIndex + perPage, totalFiltered);

        allRows.forEach(row => row.style.display = 'none');

        filteredRows.slice(startIndex, endIndex).forEach(row => {
            row.style.display = '';
        });

        if (noMatchMsg) {
            if (totalFiltered === 0) {
                noMatchMsg.classList.remove('d-none');
            } else {
                noMatchMsg.classList.add('d-none');
            }
        }

        if (userBadge) {
            userBadge.textContent = totalFiltered + (totalFiltered === 1 ? ' User' : ' Users');
        }

        if (paginationInfo) {
            if (totalFiltered === 0) {
                paginationInfo.textContent = 'Showing 0 entries';
            } else {
                paginationInfo.textContent = `Showing ${startIndex + 1} to ${endIndex} of ${totalFiltered} entries`;
            }
        }

        renderPaginationNav(totalPages);
    }

    function renderPaginationNav(totalPages) {
        if (!paginationNav) return;
        paginationNav.innerHTML = '';

        if (totalPages <= 1) return;

        const prevLi = document.createElement('li');
        prevLi.className = `page-item ${currentPage === 1 ? 'disabled' : ''}`;
        prevLi.innerHTML = `<a class="page-link" href="#">Önceki</a>`;
        prevLi.addEventListener('click', (e) => {
            e.preventDefault();
            if (currentPage > 1) {
                currentPage--;
                renderTable();
            }
        });
        paginationNav.appendChild(prevLi);

        for (let i = 1; i <= totalPages; i++) {
            if (i == 1 || i == totalPages || (i >= currentPage - 2 && i <= currentPage + 2)) {
                const li = document.createElement('li');
                li.className = `page-item ${i === currentPage ? 'active' : ''}`;
                li.innerHTML = `<a class="page-link" href="#">${i}</a>`;
                li.addEventListener('click', (e) => {
                    e.preventDefault();
                    currentPage = i;
                    renderTable();
                });
                paginationNav.appendChild(li);
            } else if (i == currentPage - 3 || i == currentPage + 3) {
                const dotsLi = document.createElement('li');
                dotsLi.className = 'page-item disabled';
                dotsLi.innerHTML = `<span class="page-link">...</span>`;
                paginationNav.appendChild(dotsLi);
            }
        }

        const nextLi = document.createElement('li');
        nextLi.className = `page-item ${currentPage === totalPages ? 'disabled' : ''}`;
        nextLi.innerHTML = `<a class="page-link" href="#">Sonraki</a>`;
        nextLi.addEventListener('click', (e) => {
            e.preventDefault();
            if (currentPage < totalPages) {
                currentPage++;
                renderTable();
            }
        });
        paginationNav.appendChild(nextLi);
    }

    if (searchInput) {
        searchInput.addEventListener('input', () => {
            currentPage = 1;
            renderTable();
        });
    }

    if (rowsPerPageSelect) {
        rowsPerPageSelect.addEventListener('change', () => {
            currentPage = 1;
            renderTable();
        });
    }

    renderTable();
});

function copyToClipboard(text, btnElement) {
    navigator.clipboard.writeText(text).then(function() {
        const icon = btnElement.querySelector('i');
        if (icon) {
            icon.className = 'la la-check text-success';
            setTimeout(() => {
                icon.className = 'la la-copy';
            }, 1500);
        }
    });
}
</script>

<?php require __DIR__ . '/lib/footer.php'; ?>