{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="mb-4">
                <h4 class="mb-1">Zmiana DNS</h4>
                <p class="text-muted mb-0">Masowa zamiana adresów URL w playlistach</p>
            </div>

            <!-- Info Card -->
            <div class="alert alert-info mb-4">
                <i class="bi bi-info-circle me-2"></i>
                <strong>Jak to działa?</strong><br>
                Wpisz stary adres (lub jego część) oraz nowy adres. System znajdzie wszystkie playlisty zawierające stary adres i zamieni go na nowy.
                <br><small class="text-muted">Przykład: zamiana <code>stary.serwer.pl</code> na <code>nowy.serwer.pl</code></small>
            </div>

            <!-- Form Card -->
            <div class="card">
                <div class="card-header">
                    <h5 class="card-title mb-0">
                        <i class="bi bi-arrow-repeat me-2"></i>Zamiana adresów
                    </h5>
                </div>
                <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" action="{$baseUrl}/dns/replace" id="dnsForm">
                        <input type="hidden" name="csrf_token" value="{$csrfToken}">
                        
                        {if $isAdmin}
                        <div class="mb-3">
                            <label class="form-label">Zakres zmiany</label>
                            <select name="target_user" class="form-select" id="targetUser">
                                <option value="self" {if ($target_user|default:'self') == 'self'}selected{/if}>Tylko moje playlisty</option>
                                <option value="all" {if ($target_user|default:'') == 'all'}selected{/if}>Wszyscy użytkownicy</option>
                                <optgroup label="Konkretny użytkownik">
                                    {foreach $users as $user}
                                    <option value="{$user.id}" {if ($target_user|default:'') == $user.id}selected{/if}>
                                        {$user.username} 
                                        {if $user.role == 'reseller'}
                                            ({$user.devices_count + $user.devices_allocated} urządzeń)
                                        {else}
                                            ({$user.devices_count} urządzeń)
                                        {/if}
                                    </option>
                                    {/foreach}
                                </optgroup>
                            </select>
                            <small class="text-muted">Wybierz czyje playlisty mają być zaktualizowane</small>
                        </div>
                        {/if}

                        <div class="mb-3">
                            <label class="form-label">Stary adres <span class="text-danger">*</span></label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="bi bi-link-45deg"></i></span>
                                <input type="text" 
                                       name="old_address" 
                                       class="form-control" 
                                       value="{$old_address|default:''}"
                                       placeholder="np. stary.serwer.pl"
                                       required>
                            </div>
                            <small class="text-muted">Adres lub fragment adresu do wyszukania</small>
                        </div>

                        <div class="mb-4">
                            <label class="form-label">Nowy adres <span class="text-danger">*</span></label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="bi bi-link"></i></span>
                                <input type="text" 
                                       name="new_address" 
                                       class="form-control" 
                                       value="{$new_address|default:''}"
                                       placeholder="np. nowy.serwer.pl"
                                       required>
                            </div>
                            <small class="text-muted">Nowy adres, który zastąpi stary</small>
                        </div>

                        <div class="d-grid gap-2">
                            <button type="submit" class="btn btn-primary btn-lg" id="submitBtn">
                                <i class="bi bi-arrow-repeat me-2"></i>Zamień adresy
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Info o polach -->
            <div class="card mt-4">
                <div class="card-header">
                    <h6 class="mb-0"><i class="bi bi-list-check me-2"></i>Pola objęte zamianą</h6>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-4">
                            <strong class="text-primary"><i class="bi bi-broadcast me-1"></i>Xtream</strong>
                            <ul class="small mb-0 mt-1">
                                <li>Host</li>
                            </ul>
                        </div>
                        <div class="col-md-4">
                            <strong class="text-success"><i class="bi bi-link-45deg me-1"></i>M3U</strong>
                            <ul class="small mb-0 mt-1">
                                <li>URL playlisty</li>
                                <li>EPG Link</li>
                            </ul>
                        </div>
                        <div class="col-md-4">
                            <strong class="text-warning"><i class="bi bi-hdd-network me-1"></i>Stalker</strong>
                            <ul class="small mb-0 mt-1">
                                <li>Server URL</li>
                                <li>Referrer URL</li>
                                <li>EPG Link</li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{/block}

{block name="scripts"}
<script>
{literal}
(function() {
    var STORAGE_KEY = 'dns_form_data';
    var oldAddrInput = document.querySelector('input[name="old_address"]');
    var newAddrInput = document.querySelector('input[name="new_address"]');
    var targetUserSelect = document.getElementById('targetUser');
    
    // Wczytaj zapisane dane z localStorage
    function loadSavedData() {
        try {
            var saved = localStorage.getItem(STORAGE_KEY);
            if (saved) {
                var data = JSON.parse(saved);
                
                // Wypełnij pola tylko jeśli są puste (nie nadpisuj wartości z serwera)
                if (oldAddrInput && !oldAddrInput.value && data.old_address) {
                    oldAddrInput.value = data.old_address;
                }
                if (newAddrInput && !newAddrInput.value && data.new_address) {
                    newAddrInput.value = data.new_address;
                }
                if (targetUserSelect && data.target_user) {
                    targetUserSelect.value = data.target_user;
                }
            }
        } catch (e) {
            console.error('Błąd wczytywania danych z localStorage:', e);
        }
    }
    
    // Zapisz dane do localStorage
    function saveData() {
        try {
            var data = {
                old_address: oldAddrInput ? oldAddrInput.value : '',
                new_address: newAddrInput ? newAddrInput.value : '',
                target_user: targetUserSelect ? targetUserSelect.value : 'self'
            };
            localStorage.setItem(STORAGE_KEY, JSON.stringify(data));
        } catch (e) {
            console.error('Błąd zapisywania do localStorage:', e);
        }
    }
    
    // Wyczyść localStorage po udanym wysłaniu
    function clearSavedData() {
        try {
            localStorage.removeItem(STORAGE_KEY);
        } catch (e) {
            console.error('Błąd czyszczenia localStorage:', e);
        }
    }
    
    // Wczytaj dane przy starcie
    loadSavedData();
    
    // Zapisuj przy każdej zmianie
    if (oldAddrInput) {
        oldAddrInput.addEventListener('input', saveData);
    }
    if (newAddrInput) {
        newAddrInput.addEventListener('input', saveData);
    }
    if (targetUserSelect) {
        targetUserSelect.addEventListener('change', saveData);
    }
    
    // SweetAlert config
    var swalConfig = {
        background: '#1a1d21',
        color: '#e1e1e1',
        confirmButtonColor: '#0d6efd',
        cancelButtonColor: '#6c757d'
    };
    
    // Obsługa formularza
    document.getElementById('dnsForm').addEventListener('submit', function(e) {
        e.preventDefault();
        
        var oldAddr = oldAddrInput.value.trim();
        var newAddr = newAddrInput.value.trim();
        var form = this;
        
        if (oldAddr === newAddr) {
            Swal.fire({
                title: 'Błąd',
                text: 'Stary i nowy adres nie mogą być identyczne.',
                icon: 'error',
                background: swalConfig.background,
                color: swalConfig.color
            });
            return;
        }
        {/literal}
        {if $isAdmin}
        {literal}
        var target = targetUserSelect.value;
        var confirmMsg = 'Czy na pewno chcesz zamienić adresy';
        var icon = 'question';
        
        if (target === 'all') {
            confirmMsg += ' we <strong>WSZYSTKICH</strong> playlistach wszystkich użytkowników?';
            icon = 'warning';
        } else if (target === 'self') {
            confirmMsg += ' w swoich playlistach?';
        } else {
            var userName = targetUserSelect.options[targetUserSelect.selectedIndex].text;
            confirmMsg += ' w playlistach użytkownika <strong>' + userName + '</strong>?';
        }
        
        Swal.fire({
            title: 'Potwierdź zmianę DNS',
            html: confirmMsg,
            icon: icon,
            showCancelButton: true,
            confirmButtonText: 'Zamień adresy',
            cancelButtonText: 'Anuluj',
            background: swalConfig.background,
            color: swalConfig.color,
            confirmButtonColor: swalConfig.confirmButtonColor,
            cancelButtonColor: swalConfig.cancelButtonColor
        }).then(function(result) {
            if (result.isConfirmed) {
                clearSavedData();
                document.getElementById('submitBtn').disabled = true;
                document.getElementById('submitBtn').innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Przetwarzanie...';
                form.submit();
            }
        });
        {/literal}
        {else}
        {literal}
        clearSavedData();
        document.getElementById('submitBtn').disabled = true;
        document.getElementById('submitBtn').innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Przetwarzanie...';
        form.submit();
        {/literal}
        {/if}
    {literal}
    });
})();
{/literal}
</script>
{/block}
