{extends file="layout.tpl"}

{block name="content"}
<div class="container-fluid">
    <div class="row justify-content-center">
        <div class="col-lg-6">
            <!-- Header -->
            <div class="d-flex align-items-center mb-4">
                <a href="{$baseUrl}/users" class="btn btn-outline-secondary me-3">
                    <i class="bi bi-arrow-left"></i>
                </a>
                <div>
                    <h4 class="mb-1">{$pageTitle}</h4>
                    <p class="text-muted mb-0">
                        {if $isEdit}Edytuj dane użytkownika{else}Utwórz nowe konto użytkownika{/if}
                    </p>
                </div>
            </div>

            {* Reseller - pokaż dostępne limity *}
            {if $isReseller && $availableLimits}
            <div class="alert alert-info mb-4">
                <i class="bi bi-info-circle me-2"></i>
                <strong>Dostępne limity:</strong>
                Użytkownicy: {$availableLimits.users}, 
                Urządzenia: {$availableLimits.devices}, 
                Playlisty: {$availableLimits.playlists}
            </div>
            {/if}

            <!-- Form Card -->
            <div class="card">
                <div class="card-body">
                    {if $error|default:false}
                    <div class="alert alert-danger">
                        <i class="bi bi-exclamation-circle me-2"></i>{$error}
                    </div>
                    {/if}

                    <form method="post" autocomplete="off">
                        <input type="hidden" name="csrf_token" value="{$csrfToken}">
                        
                        <div class="mb-3">
                            <label class="form-label">Nazwa użytkownika <span class="text-danger">*</span></label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="bi bi-person"></i></span>
                                {if $isEdit}
                                <input type="text" 
                                       name="new_account_login" 
                                       id="newAccountLogin"
                                       class="form-control" 
                                       value="{$data.username|default:''}"
                                       autocomplete="off"
                                       data-lpignore="true"
                                       data-form-type="other"
                                       readonly>
                                {else}
                                <input type="text" 
                                       name="new_account_login" 
                                       id="newAccountLogin"
                                       class="form-control" 
                                       value="{$data.username|default:''}"
                                       pattern="[a-zA-Z0-9_-]+"
                                       minlength="3"
                                       autocomplete="off"
                                       data-lpignore="true"
                                       data-form-type="other"
                                       required>
                                {/if}
                            </div>
                            <small class="text-muted">Tylko litery, cyfry, _ i - (min. 3 znaki)</small>
                        </div>

                        {if !$isEdit}
                        <div class="mb-3">
                            <label class="form-label">Hasło <span class="text-danger">*</span></label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="bi bi-lock"></i></span>
                                <input type="text" 
                                       name="new_account_secret" 
                                       id="newAccountSecret"
                                       class="form-control" 
                                       minlength="6"
                                       autocomplete="off"
                                       data-lpignore="true"
                                       data-form-type="other"
                                       required>
                                <button type="button" class="btn btn-outline-secondary" id="generatePasswordBtn" title="Generuj hasło">
                                    <i class="bi bi-magic"></i>
                                </button>
                            </div>
                            <small class="text-muted">Minimum 6 znaków</small>
                        </div>
                        {else}
                        <div class="mb-3">
                            <label class="form-label">Nowe hasło <span class="text-muted">(opcjonalne)</span></label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="bi bi-lock"></i></span>
                                <input type="text" 
                                       name="new_account_secret" 
                                       id="newAccountSecret"
                                       class="form-control" 
                                       autocomplete="off"
                                       data-lpignore="true"
                                       data-form-type="other"
                                       placeholder="Pozostaw puste aby nie zmieniać">
                                <button type="button" class="btn btn-outline-secondary" id="generatePasswordBtn" title="Generuj hasło">
                                    <i class="bi bi-magic"></i>
                                </button>
                            </div>
                            <small class="text-muted">Wypełnij tylko jeśli chcesz zmienić hasło (min. 6 znaków)</small>
                        </div>
                        {/if}

                        {* Rola - tylko dla admina *}
                        {if $isAdmin}
                        <div class="mb-3">
                            <label class="form-label">Rola</label>
                            <select name="role" class="form-select" id="roleSelect">
                                <option value="user" {if ($data.role|default:'user') == 'user'}selected{/if}>Użytkownik</option>
                                <option value="reseller" {if ($data.role|default:'') == 'reseller'}selected{/if}>Reseller</option>
                                <option value="admin" {if ($data.role|default:'') == 'admin'}selected{/if}>Administrator</option>
                            </select>
                        </div>

                        {* Przypisanie do resellera - tylko dla userów *}
                        <div class="mb-3" id="parentIdGroup">
                            <label class="form-label">Przypisz do resellera</label>
                            <select name="parent_id" class="form-select">
                                <option value="">-- Bezpośrednio do admina --</option>
                                {foreach $resellers as $reseller}
                                <option value="{$reseller.id}" {if ($data.parent_id|default:0) == $reseller.id}selected{/if}>
                                    {$reseller.username} (użytk: {$reseller.users_count}/{$reseller.max_users})
                                </option>
                                {/foreach}
                            </select>
                            <small class="text-muted">Opcjonalne - możesz przypisać użytkownika do resellera</small>
                        </div>
                        {/if}

                        {* Limity dla resellera - tylko admin przy tworzeniu/edycji resellera *}
                        {if $isAdmin}
                        <div id="resellerLimitsGroup" style="display: none;">
                            <hr>
                            <h6 class="text-muted mb-3"><i class="bi bi-sliders me-2"></i>Pula resellera (do rozdysponowania)</h6>
                            
                            <div class="row">
                                <div class="col-md-4 mb-3">
                                    <label class="form-label">Max użytkowników</label>
                                    <input type="number" 
                                           name="max_users" 
                                           id="maxUsers"
                                           class="form-control" 
                                           value="{$data.max_users|default:10}"
                                           min="0"
                                           max="9999"
                                           disabled>
                                    <small class="text-muted">Ilu userów może stworzyć</small>
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label class="form-label">Pula urządzeń</label>
                                    <input type="number" 
                                           name="max_devices" 
                                           id="maxDevices"
                                           class="form-control" 
                                           value="{$data.max_devices|default:50}"
                                           min="1"
                                           max="99999"
                                           disabled>
                                    <small class="text-muted">Własne + do rozdania</small>
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label class="form-label">Pula playlist</label>
                                    <input type="number" 
                                           name="max_playlists" 
                                           id="maxPlaylists"
                                           class="form-control" 
                                           value="{$data.max_playlists|default:200}"
                                           min="1"
                                           max="99999"
                                           disabled>
                                    <small class="text-muted">Własne + do rozdania</small>
                                </div>
                            </div>
                            <hr>
                        </div>
                        {/if}

                        {* Limity użytkownika - tylko dla roli USER (ukryte dla admin/reseller) *}
                        <div class="row" id="userLimitsGroup" style="{if $data.role|default:'user' != 'user'}display:none{else}display:flex{/if}">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Limit urządzeń</label>
                                <div class="input-group">
                                    <span class="input-group-text"><i class="bi bi-tv"></i></span>
                                    <input type="number" 
                                           name="device_limit" 
                                           class="form-control" 
                                           value="{$data.device_limit|default:3}"
                                           min="1"
                                           max="{if $availableLimits}{$availableLimits.devices}{else}999{/if}">
                                </div>
                                {if $availableLimits}
                                <small class="text-muted">Dostępne: {$availableLimits.devices}</small>
                                {/if}
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Limit playlist</label>
                                <div class="input-group">
                                    <span class="input-group-text"><i class="bi bi-list-ul"></i></span>
                                    <input type="number" 
                                           name="playlist_limit" 
                                           class="form-control" 
                                           value="{$data.playlist_limit|default:100}"
                                           min="1"
                                           max="{if $availableLimits}{$availableLimits.playlists}{else}9999{/if}">
                                </div>
                                {if $availableLimits}
                                <small class="text-muted">Dostępne: {$availableLimits.playlists}</small>
                                {/if}
                            </div>
                        </div>

                        {if $isEdit}
                        <div class="mb-4">
                            <div class="form-check form-switch">
                                <input type="checkbox" 
                                       name="is_active" 
                                       id="is_active" 
                                       class="form-check-input"
                                       value="1"
                                       {if $data.is_active|default:1}checked{/if}>
                                <label class="form-check-label" for="is_active">Konto aktywne</label>
                            </div>
                        </div>
                        {else}
                        <div class="mb-4">
                            <label class="form-label">Uwagi <span class="text-muted">(opcjonalne)</span></label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="bi bi-sticky"></i></span>
                                <textarea name="initial_note" 
                                          class="form-control" 
                                          rows="2" 
                                          placeholder="Notatka dodana przy tworzeniu użytkownika...">{$data.initial_note|default:''}</textarea>
                            </div>
                            <small class="text-muted">Zostanie zapisana jako notatka do tego użytkownika</small>
                        </div>
                        {/if}

                        <div class="d-flex gap-2">
                            <button type="submit" class="btn btn-primary">
                                <i class="bi bi-check-lg me-1"></i>
                                {if $isEdit}Zapisz zmiany{else}Utwórz użytkownika{/if}
                            </button>
                            <a href="{$baseUrl}/users" class="btn btn-secondary">Anuluj</a>
                        </div>
                    </form>
                </div>
            </div>

            {if $isEdit}
            <!-- Info Card -->
            <div class="card mt-4">
                <div class="card-header">
                    <h6 class="mb-0"><i class="bi bi-info-circle me-2"></i>Informacje</h6>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-6">
                            <small class="text-muted d-block">Utworzony</small>
                            <span>{$data.created_at|date_format:"%d.%m.%Y %H:%M"}</span>
                        </div>
                        <div class="col-6">
                            <small class="text-muted d-block">Ostatnia aktualizacja</small>
                            <span>{$data.updated_at|date_format:"%d.%m.%Y %H:%M"}</span>
                        </div>
                        <div class="col-6 mt-3">
                            <small class="text-muted d-block">Ostatnie logowanie</small>
                            <span>
                                {if $data.last_login}
                                {$data.last_login|date_format:"%d.%m.%Y %H:%M"}
                                {else}
                                Nigdy
                                {/if}
                            </span>
                        </div>
                        <div class="col-6 mt-3">
                            <small class="text-muted d-block">Liczba urządzeń</small>
                            <span>{$data.devices_count|default:0}</span>
                        </div>
                        {if $data.parent_username}
                        <div class="col-6 mt-3">
                            <small class="text-muted d-block">Przypisany do</small>
                            <span>{$data.parent_username}</span>
                        </div>
                        {/if}
                    </div>
                </div>
            </div>
            
            {* Notatki - tylko dla admina/resellera i nie dla siebie *}
            {if ($isAdmin || $isReseller) && $data.id != $currentUser.id}
            <div class="mt-4">
                {include file="partials/entity_notes.tpl" entityType="user" entityId=$data.id}
            </div>
            {/if}
            {/if}
        </div>
    </div>
