{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">Playlisty</h4>
            <p class="text-muted mb-0">
                {if $filterDeviceId && $filterDeviceName}
                    Playlisty urządzenia: <strong>{$filterDeviceName}</strong>
                    {if $filterDeviceOwner} (właściciel: {$filterDeviceOwner}){/if}
                {elseif $filterUserId && $filterUserId != 'all' && $filterUserName}
                    Playlisty użytkownika: <strong>{$filterUserName}</strong>
                {elseif $filterUserId == 'all'}
                    Wszystkie playlisty
                {elseif !$isAdmin && !$isReseller}
                    Twoje playlisty
                {else}
                    Twoje playlisty
                {/if}
            </p>
        </div>
        {if $filterDeviceId}
        <a href="{$baseUrl}/playlists/add?device_id={$filterDeviceId}" class="btn btn-primary">
            <i class="bi bi-plus-lg me-1"></i>Dodaj playlistę
        </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-3">
                    <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="Nazwa playlisty..." value="{$search|default:''}">
                    </div>
                </div>
                
                {if $isAdmin || $isReseller}
                <div class="col-md-3">
                    <label class="form-label small text-muted">Użytkownik</label>
                    <select name="user_id" class="form-select auto-submit" id="userFilter">
                        <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-3">
                    <label class="form-label small text-muted">Urządzenie</label>
                    <select name="device_id" class="form-select auto-submit" id="deviceFilter">
                        <option value="">Wszystkie</option>
                        {foreach $filteredDevices as $device}
                        <option value="{$device.id}" {if $filterDeviceId == $device.id}selected{/if}>
                            {$device.name|default:$device.mac}{if $filterUserId == 'all' && $device.username} - {$device.username}{/if}
                        </option>
                        {/foreach}
                    </select>
                </div>
                
                <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 || $filterDeviceId || $filterUserId}
                <div class="col-auto">
                    <a href="{$baseUrl}/playlists" class="btn btn-outline-secondary">
                        <i class="bi bi-x-lg"></i>
                    </a>
                </div>
                {/if}
            </form>
        </div>
    </div>

    <!-- Bulk Actions Bar -->
    <div class="card mb-3 bulk-actions-bar" style="display: none;">
        <div class="card-body py-2">
            <div class="d-flex flex-wrap align-items-center gap-2">
                <span class="text-muted me-2">
                    <strong id="selectedCount">0</strong> zaznaczonych
                </span>
                <div class="vr d-none d-md-block"></div>
                <button type="button" class="btn btn-sm btn-outline-success bulk-btn" data-action="activate" title="Aktywuj zaznaczone">
                    <i class="bi bi-check-circle me-1"></i>Aktywuj
                </button>
                <button type="button" class="btn btn-sm btn-outline-secondary bulk-btn" data-action="deactivate" title="Dezaktywuj zaznaczone">
                    <i class="bi bi-x-circle me-1"></i>Dezaktywuj
                </button>
                <button type="button" class="btn btn-sm btn-outline-info bulk-btn" data-action="touch" title="Odśwież update_date">
                    <i class="bi bi-arrow-clockwise me-1"></i>Odśwież
                </button>
                <div class="vr d-none d-md-block"></div>
                <button type="button" class="btn btn-sm btn-outline-primary bulk-btn" data-action="copy" title="Kopiuj do innego urządzenia">
                    <i class="bi bi-copy me-1"></i>Kopiuj
                </button>
                <button type="button" class="btn btn-sm btn-outline-warning bulk-btn" data-action="move" title="Przenieś do innego urządzenia">
                    <i class="bi bi-arrow-right-circle me-1"></i>Przenieś
                </button>
                <div class="vr d-none d-md-block"></div>
                <button type="button" class="btn btn-sm btn-outline-danger bulk-btn" data-action="delete" title="Usuń zaznaczone">
                    <i class="bi bi-trash me-1"></i>Usuń
                </button>
            </div>
        </div>
    </div>

    <!-- Playlists 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 style="width: 40px;">
                                <input type="checkbox" class="form-check-input" id="selectAll" title="Zaznacz wszystkie">
                            </th>
                            <th>Nazwa</th>
                            <th>Typ</th>
                            <th>Urządzenie</th>
                            {if ($isAdmin || $isReseller) && $filterUserId == 'all' && !$filterDeviceId}<th>Użytkownik</th>{/if}
                            <th>Update Date</th>
                            <th>Notatki</th>
                            <th>Status</th>
                            <th class="text-end">Akcje</th>
                        </tr>
                    </thead>
                    <tbody>
                        {foreach $playlists as $playlist}
                        <tr data-playlist-id="{$playlist.id}">
                            <td>
                                <input type="checkbox" class="form-check-input playlist-checkbox" 
                                       value="{$playlist.id}" 
                                       data-name="{$playlist.name|escape:'html'}"
                                       data-device-id="{$playlist.device_id}">
                            </td>
                            <td>
                                <strong>{$playlist.name}</strong>
                                {if $playlist.type == 'xtream'}
                                <br><small class="text-muted">{$playlist.config.host|default:''}</small>
                                {elseif $playlist.type == 'm3u'}
                                <br><small class="text-muted">{$playlist.config.url|default:''|truncate:50}</small>
                                {elseif $playlist.type == 'stalker'}
                                <br><small class="text-muted">{$playlist.config.server_url|default:''}</small>
                                {/if}
                            </td>
                            <td>
                                {if $playlist.type == 'xtream'}
                                <span class="badge bg-primary"><i class="bi bi-broadcast me-1"></i>Xtream</span>
                                {elseif $playlist.type == 'm3u'}
                                <span class="badge bg-success"><i class="bi bi-link-45deg me-1"></i>M3U</span>
                                {elseif $playlist.type == 'stalker'}
                                <span class="badge bg-warning text-dark"><i class="bi bi-hdd-network me-1"></i>Stalker</span>
                                {/if}
                            </td>
                            <td>
                                <a href="{$baseUrl}/playlists?device_id={$playlist.device_id}">
                                    {$playlist.device_name|default:$playlist.mac}
                                </a>
                                <br><small class="text-muted">{$playlist.mac}</small>
                            </td>
                            {if ($isAdmin || $isReseller) && $filterUserId == 'all' && !$filterDeviceId}
                            <td>
                                <a href="{$baseUrl}/playlists?user_id={$playlist.owner_id|default:''}">{$playlist.username}</a>
                            </td>
                            {/if}
                            <td>
                                <span title="{$playlist.update_date|date_format:'%d.%m.%Y %H:%M:%S'}">
                                    {$playlist.update_date|date_format:"%d.%m.%Y %H:%M"}
                                </span>
                            </td>
                            <td>
                                <span class="badge bg-secondary notes-badge" 
                                      style="cursor:pointer;"
                                      data-entity-type="playlist" 
                                      data-entity-id="{$playlist.id}"
                                      onclick="NotesManager.open('playlist', {$playlist.id}, '{$playlist.name|escape:'javascript'}')"
                                      title="Pokaż notatki">
                                    <i class="bi bi-sticky"></i> <span class="notes-count">{$playlist.notes_count|default:0}</span>
                                </span>
                            </td>
                            <td>
                                {if $playlist.is_active}
                                <span class="badge bg-success">Aktywna</span>
                                {else}
                                <span class="badge bg-secondary">Nieaktywna</span>
                                {/if}
                            </td>
                            <td class="text-end">
                                <div class="btn-group">
                                    {if $playlist.type == 'xtream'}
                                    <a href="{$baseUrl}/xtream-check?server={$playlist.config.host|escape:'url'}&user={$playlist.config.username|escape:'url'}&pass={$playlist.config.password|escape:'url'}" 
                                       class="btn btn-sm btn-outline-info" 
                                       title="Sprawdź w Xtream Check">
                                        <i class="bi bi-search"></i>
                                    </a>
                                    {/if}
                                    <button type="button" class="btn btn-sm btn-outline-secondary" 
                                            title="Dodaj notatkę"
                                            onclick="NotesManager.quickAdd('playlist', {$playlist.id}, '{$playlist.name|escape:'javascript'}')">
                                        <i class="bi bi-sticky"></i>
                                    </button>
                                    <button type="button" 
                                            class="btn btn-sm btn-outline-{if $playlist.is_active}secondary{else}success{/if} toggle-active-btn" 
                                            title="{if $playlist.is_active}Dezaktywuj{else}Aktywuj{/if}"
                                            data-id="{$playlist.id}"
                                            data-name="{$playlist.name|escape:'html'}"
                                            data-active="{$playlist.is_active}">
                                        <i class="bi bi-{if $playlist.is_active}pause-circle{else}play-circle{/if}"></i>
                                    </button>
                                    <a href="{$baseUrl}/playlists/clone?id={$playlist.id}" class="btn btn-sm btn-outline-secondary" title="Sklonuj do innego urządzenia">
                                        <i class="bi bi-copy"></i>
                                    </a>
                                    <a href="{$baseUrl}/playlists/edit?id={$playlist.id}" class="btn btn-sm btn-outline-primary" title="Edytuj">
                                        <i class="bi bi-pencil"></i>
                                    </a>
                                    <button type="button" class="btn btn-sm btn-outline-danger delete-btn" 
                                            title="Usuń"
                                            data-id="{$playlist.id}"
                                            data-name="{$playlist.name|escape:'html'}">
                                        <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-list-ul" style="font-size: 3rem;"></i>
                                </div>
                                <p class="mb-3">Brak playlist</p>
                                {if $filterDeviceId}
                                <a href="{$baseUrl}/playlists/add?device_id={$filterDeviceId}" class="btn btn-primary">
                                    <i class="bi bi-plus-lg me-1"></i>Dodaj pierwszą playlistę
                                </a>
                                {else}
                                <p class="text-muted">Wybierz urządzenie aby dodać playlistę</p>
                                {/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 $filterDeviceId}{$paginationParams = "{$paginationParams}&device_id={$filterDeviceId}"}{/if}
                {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>
{/block}

{block name="scripts"}
<script>
var playlistConfig = {
    csrfToken: '{$csrfToken}',
    baseUrl: '{$baseUrl}',
    currentUserId: '{$currentUser.id}',
    deviceOptions: '{foreach $devices as $device}<option value="{$device.id}">{$device.name|default:$device.mac|escape:'javascript'} ({$device.mac}){if $isAdmin} - {$device.username}{/if}</option>{/foreach}'
};
</script>
{literal}
<script>
(function() {
    const csrfToken = playlistConfig.csrfToken;
    const baseUrl = playlistConfig.baseUrl;
    const currentUserId = playlistConfig.currentUserId;
    const deviceOptions = playlistConfig.deviceOptions;
    const selectAll = document.getElementById('selectAll');
    const checkboxes = document.querySelectorAll('.playlist-checkbox');
    const bulkBar = document.querySelector('.bulk-actions-bar');
    const selectedCountEl = document.getElementById('selectedCount');

    const swalConfig = {
        background: '#1a1d21',
        color: '#e1e1e1',
        confirmButtonColor: '#0d6efd',
        cancelButtonColor: '#6c757d'
    };

    function updateBulkBar() {
        const checked = document.querySelectorAll('.playlist-checkbox:checked');
        const count = checked.length;
        selectedCountEl.textContent = count;
        bulkBar.style.display = count > 0 ? 'block' : 'none';
        selectAll.checked = count > 0 && count === checkboxes.length;
        selectAll.indeterminate = count > 0 && count < checkboxes.length;
    }

    function getSelectedIds() {
        return Array.from(document.querySelectorAll('.playlist-checkbox:checked')).map(cb => cb.value);
    }

    function submitForm(action, ids, extraData) {
        extraData = extraData || {};
        const form = document.createElement('form');
        form.method = 'POST';
        form.action = baseUrl + '/playlists/bulk';
        
        const fields = Object.assign({ csrf_token: csrfToken, action: action, ids: ids.join(',') }, extraData);
        for (const key in fields) {
            const input = document.createElement('input');
            input.type = 'hidden';
            input.name = key;
            input.value = fields[key];
            form.appendChild(input);
        }
        
        document.body.appendChild(form);
        form.submit();
    }

    if (selectAll) {
        selectAll.addEventListener('change', function() {
            checkboxes.forEach(function(cb) { cb.checked = selectAll.checked; });
            updateBulkBar();
        });
    }

    checkboxes.forEach(function(cb) { cb.addEventListener('change', updateBulkBar); });

    document.querySelectorAll('.bulk-btn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            const action = this.dataset.action;
            const ids = getSelectedIds();
            if (ids.length === 0) return;

            switch(action) {
                case 'delete':
                    Swal.fire({
                        title: 'Potwierdź usunięcie',
                        html: 'Czy na pewno chcesz usunąć <strong>' + ids.length + '</strong> zaznaczonych playlist?<br><br><span class="text-danger">Tej operacji nie można cofnąć!</span>',
                        icon: 'warning',
                        showCancelButton: true,
                        confirmButtonText: 'Usuń',
                        cancelButtonText: 'Anuluj',
                        confirmButtonColor: '#dc3545',
                        background: swalConfig.background,
                        color: swalConfig.color
                    }).then(function(result) {
                        if (result.isConfirmed) submitForm('delete', ids);
                    });
                    break;

                case 'activate':
                    Swal.fire({
                        title: 'Aktywacja playlist',
                        html: 'Czy aktywować <strong>' + ids.length + '</strong> zaznaczonych playlist?',
                        icon: 'question',
                        showCancelButton: true,
                        confirmButtonText: 'Aktywuj',
                        cancelButtonText: 'Anuluj',
                        confirmButtonColor: '#198754',
                        background: swalConfig.background,
                        color: swalConfig.color
                    }).then(function(result) {
                        if (result.isConfirmed) submitForm('activate', ids);
                    });
                    break;

                case 'deactivate':
                    Swal.fire({
                        title: 'Dezaktywacja playlist',
                        html: 'Czy dezaktywować <strong>' + ids.length + '</strong> zaznaczonych playlist?',
                        icon: 'question',
                        showCancelButton: true,
                        confirmButtonText: 'Dezaktywuj',
                        cancelButtonText: 'Anuluj',
                        background: swalConfig.background,
                        color: swalConfig.color,
                        cancelButtonColor: swalConfig.cancelButtonColor
                    }).then(function(result) {
                        if (result.isConfirmed) submitForm('deactivate', ids);
                    });
                    break;

                case 'touch':
                    Swal.fire({
                        title: 'Odświeżenie playlist',
                        html: 'Czy odświeżyć update_date dla <strong>' + ids.length + '</strong> zaznaczonych playlist?<br><br><small class="text-muted">Wymusi to ponowne pobranie playlist przez urządzenia.</small>',
                        icon: 'question',
                        showCancelButton: true,
                        confirmButtonText: 'Odśwież',
                        cancelButtonText: 'Anuluj',
                        confirmButtonColor: '#0dcaf0',
                        background: swalConfig.background,
                        color: swalConfig.color
                    }).then(function(result) {
                        if (result.isConfirmed) submitForm('touch', ids);
                    });
                    break;

                case 'copy':
                case 'move':
                    var isMove = action === 'move';
                    Swal.fire({
                        title: isMove ? 'Przenieś playlisty' : 'Kopiuj playlisty',
                        html: '<p><strong>' + ids.length + '</strong> playlist zostanie ' + (isMove ? 'przeniesionych' : 'skopiowanych') + '.</p>' +
                            '<div class="mb-3 text-start">' +
                            '<label class="form-label">Urządzenie docelowe</label>' +
                            '<select id="swal-device" class="form-select">' +
                            '<option value="">Wybierz urządzenie...</option>' +
                            deviceOptions +
                            '</select>' +
                            '</div>' +
                            '<small class="text-muted">Duplikaty zostaną pominięte. Nazwy będą automatycznie ponumerowane.</small>',
                        icon: 'question',
                        showCancelButton: true,
                        confirmButtonText: isMove ? 'Przenieś' : 'Kopiuj',
                        cancelButtonText: 'Anuluj',
                        confirmButtonColor: isMove ? '#ffc107' : '#0d6efd',
                        background: swalConfig.background,
                        color: swalConfig.color,
                        preConfirm: function() {
                            var deviceId = document.getElementById('swal-device').value;
                            if (!deviceId) {
                                Swal.showValidationMessage('Wybierz urządzenie docelowe');
                                return false;
                            }
                            return deviceId;
                        }
                    }).then(function(result) {
                        if (result.isConfirmed) {
                            submitForm(action, ids, { target_device_id: result.value });
                        }
                    });
                    break;
            }
        });
    });

    // Single toggle active button
    document.querySelectorAll('.toggle-active-btn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            var id = this.dataset.id;
            var name = this.dataset.name;
            var isActive = this.dataset.active === '1';
            var actionText = isActive ? 'dezaktywować' : 'aktywować';

            Swal.fire({
                title: (isActive ? 'Dezaktywacja' : 'Aktywacja') + ' playlisty',
                html: 'Czy ' + actionText + ' playlistę <strong>"' + name + '"</strong>?',
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: isActive ? 'Dezaktywuj' : 'Aktywuj',
                cancelButtonText: 'Anuluj',
                confirmButtonColor: isActive ? '#6c757d' : '#198754',
                background: swalConfig.background,
                color: swalConfig.color
            }).then(function(result) {
                if (result.isConfirmed) {
                    var form = document.createElement('form');
                    form.method = 'POST';
                    form.action = baseUrl + '/playlists/toggle-active';
                    form.innerHTML = '<input type="hidden" name="csrf_token" value="' + csrfToken + '"><input type="hidden" name="id" value="' + id + '">';
                    document.body.appendChild(form);
                    form.submit();
                }
            });
        });
    });

    // Single delete button
    document.querySelectorAll('.delete-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ąć playlistę <strong>"' + name + '"</strong>?',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Usuń',
                cancelButtonText: 'Anuluj',
                confirmButtonColor: '#dc3545',
                background: swalConfig.background,
                color: swalConfig.color
            }).then(function(result) {
                if (result.isConfirmed) {
                    var form = document.createElement('form');
                    form.method = 'POST';
                    form.action = baseUrl + '/playlists/delete';
                    form.innerHTML = '<input type="hidden" name="csrf_token" value="' + csrfToken + '"><input type="hidden" name="id" value="' + id + '">';
                    document.body.appendChild(form);
                    form.submit();
                }
            });
        });
    });
    
    // Filtruj urządzenia po wyborze użytkownika
    var userFilter = document.getElementById('userFilter');
    var deviceFilter = document.getElementById('deviceFilter');
    
    // Auto-submit przy zmianie filtrów (user_id, device_id)
    document.querySelectorAll('.auto-submit').forEach(function(el) {
        el.addEventListener('change', function() {
            // Przy zmianie użytkownika - resetuj urządzenie
            if (this.id === 'userFilter') {
                var deviceFilter = document.getElementById('deviceFilter');
                if (deviceFilter) {
                    deviceFilter.value = '';
                }
            }
            document.getElementById('filterForm').submit();
        });
    });
})();
</script>
{/literal}
{/block}
