{extends file="layout.tpl"}

{block name="content"}
<div class="container-fluid">
    <!-- Header -->
    <div class="d-flex flex-wrap justify-content-between align-items-center mb-4">
        <div>
            <h4 class="mb-1">Urządzenia</h4>
            <p class="text-muted mb-0">
                {if !$isAdmin && !$isReseller}
                Twoje urządzenia: {$currentDevicesCount}/{$deviceLimit}
                {elseif $filterUserId == 'all'}
                Wszystkie urządzenia
                {elseif $filterUserId && $filterUserId != ''}
                Urządzenia użytkownika
                {else}
                Twoje urządzenia
                {/if}
            </p>
        </div>
        {if $isAdmin || $isReseller || $currentDevicesCount < $deviceLimit}
        <a href="{$baseUrl}/devices/add{if $filterUserId && $filterUserId != 'all'}?user_id={$filterUserId}{/if}" class="btn btn-primary">
            <i class="bi bi-plus-lg me-1"></i>Dodaj urządzenie
        </a>
        {/if}
    </div>

    <!-- Filters -->
    <div class="card mb-4">
        <div class="card-body">
            <form method="get" class="row g-3 align-items-end" id="filterForm">
                <div class="col-md-4">
                    <label class="form-label small text-muted">Szukaj</label>
                    <div class="input-group">
                        <span class="input-group-text"><i class="bi bi-search"></i></span>
                        <input type="text" name="search" class="form-control" placeholder="MAC, kod, nazwa..." value="{$search|default:''}">
                    </div>
                </div>
                
                {if $isAdmin || $isReseller}
                <div class="col-md-4">
                    <label class="form-label small text-muted">Użytkownik</label>
                    <select name="user_id" class="form-select auto-submit">
                        <option value="">-- Moje --</option>
                        <option value="all" {if $filterUserId == 'all'}selected{/if}>Wszyscy</option>
                        {foreach $users as $user}
                        <option value="{$user.id}" {if $filterUserId == $user.id}selected{/if}>{$user.username}</option>
                        {/foreach}
                    </select>
                </div>
                {/if}
                
                <div class="col-md-2">
                    <button type="submit" class="btn btn-secondary w-100">
                        <i class="bi bi-filter me-1"></i>Filtruj
                    </button>
                </div>
                
                {if $search || $filterUserId}
                <div class="col-auto">
                    <a href="{$baseUrl}/devices" class="btn btn-outline-secondary">
                        <i class="bi bi-x-lg"></i>
                    </a>
                </div>
                {/if}
            </form>
        </div>
    </div>

    <!-- Devices Table -->
    <div class="card">
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover align-middle mb-0">
                    <thead>
                        <tr>
                            <th>Nazwa</th>
                            <th>MAC</th>
                            <th>Kod</th>
                            {if ($isAdmin || $isReseller) && $filterUserId == 'all'}<th>Użytkownik</th>{/if}
                            <th>Playlisty</th>
                            <th>Notatki</th>
                            <th>Status</th>
                            <th>Utworzony</th>
                            <th class="text-end">Akcje</th>
                        </tr>
                    </thead>
                    <tbody>
                        {foreach $devices as $device}
                        <tr>
                            <td>
                                <strong>{$device.name|default:'Bez nazwy'}</strong>
                            </td>
                            <td><code class="user-select-all">{$device.mac}</code></td>
                            <td><code class="user-select-all">{$device.code}</code></td>
                            {if ($isAdmin || $isReseller) && $filterUserId == 'all'}
                            <td>
                                <a href="{$baseUrl}/devices?user_id={$device.user_id}">{$device.username}</a>
                            </td>
                            {/if}
                            <td>
                                <a href="{$baseUrl}/playlists?device_id={$device.id}" class="badge bg-info text-decoration-none">
                                    {$device.playlists_count} playlist
                                </a>
                            </td>
                            <td>
                                <span class="badge bg-secondary notes-badge" 
                                      style="cursor:pointer;"
                                      data-entity-type="device" 
                                      data-entity-id="{$device.id}"
                                      onclick="NotesManager.open('device', {$device.id}, '{$device.name|default:$device.mac|escape:'javascript'}')"
                                      title="Pokaż notatki">
                                    <i class="bi bi-sticky"></i> <span class="notes-count">{$device.notes_count|default:0}</span>
                                </span>
                            </td>
                            <td>
                                {if $device.is_blocked}
                                <span class="badge bg-danger"><i class="bi bi-shield-x me-1"></i>Zablokowane</span>
                                {else}
                                <span class="badge bg-success"><i class="bi bi-check-circle me-1"></i>Aktywne</span>
                                {/if}
                            </td>
                            <td>{$device.created_at|date_format:"%d.%m.%Y"}</td>
                            <td class="text-end">
                                <div class="btn-group">
                                    <button type="button" class="btn btn-sm btn-outline-secondary" 
                                            title="Dodaj notatkę"
                                            onclick="NotesManager.quickAdd('device', {$device.id}, '{$device.name|default:$device.mac|escape:'javascript'}')">
                                        <i class="bi bi-sticky"></i>
                                    </button>
                                    <a href="{$baseUrl}/playlists/add?device_id={$device.id}" class="btn btn-sm btn-outline-success" title="Dodaj playlistę">
                                        <i class="bi bi-plus-lg"></i>
                                    </a>
                                    <a href="{$baseUrl}/playlists?device_id={$device.id}" class="btn btn-sm btn-outline-info" title="Playlisty">
                                        <i class="bi bi-list-ul"></i>
                                    </a>
                                    <a href="{$baseUrl}/settings/device?id={$device.id}" class="btn btn-sm btn-outline-secondary" title="Ustawienia">
                                        <i class="bi bi-sliders"></i>
                                    </a>
                                    <a href="{$baseUrl}/devices/edit?id={$device.id}" class="btn btn-sm btn-outline-primary" title="Edytuj">
                                        <i class="bi bi-pencil"></i>
                                    </a>
                                    {if $isAdmin}
                                    <button type="button" class="btn btn-sm btn-outline-warning toggle-block-btn" 
                                            title="{if $device.is_blocked}Odblokuj{else}Zablokuj{/if}"
                                            data-id="{$device.id}"
                                            data-name="{$device.name|default:$device.mac}"
                                            data-blocked="{$device.is_blocked}">
                                        <i class="bi bi-{if $device.is_blocked}unlock{else}lock{/if}"></i>
                                    </button>
                                    {/if}
                                    <button type="button" class="btn btn-sm btn-outline-danger delete-device-btn" 
                                            title="Usuń"
                                            data-id="{$device.id}"
                                            data-name="{$device.name|default:$device.mac}">
                                        <i class="bi bi-trash"></i>
                                    </button>
                                </div>
                            </td>
                        </tr>
                        {foreachelse}
                        <tr>
                            <td colspan="{if $isAdmin}9{else}8{/if}" class="text-center py-5">>
                                <div class="text-muted mb-3">
                                    <i class="bi bi-tv" style="font-size: 3rem;"></i>
                                </div>
                                <p class="mb-3">Brak urządzeń</p>
                                {if !$isAdmin && $currentDevicesCount < $deviceLimit}
                                <a href="{$baseUrl}/devices/add" class="btn btn-primary">
                                    <i class="bi bi-plus-lg me-1"></i>Dodaj pierwsze urządzenie
                                </a>
                                {/if}
                            </td>
                        </tr>
                        {/foreach}
                    </tbody>
                </table>
            </div>
        </div>

        {if $pagination.total_pages > 1}
        <div class="card-footer">
            <nav>
                {* Budujemy query string dla paginacji *}
                {$paginationParams = ""}
                {if $filterUserId}{$paginationParams = "{$paginationParams}&user_id={$filterUserId}"}{/if}
                {if $search}{$paginationParams = "{$paginationParams}&search={$search|escape:'url'}"}{/if}
                
                <ul class="pagination pagination-sm mb-0 justify-content-center">
                    <li class="page-item{if !$pagination.has_prev} disabled{/if}">
                        <a class="page-link" href="?page={$pagination.current_page - 1}{$paginationParams}">
                            <i class="bi bi-chevron-left"></i>
                        </a>
                    </li>
                    {foreach $pagination.pages as $page}
                        {if $page === '...'}
                        <li class="page-item disabled"><span class="page-link">...</span></li>
                        {else}
                        <li class="page-item{if $page == $pagination.current_page} active{/if}">
                            <a class="page-link" href="?page={$page}{$paginationParams}">{$page}</a>
                        </li>
                        {/if}
                    {/foreach}
                    <li class="page-item{if !$pagination.has_next} disabled{/if}">
                        <a class="page-link" href="?page={$pagination.current_page + 1}{$paginationParams}">
                            <i class="bi bi-chevron-right"></i>
                        </a>
                    </li>
                </ul>
            </nav>
        </div>
        {/if}
    </div>
