{extends file="layout.tpl"}

{block name="content"}
<div class="container-fluid">
    <div class="row justify-content-center">
        <div class="col-lg-8">
            <!-- Header -->
            <div class="d-flex align-items-center mb-4">
                <a href="{$baseUrl}/settings/definitions" 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 $definition}Edytuj parametr: <code>{$definition.key}</code>{else}Dodaj nowy parametr dla urządzeń{/if}
                    </p>
                </div>
            </div>

            <form method="post" id="definitionForm">
                <div class="card">
                    <div class="card-body">
                        <input type="hidden" name="csrf_token" value="{$csrfToken}">

                        <div class="row g-3">
                            <!-- Klucz -->
                            <div class="col-md-6">
                                <label class="form-label">Klucz <span class="text-danger">*</span></label>
                                <input type="text" name="key" class="form-control font-monospace" 
                                       value="{$definition.key|default:''}" required
                                       pattern="[a-zA-Z][a-zA-Z0-9_]*"
                                       placeholder="np. isPlayerClockEnabled">
                                <div class="form-text">Nazwa parametru (camelCase, bez spacji)</div>
                            </div>

                            <!-- Typ -->
                            <div class="col-md-6">
                                <label class="form-label">Typ <span class="text-danger">*</span></label>
                                <select name="type" class="form-select" id="typeSelect" required>
                                    {foreach $typeLabels as $value => $label}
                                    <option value="{$value}" {if ($definition.type|default:'boolean') == $value}selected{/if}>
                                        {$label}
                                    </option>
                                    {/foreach}
                                </select>
                            </div>

                            <!-- Etykieta -->
                            <div class="col-12">
                                <label class="form-label">Etykieta <span class="text-danger">*</span></label>
                                <input type="text" name="label" class="form-control" 
                                       value="{$definition.label|default:''}" required
                                       placeholder="np. Włącz zegar w playerze">
                            </div>

                            <!-- Opis -->
                            <div class="col-12">
                                <label class="form-label">Opis</label>
                                <textarea name="description" class="form-control" rows="2"
                                          placeholder="Opcjonalny opis dla administratora">{$definition.description|default:''}</textarea>
                            </div>

                            <!-- Grupa -->
                            <div class="col-md-6">
                                <label class="form-label">Grupa</label>
                                <select name="group_name" class="form-select">
                                    {foreach $groupLabels as $value => $label}
                                    <option value="{$value}" {if ($definition.group_name|default:'general') == $value}selected{/if}>
                                        {$label}
                                    </option>
                                    {/foreach}
                                </select>
                            </div>

                            <!-- Min. poziom edycji -->
                            <div class="col-md-6">
                                <label class="form-label">Minimalny poziom edycji</label>
                                <select name="min_scope" class="form-select">
                                    {foreach $scopeLabels as $value => $label}
                                    <option value="{$value}" {if ($definition.min_scope|default:'device') == $value}selected{/if}>
                                        {$label}
                                    </option>
                                    {/foreach}
                                </select>
                                <div class="form-text">Kto może edytować to ustawienie</div>
                            </div>

                            <!-- Wartość domyślna -->
                            <div class="col-md-6">
                                <label class="form-label">Wartość domyślna</label>
                                <div id="defaultValueContainer">
                                    <!-- Dynamicznie wypełniane przez JS -->
                                </div>
                            </div>

                            <!-- Kolejność sortowania -->
                            <div class="col-md-6">
                                <label class="form-label">Kolejność sortowania</label>
                                <input type="number" name="sort_order" class="form-control" 
                                       value="{$definition.sort_order|default:0}" min="0">
                            </div>

                            <!-- Opcje (dla int/long) -->
                            <div class="col-12" id="optionsContainer" style="display:none;">
                                <label class="form-label">
                                    Opcje do wyboru
                                    <small class="text-muted">(tylko dla typów int/long - zostaw puste dla dowolnej wartości liczbowej)</small>
                                </label>
                                
                                <div id="optionsList" class="mb-2">
                                    <!-- Opcje dodawane dynamicznie -->
                                </div>
                                
                                <button type="button" class="btn btn-sm btn-outline-success" id="addOptionBtn">
                                    <i class="bi bi-plus-lg me-1"></i>Dodaj opcję
                                </button>
                                
                                <input type="hidden" name="options" id="optionsJson">
                            </div>

                            <!-- Aktywna -->
                            <div class="col-12">
                                <div class="form-check form-switch">
                                    <input type="checkbox" name="is_active" class="form-check-input" id="isActive" value="1"
                                           {if $definition.is_active|default:1}checked{/if}>
                                    <label class="form-check-label" for="isActive">Aktywna</label>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="card-footer d-flex justify-content-between">
                        <a href="{$baseUrl}/settings/definitions" class="btn btn-outline-secondary">Anuluj</a>
                        <button type="submit" class="btn btn-primary">
                            <i class="bi bi-check-lg me-1"></i>
                            {if $definition}Zapisz zmiany{else}Dodaj definicję{/if}
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
{/block}

