{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">Użytkownicy</h4>
            <p class="text-muted mb-0">
                {if $isReseller}Zarządzaj swoimi użytkownikami{else}Zarządzaj użytkownikami systemu{/if}
            </p>
        </div>
        <a href="{$baseUrl}/users/add" class="btn btn-primary">
            <i class="bi bi-plus-lg me-1"></i>Dodaj użytkownika
        </a>
    </div>

    {* Reseller - pokaż wykorzystanie limitów *}
    {if $isReseller && $resellerUsage}
    <div class="row mb-4">
        <div class="col-md-4">
            <div class="card bg-primary bg-opacity-10 border-primary">
                <div class="card-body py-3">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <small class="text-muted">Użytkownicy</small>
                            <h4 class="mb-0">{$resellerUsage.users.used} / {$resellerUsage.users.max}</h4>
                        </div>
                        <i class="bi bi-people text-primary" style="font-size: 2rem;"></i>
                    </div>
                    <div class="progress mt-2" style="height: 5px;">
                        <div class="progress-bar bg-primary" style="width: {if $resellerUsage.users.max > 0}{($resellerUsage.users.used / $resellerUsage.users.max * 100)|round}{else}0{/if}%"></div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card bg-success bg-opacity-10 border-success">
                <div class="card-body py-3">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <small class="text-muted">Urządzenia</small>
                            <h4 class="mb-0">{$resellerUsage.devices.used} / {$resellerUsage.devices.max}</h4>
                            <small class="text-muted">
                                własne: {$resellerUsage.devices.own}, 
                                przydzielone: {$resellerUsage.devices.allocated}
                                <br><span class="text-success">można dodać własnych: {$resellerUsage.devices.available_for_self}</span>
                            </small>
                        </div>
                        <i class="bi bi-tv text-success" style="font-size: 2rem;"></i>
                    </div>
                    <div class="progress mt-2" style="height: 5px;">
                        <div class="progress-bar bg-success" style="width: {if $resellerUsage.devices.max > 0}{($resellerUsage.devices.used / $resellerUsage.devices.max * 100)|round}{else}0{/if}%"></div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card bg-info bg-opacity-10 border-info">
                <div class="card-body py-3">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <small class="text-muted">Playlisty</small>
                            <h4 class="mb-0">{$resellerUsage.playlists.used} / {$resellerUsage.playlists.max}</h4>
                            <small class="text-muted">
                                własne: {$resellerUsage.playlists.own}, 
                                przydzielone: {$resellerUsage.playlists.allocated}
                                <br><span class="text-info">można dodać własnych: {$resellerUsage.playlists.available_for_self}</span>
                            </small>
                        </div>
                        <i class="bi bi-list-ul text-info" style="font-size: 2rem;"></i>
                    </div>
                    <div class="progress mt-2" style="height: 5px;">
                        <div class="progress-bar bg-info" style="width: {if $resellerUsage.playlists.max > 0}{($resellerUsage.playlists.used / $resellerUsage.playlists.max * 100)|round}{else}0{/if}%"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    {/if}

    <!-- Filters -->
    <div class="card mb-4">
        <div class="card-body">
            <form method="get" class="row g-3">
                <div class="col-md-8">
                    <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="Szukaj użytkownika..." value="{$search|default:''}">
                    </div>
                </div>
                <div class="col-md-4">
                    <button type="submit" class="btn btn-secondary w-100">
                        <i class="bi bi-filter me-1"></i>Filtruj
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Users 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>ID</th>
                            <th>Użytkownik</th>
                            <th>Rola</th>
                            {if $isAdmin}<th>Reseller</th>{/if}
                            <th>Urządzenia</th>
                            <th>Playlisty</th>
                            <th>Notatki</th>
                            <th>Status</th>
                            <th>Ostatnie logowanie</th>
                            <th class="text-end">Akcje</th>
                        </tr>
                    </thead>
                    <tbody>
                        {foreach $users as $user}
                        <tr>
                            <td><span class="text-muted">#{$user.id}</span></td>
                            <td>
                                <strong>{$user.username}</strong>
                            </td>
                            <td>
                                {if $user.role == 'admin'}
                                <span class="badge bg-danger"><i class="bi bi-shield-check me-1"></i>Admin</span>
                                {elseif $user.role == 'reseller'}
                                <span class="badge bg-primary"><i class="bi bi-shop me-1"></i>Reseller</span>
                                {else}
                                <span class="badge bg-secondary"><i class="bi bi-person me-1"></i>User</span>
                                {/if}
                            </td>
                            {if $isAdmin}
                            <td>
                                {if $user.parent_username}
                                <span class="text-muted">{$user.parent_username}</span>
                                {else}
                                <span class="text-muted">-</span>
                                {/if}
                            </td>
                            {/if}
                            <td>
                                {if $user.role == 'admin'}
                                <span class="badge bg-secondary">∞</span>
                                {elseif $user.role == 'reseller'}
                                {* Reseller: własne + przydzielone / pula *}
                                <span class="badge bg-info" title="własne: {$user.devices_count}, przydzielone: {$user.devices_allocated}">{$user.devices_count + $user.devices_allocated}/{$user.max_devices}</span>
                                {else}
                                <span class="badge bg-info">{$user.devices_count}/{$user.device_limit}</span>
                                {/if}
                            </td>
                            <td>
                                {if $user.role == 'admin'}
                                <span class="badge bg-secondary">∞</span>
                                {elseif $user.role == 'reseller'}
                                {* Reseller: własne + przydzielone / pula *}
                                <span class="badge bg-info" title="własne: {$user.playlists_count}, przydzielone: {$user.playlists_allocated}">{$user.playlists_count + $user.playlists_allocated}/{$user.max_playlists}</span>
                                {else}
                                <span class="badge bg-info">{$user.playlists_count|default:0}/{$user.playlist_limit|default:100}</span>
                                {/if}
                            </td>
                            <td>
                                <span class="badge bg-secondary notes-badge" 
                                      style="cursor:pointer;"
                                      data-entity-type="user" 
                                      data-entity-id="{$user.id}"
                                      onclick="NotesManager.open('user', {$user.id}, '{$user.username|escape:'javascript'}')"
                                      title="Pokaż notatki">
                                    <i class="bi bi-sticky"></i> <span class="notes-count">{$user.notes_count|default:0}</span>
                                </span>
                            </td>
                            <td>
                                {if $user.is_active}
                                <span class="badge bg-success">Aktywny</span>
                                {else}
                                <span class="badge bg-danger">Nieaktywny</span>
                                {/if}
                            </td>
                            <td>
                                {if $user.last_login}
                                {$user.last_login|date_format:"%d.%m.%Y %H:%M"}
                                {else}
                                <span class="text-muted">Nigdy</span>
                                {/if}
                            </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('user', {$user.id}, '{$user.username|escape:'javascript'}')">
                                        <i class="bi bi-sticky"></i>
                                    </button>
                                    <a href="{$baseUrl}/devices?user_id={$user.id}" class="btn btn-sm btn-outline-info" title="Urządzenia">
                                        <i class="bi bi-tv"></i>
                                    </a>
                                    <a href="{$baseUrl}/users/edit?id={$user.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-warning reset-password-btn" 
                                            title="Reset hasła"
                                            data-id="{$user.id}"
                                            data-username="{$user.username}">
                                        <i class="bi bi-key"></i>
                                    </button>
                                    {if $user.id != $currentUser.id}
                                    <button type="button" class="btn btn-sm btn-outline-danger delete-user-btn" 
                                            title="Usuń"
                                            data-id="{$user.id}"
                                            data-username="{$user.username}"
                                            data-role="{$user.role}">
                                        <i class="bi bi-trash"></i>
                                    </button>
                                    {/if}
                                </div>
                            </td>
                        </tr>
                        {foreachelse}
                        <tr>
                            <td colspan="{if $isAdmin}10{else}9{/if}" class="text-center py-5">
                                <div class="text-muted mb-3">
                                    <i class="bi bi-people" style="font-size: 3rem;"></i>
                                </div>
                                <p class="mb-0">Brak użytkowników</p>
                            </td>
                        </tr>
                        {/foreach}
                    </tbody>
                </table>
            </div>
        </div>

        {if $pagination.total_pages > 1}
        <div class="card-footer">
            <nav>
                <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}{if $search}&search={$search|escape}{/if}">
                            <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}{if $search}&search={$search|escape}{/if}">{$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}{if $search}&search={$search|escape}{/if}">
                            <i class="bi bi-chevron-right"></i>
                        </a>
                    </li>
                </ul>
            </nav>
        </div>
        {/if}
    </div>