</div>

<!-- Hidden forms -->
<form id="deleteDeviceForm" method="post" action="{$baseUrl}/devices/delete" style="display:none;">
    <input type="hidden" name="csrf_token" value="{$csrfToken}">
    <input type="hidden" name="id" id="deleteDeviceId">
</form>
<form id="toggleBlockForm" method="post" action="{$baseUrl}/devices/toggle-block" style="display:none;">
    <input type="hidden" name="csrf_token" value="{$csrfToken}">
    <input type="hidden" name="id" id="toggleBlockId">
</form>
{/block}

{block name="scripts"}
{literal}
<script>
(function() {
    var swalConfig = {
        background: '#1a1d21',
        color: '#e1e1e1',
        confirmButtonColor: '#0d6efd',
        cancelButtonColor: '#6c757d'
    };

    // Delete device
    document.querySelectorAll('.delete-device-btn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            var id = this.dataset.id;
            var name = this.dataset.name;

            Swal.fire({
                title: 'Potwierdź usunięcie',
                html: 'Czy na pewno chcesz usunąć urządzenie <strong>"' + name + '"</strong>?<br><br><span class="text-danger"><i class="bi bi-exclamation-triangle me-1"></i>Ta operacja usunie również wszystkie playlisty tego urządzenia!</span>',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Usuń',
                cancelButtonText: 'Anuluj',
                confirmButtonColor: '#dc3545',
                background: swalConfig.background,
                color: swalConfig.color
            }).then(function(result) {
                if (result.isConfirmed) {
                    document.getElementById('deleteDeviceId').value = id;
                    document.getElementById('deleteDeviceForm').submit();
                }
            });
        });
    });

    // Toggle block
    document.querySelectorAll('.toggle-block-btn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            var id = this.dataset.id;
            var name = this.dataset.name;
            var isBlocked = this.dataset.blocked === '1';
            var actionText = isBlocked ? 'odblokować' : 'zablokować';

            Swal.fire({
                title: (isBlocked ? 'Odblokowanie' : 'Blokowanie') + ' urządzenia',
                html: 'Czy na pewno chcesz ' + actionText + ' urządzenie <strong>"' + name + '"</strong>?',
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: isBlocked ? 'Odblokuj' : 'Zablokuj',
                cancelButtonText: 'Anuluj',
                confirmButtonColor: isBlocked ? '#198754' : '#ffc107',
                background: swalConfig.background,
                color: swalConfig.color
            }).then(function(result) {
                if (result.isConfirmed) {
                    document.getElementById('toggleBlockId').value = id;
                    document.getElementById('toggleBlockForm').submit();
                }
            });
        });
    });
    
    // Auto-submit przy zmianie filtrów
    document.querySelectorAll('.auto-submit').forEach(function(el) {
        el.addEventListener('change', function() {
            document.getElementById('filterForm').submit();
        });
    });
})();
</script>
{/literal}
{/block}