{block name="scripts"}
<script>
var definition = {$definition|json_encode|default:'null'};
var currentOptions = {if $definition && $definition.options}{$definition.options|json_encode}{else}[]{/if};

document.addEventListener('DOMContentLoaded', function() {
    var typeSelect = document.getElementById('typeSelect');
    var defaultContainer = document.getElementById('defaultValueContainer');
    var optionsContainer = document.getElementById('optionsContainer');
    var optionsList = document.getElementById('optionsList');
    var addOptionBtn = document.getElementById('addOptionBtn');
    var optionsJson = document.getElementById('optionsJson');
    var form = document.getElementById('definitionForm');
    
    // Template dla opcji
    function createOptionRow(value, label) {
        var row = document.createElement('div');
        row.className = 'input-group mb-2 option-row';
        row.innerHTML = 
            '<span class="input-group-text">Wartość</span>' +
            '<input type="number" class="form-control option-value" value="' + (value || '') + '" placeholder="0" style="max-width:100px">' +
            '<span class="input-group-text">Etykieta</span>' +
            '<input type="text" class="form-control option-label" value="' + (label || '') + '" placeholder="np. Góra-lewo">' +
            '<button type="button" class="btn btn-outline-danger remove-option-btn"><i class="bi bi-trash"></i></button>';
        return row;
    }
    
    // Dodaj opcję
    addOptionBtn.addEventListener('click', function() {
        optionsList.appendChild(createOptionRow('', ''));
    });
    
    // Usuń opcję (delegacja)
    optionsList.addEventListener('click', function(e) {
        if (e.target.closest('.remove-option-btn')) {
            e.target.closest('.option-row').remove();
        }
    });
    
    // Załaduj istniejące opcje
    function loadOptions() {
        optionsList.innerHTML = '';
        if (currentOptions && currentOptions.length > 0) {
            currentOptions.forEach(function(opt) {
                optionsList.appendChild(createOptionRow(opt.value, opt.label));
            });
        }
    }
    
    // Zbierz opcje do JSON przed wysłaniem
    form.addEventListener('submit', function() {
        var options = [];
        document.querySelectorAll('.option-row').forEach(function(row) {
            var value = row.querySelector('.option-value').value;
            var label = row.querySelector('.option-label').value;
            if (value !== '' && label !== '') {
                options.push({
                    value: parseInt(value),
                    label: label
                });
            }
        });
        optionsJson.value = options.length > 0 ? JSON.stringify(options) : '';
    });
    
    function updateDefaultInput() {
        var type = typeSelect.value;
        var currentValue = definition ? definition.default_value : '';
        
        if (type === 'boolean') {
            defaultContainer.innerHTML = '<select name="default_value" class="form-select">' +
                '<option value="true"' + (currentValue === 'true' || currentValue === '1' ? ' selected' : '') + '>true (włączone)</option>' +
                '<option value="false"' + (currentValue === 'false' || currentValue === '0' || !currentValue ? ' selected' : '') + '>false (wyłączone)</option>' +
                '</select>';
            optionsContainer.style.display = 'none';
        } else if (type === 'string') {
            defaultContainer.innerHTML = '<input type="text" name="default_value" class="form-control" value="' + (currentValue || '') + '">';
            optionsContainer.style.display = 'none';
        } else {
            // int lub long
            defaultContainer.innerHTML = '<input type="number" name="default_value" class="form-control" value="' + (currentValue || '0') + '">';
            optionsContainer.style.display = 'block';
        }
    }
    
    typeSelect.addEventListener('change', function() {
        updateDefaultInput();
        // Wyczyść opcje przy zmianie typu
        if (typeSelect.value === 'boolean' || typeSelect.value === 'string') {
            optionsList.innerHTML = '';
        }
    });
    
    updateDefaultInput();
    loadOptions();
});
</script>
{/block}