</div>
{/block}

{block name="scripts"}
<script>
// Generator haseł
(function() {
    var passwordSettings = {$passwordSettings|default:'{"length":12,"lowercase":true,"uppercase":true,"numbers":true,"symbols":false}'};
    var generateBtn = document.getElementById('generatePasswordBtn');
    var passwordField = document.getElementById('newAccountSecret');
    
    function generatePassword() {
        var chars = '';
        var required = [];
        
        if (passwordSettings.lowercase) {
            var lowercase = 'abcdefghijklmnopqrstuvwxyz';
            chars += lowercase;
            required.push(lowercase.charAt(Math.floor(Math.random() * lowercase.length)));
        }
        
        if (passwordSettings.uppercase) {
            var uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
            chars += uppercase;
            required.push(uppercase.charAt(Math.floor(Math.random() * uppercase.length)));
        }
        
        if (passwordSettings.numbers) {
            var numbers = '0123456789';
            chars += numbers;
            required.push(numbers.charAt(Math.floor(Math.random() * numbers.length)));
        }
        
        if (passwordSettings.symbols) {
            var symbols = '!@#$%^&*()_+-=[]{}|;:,.<>?';
            chars += symbols;
            required.push(symbols.charAt(Math.floor(Math.random() * symbols.length)));
        }
        
        if (!chars) {
            chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        }
        
        var password = required.join('');
        var length = passwordSettings.length || 12;
        
        while (password.length < length) {
            password += chars.charAt(Math.floor(Math.random() * chars.length));
        }
        
        // Shuffle
        password = password.split('').sort(function() { return 0.5 - Math.random(); }).join('');
        
        return password;
    }
    
    if (generateBtn && passwordField) {
        generateBtn.addEventListener('click', function() {
            passwordField.value = generatePassword();
            passwordField.select();
        });
    }
})();

