{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}/devices" 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 urządzenia{else}Dodaj nowe urządzenie{/if}
                    </p>
                </div>
            </div>

            <!-- 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">
                        <input type="hidden" name="csrf_token" value="{$csrfToken}">
                        
                        {if $isAdmin && !$isEdit}
                        <div class="mb-3">
                            <label class="form-label">Użytkownik <span class="text-danger">*</span></label>
                            <select name="user_id" class="form-select" required>
                                <option value="">Wybierz użytkownika...</option>
                                {foreach $users as $user}
                                <option value="{$user.id}" {if ($data.user_id|default:0) == $user.id}selected{/if}>
                                    {$user.username}
                                    {if $user.role == 'reseller'}
                                        ({$user.devices_count + $user.devices_allocated}/{$user.max_devices} urządzeń)
                                    {elseif $user.role != 'admin'}
                                        ({$user.devices_count}/{$user.device_limit} urządzeń)
                                    {/if}
                                </option>
                                {/foreach}
                            </select>
                        </div>
                        {/if}

                        <div class="mb-3">
                            <label class="form-label">Nazwa urządzenia</label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="bi bi-tag"></i></span>
                                <input type="text" 
                                       name="name" 
                                       class="form-control" 
                                       value="{$data.name|default:''}"
                                       placeholder="np. Samsung TV Salon">
                            </div>
                            <small class="text-muted">Opcjonalna nazwa ułatwiająca identyfikację</small>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Adres MAC <span class="text-danger">*</span></label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="bi bi-ethernet"></i></span>
                                <input type="text" 
                                       name="mac" 
                                       class="form-control" 
                                       value="{$data.mac|default:''}"
                                       placeholder="00:1A:2B:3C:4D:5E"
                                       required>
                            </div>
                            <small class="text-muted">Format: XX:XX:XX:XX:XX:XX lub XXXXXXXXXXXX</small>
                        </div>

                        <div class="mb-4">
                            <label class="form-label">Kod dostępu <span class="text-danger">*</span></label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="bi bi-key"></i></span>
                                <input type="text" 
                                       name="code" 
                                       class="form-control" 
                                       value="{$data.code|default:''}"
                                       minlength="3"
                                       required>
                            </div>
                            <small class="text-muted">Kod wyświetlany na urządzeniu</small>
                        </div>

                        {if !$isEdit}
                        <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 urządzenia...">{$data.initial_note|default:''}</textarea>
                            </div>
                            <small class="text-muted">Zostanie zapisana jako notatka do tego urządzenia</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}Dodaj urządzenie{/if}
                            </button>
                            <a href="{$baseUrl}/devices" class="btn btn-secondary">Anuluj</a>
                        </div>
                    </form>
                </div>
            </div>

            {if $isEdit}
            <!-- Actions Card -->
            <div class="card mt-4">
                <div class="card-header">
                    <h6 class="mb-0"><i class="bi bi-lightning me-2"></i>Akcje</h6>
                </div>
                <div class="card-body">
                    <div class="d-grid gap-2">
                        <a href="{$baseUrl}/settings/device?id={$data.id}" class="btn btn-outline-primary">
                            <i class="bi bi-sliders me-2"></i>Ustawienia urządzenia
                        </a>
                        <a href="{$baseUrl}/playlists?device_id={$data.id}" class="btn btn-outline-info">
                            <i class="bi bi-collection-play me-2"></i>Playlisty ({$data.playlists_count|default:0})
                        </a>
                    </div>
                </div>
            </div>
            
            <!-- 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>
                        {if $isAdmin}
                        <div class="col-6 mt-3">
                            <small class="text-muted d-block">Właściciel</small>
                            <span>{$data.username}</span>
                        </div>
                        {/if}
                        <div class="col-6 mt-3">
                            <small class="text-muted d-block">Playlisty</small>
                            <a href="{$baseUrl}/playlists?device_id={$data.id}">{$data.playlists_count|default:0} playlist</a>
                        </div>
                    </div>
                </div>
            </div>
            
            {* Notatki *}
            <div class="mt-4">
                {include file="partials/entity_notes.tpl" entityType="device" entityId=$data.id}
            </div>
            {/if}
        </div>
    </div>
</div>
{/block}

{block name="scripts"}
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Formatowanie MAC address
    var macInput = document.querySelector('input[name="mac"]');
    if (macInput) {
        macInput.addEventListener('input', function(e) {
            // Usuń wszystko oprócz hex
            var value = this.value.replace(/[^0-9A-Fa-f]/g, '').toUpperCase();
            
            // Ogranicz do 12 znaków
            value = value.substring(0, 12);
            
            // Dodaj dwukropki co 2 znaki
            var formatted = '';
            for (var i = 0; i < value.length; i++) {
                if (i > 0 && i % 2 === 0) {
                    formatted += ':';
                }
                formatted += value[i];
            }
            
            this.value = formatted;
        });
        
        // Przy wklejaniu - od razu formatuj
        macInput.addEventListener('paste', function(e) {
            var self = this;
            setTimeout(function() {
                var value = self.value.replace(/[^0-9A-Fa-f]/g, '').toUpperCase();
                value = value.substring(0, 12);
                var formatted = '';
                for (var i = 0; i < value.length; i++) {
                    if (i > 0 && i % 2 === 0) {
                        formatted += ':';
                    }
                    formatted += value[i];
                }
                self.value = formatted;
            }, 0);
        });
    }
    
    // Kod urządzenia - zawsze duże litery
    var codeInput = document.querySelector('input[name="code"]');
    if (codeInput) {
        codeInput.addEventListener('input', function() {
            this.value = this.value.toUpperCase();
        });
    }
});
</script>
{/block}