</div>

<!-- Hidden forms -->
<form id="deleteUserForm" method="post" action="{$baseUrl}/users/delete" style="display:none;">
    <input type="hidden" name="csrf_token" value="{$csrfToken}">
    <input type="hidden" name="id" id="deleteUserId">
</form>
<form id="resetPasswordForm" method="post" action="{$baseUrl}/users/reset-password" style="display:none;">
    <input type="hidden" name="csrf_token" value="{$csrfToken}">
    <input type="hidden" name="id" id="resetUserId">
    <input type="hidden" name="new_password" id="resetPassword">
</form>
{/block}

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

    // Delete user
    document.querySelectorAll('.delete-user-btn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            var id = this.dataset.id;
            var username = this.dataset.username;
            var role = this.dataset.role;
            
            var warning = '';
            if (role === 'reseller') {
                warning = '<br><br><span class="text-warning"><i class="bi bi-exclamation-triangle me-1"></i>To jest reseller - zostaną usunięci również wszyscy jego użytkownicy!</span>';
            }

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

    // Reset password
    document.querySelectorAll('.reset-password-btn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            var id = this.dataset.id;
            var username = this.dataset.username;

            Swal.fire({
                title: 'Reset hasła',
                html: '<p>Resetujesz hasło dla użytkownika: <strong>' + username + '</strong></p>' +
                    '<div class="mb-3 text-start">' +
                    '<label class="form-label">Nowe hasło</label>' +
                    '<input type="password" id="swal-password" class="form-control" minlength="6" placeholder="Minimum 6 znaków">' +
                    '</div>',
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: 'Resetuj hasło',
                cancelButtonText: 'Anuluj',
                confirmButtonColor: '#ffc107',
                background: swalConfig.background,
                color: swalConfig.color,
                preConfirm: function() {
                    var password = document.getElementById('swal-password').value;
                    if (!password || password.length < 6) {
                        Swal.showValidationMessage('Hasło musi mieć minimum 6 znaków');
                        return false;
                    }
                    return password;
                }
            }).then(function(result) {
                if (result.isConfirmed) {
                    document.getElementById('resetUserId').value = id;
                    document.getElementById('resetPassword').value = result.value;
                    document.getElementById('resetPasswordForm').submit();
                }
            });
        });
    });
})();
</script>
{/literal}
{/block}