{if $isAdmin}
// Role switcher dla admina
(function() {
    var roleSelect = document.getElementById('roleSelect');
    var resellerLimitsGroup = document.getElementById('resellerLimitsGroup');
    var parentIdGroup = document.getElementById('parentIdGroup');
    var userLimitsGroup = document.getElementById('userLimitsGroup');
    var maxUsers = document.getElementById('maxUsers');
    var maxDevices = document.getElementById('maxDevices');
    var maxPlaylists = document.getElementById('maxPlaylists');

    function updateFormFields() {
        var role = roleSelect.value;
        
        if (role === 'reseller') {
            resellerLimitsGroup.style.display = 'block';
            parentIdGroup.style.display = 'none';
            userLimitsGroup.style.display = 'none';
            // Włącz pola resellera
            if (maxUsers) maxUsers.disabled = false;
            if (maxDevices) maxDevices.disabled = false;
            if (maxPlaylists) maxPlaylists.disabled = false;
        } else if (role === 'admin') {
            resellerLimitsGroup.style.display = 'none';
            parentIdGroup.style.display = 'none';
            userLimitsGroup.style.display = 'none';
            // Wyłącz pola resellera
            if (maxUsers) maxUsers.disabled = true;
            if (maxDevices) maxDevices.disabled = true;
            if (maxPlaylists) maxPlaylists.disabled = true;
        } else {
            resellerLimitsGroup.style.display = 'none';
            parentIdGroup.style.display = 'block';
            userLimitsGroup.style.display = 'flex';
            // Wyłącz pola resellera
            if (maxUsers) maxUsers.disabled = true;
            if (maxDevices) maxDevices.disabled = true;
            if (maxPlaylists) maxPlaylists.disabled = true;
        }
    }

    if (roleSelect) {
        roleSelect.addEventListener('change', updateFormFields);
        updateFormFields();
    }
})();
{/if}
</script>
{/block}
