{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">{$pageTitle}</h4>
            <p class="text-muted mb-0">
                {if $timestamp}
                Ostatnia modyfikacja: {$timestamp|date_format:"%d.%m.%Y %H:%M:%S"}
                {else}
                Brak zapisanych ustawień - używane są wartości domyślne
                {/if}
            </p>
        </div>
        <div class="d-flex gap-2">
            {if $scope == 'device' && isset($device)}
            <a href="{$baseUrl}/devices/edit?id={$device.id}" class="btn btn-outline-secondary">
                <i class="bi bi-arrow-left me-1"></i>Powrót do urządzenia
            </a>
            {elseif $scope == 'user' && isset($user)}
            <a href="{$baseUrl}/users/edit?id={$user.id}" class="btn btn-outline-secondary">
                <i class="bi bi-arrow-left me-1"></i>Powrót do użytkownika
            </a>
            {elseif $scope == 'reseller' && isset($reseller)}
            <a href="{$baseUrl}/users/edit?id={$reseller.id}" class="btn btn-outline-secondary">
                <i class="bi bi-arrow-left me-1"></i>Powrót do resellera
            </a>
            {/if}
        </div>
    </div>

    <form method="post">
        <input type="hidden" name="csrf_token" value="{$csrfToken}">
        <input type="hidden" name="action" value="save" id="formAction">

        <div class="row">
            <!-- Sidebar z akcjami -->
            <div class="col-lg-3">
                <!-- Presety -->
                {if $presets|count > 0}
                <div class="card mb-4">
                    <div class="card-header">
                        <h6 class="mb-0"><i class="bi bi-collection me-2"></i>Zastosuj preset</h6>
                    </div>
                    <div class="card-body">
                        <select class="form-select mb-2" id="presetSelect">
                            <option value="">Wybierz preset...</option>
                            {foreach $presets as $preset}
                            <option value="{$preset.id}">{$preset.name} ({$preset.items_count} ustawień)</option>
                            {/foreach}
                        </select>
                        <button type="button" class="btn btn-outline-primary w-100" id="applyPresetBtn" disabled>
                            <i class="bi bi-lightning me-1"></i>Zastosuj
                        </button>
                    </div>
                </div>
                {/if}

                <!-- Akcje -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h6 class="mb-0"><i class="bi bi-gear me-2"></i>Akcje</h6>
                    </div>
                    <div class="card-body d-grid gap-2">
                        <button type="submit" class="btn btn-primary">
                            <i class="bi bi-check-lg me-1"></i>Zapisz ustawienia
                        </button>
                        <button type="button" class="btn btn-outline-warning" id="resetBtn">
                            <i class="bi bi-arrow-counterclockwise me-1"></i>Resetuj do domyślnych
                        </button>
                    </div>
                </div>

                <!-- Info -->
                <div class="card bg-dark">
                    <div class="card-body">
                        <h6><i class="bi bi-info-circle me-2"></i>Informacje</h6>
                        <small class="text-muted">
                            {if $isMySettings|default:false}
                            Ustawienia które tu zmienisz będą stosowane do <strong>wszystkich Twoich urządzeń</strong>, chyba że urządzenie ma własne ustawienia.
                            {else}
                            Ustawienia na poziomie <strong>{$scopeLabel}</strong> nadpisują ustawienia z wyższych poziomów.
                            {/if}
                            <br><br>
                            <span class="badge bg-success">●</span> - wartość ustawiona<br>
                            <span class="badge bg-secondary">●</span> - wartość domyślna/dziedziczona
                        </small>
                    </div>
                </div>
            </div>

            <!-- Ustawienia -->
            <div class="col-lg-9">
                {foreach $grouped as $groupName => $groupDefs}
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="mb-0">
                            <i class="bi bi-folder me-2"></i>
                            {$groupLabels[$groupName]|default:$groupName}
                            <span class="badge bg-secondary ms-2">{count($groupDefs)}</span>
                        </h5>
                    </div>
                    <div class="card-body">
                        {foreach $groupDefs as $def}
                        <div class="row mb-3 pb-3 border-bottom align-items-center">
                            <div class="col-md-5">
                                <div class="d-flex align-items-center">
                                    {if $def.has_value}
                                    <span class="badge bg-success me-2" title="Wartość ustawiona">●</span>
                                    {else}
                                    <span class="badge bg-secondary me-2" title="Wartość domyślna">●</span>
                                    {/if}
                                    <div>
                                        <strong>{$def.label}</strong>
                                        <br><small class="text-muted"><code>{$def.key}</code></small>
                                        {if $def.description}
                                        <br><small class="text-muted">{$def.description}</small>
                                        {/if}
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-5">
                                {if $def.type == 'boolean'}
                                <div class="form-check form-switch">
                                    <input type="hidden" name="values[{$def.id}]" value="false">
                                    <input type="checkbox" name="values[{$def.id}]" class="form-check-input" 
                                           id="setting_{$def.id}" value="true"
                                           {if ($def.current_value|default:$def.default_value) == 'true' || ($def.current_value|default:$def.default_value) === true}checked{/if}>
                                    <label class="form-check-label" for="setting_{$def.id}">
                                        {if ($def.current_value|default:$def.default_value) == 'true' || ($def.current_value|default:$def.default_value) === true}Włączone{else}Wyłączone{/if}
                                    </label>
                                </div>
                                {elseif $def.options}
                                <select name="values[{$def.id}]" class="form-select">
                                    {foreach $def.options as $opt}
                                    <option value="{$opt.value}" {if ($def.current_value|default:$def.default_value) == $opt.value}selected{/if}>
                                        {$opt.label}
                                    </option>
                                    {/foreach}
                                </select>
                                {elseif $def.type == 'string'}
                                <input type="text" name="values[{$def.id}]" class="form-control"
                                       value="{$def.current_value|default:$def.default_value}">
                                {else}
                                <input type="number" name="values[{$def.id}]" class="form-control"
                                       value="{$def.current_value|default:$def.default_value}">
                                {/if}
                            </div>
                            <div class="col-md-2 text-end">
                                <small class="text-muted">
                                    <span class="badge bg-{if $def.type == 'boolean'}info{elseif $def.type == 'int'}primary{elseif $def.type == 'long'}warning{else}secondary{/if}">
                                        {$def.type}
                                    </span>
                                </small>
                            </div>
                        </div>
                        {/foreach}
                    </div>
                </div>
                {foreachelse}
                <div class="alert alert-info">
                    <i class="bi bi-info-circle me-2"></i>
                    Brak dostępnych ustawień dla tego poziomu.
                </div>
                {/foreach}
            </div>
        </div>
    </form>
</div>

<!-- Hidden form for preset -->
<form id="presetForm" method="post" style="display:none;">
    <input type="hidden" name="csrf_token" value="{$csrfToken}">
    <input type="hidden" name="action" value="apply_preset">
    <input type="hidden" name="preset_id" id="presetIdInput">
</form>

<!-- Hidden form for reset -->
<form id="resetForm" method="post" style="display:none;">
    <input type="hidden" name="csrf_token" value="{$csrfToken}">
    <input type="hidden" name="action" value="reset">
</form>
{/block}

{block name="scripts"}
{literal}
<script>
// Preset
var presetSelect = document.getElementById('presetSelect');
var applyPresetBtn = document.getElementById('applyPresetBtn');

if (presetSelect) {
    presetSelect.addEventListener('change', function() {
        applyPresetBtn.disabled = !this.value;
    });

    applyPresetBtn.addEventListener('click', function() {
        var presetId = presetSelect.value;
        if (!presetId) return;

        Swal.fire({
            title: 'Zastosować preset?',
            text: 'Obecne ustawienia zostaną nadpisane wartościami z presetu.',
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'Zastosuj',
            cancelButtonText: 'Anuluj',
            background: '#1a1d21',
            color: '#e1e1e1'
        }).then(function(result) {
            if (result.isConfirmed) {
                document.getElementById('presetIdInput').value = presetId;
                document.getElementById('presetForm').submit();
            }
        });
    });
}

// Reset
document.getElementById('resetBtn').addEventListener('click', function() {
    Swal.fire({
        title: 'Resetować ustawienia?',
        text: 'Wszystkie ustawienia na tym poziomie zostaną usunięte. Będą używane wartości z wyższych poziomów lub domyślne.',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Resetuj',
        cancelButtonText: 'Anuluj',
        confirmButtonColor: '#ffc107',
        background: '#1a1d21',
        color: '#e1e1e1'
    }).then(function(result) {
        if (result.isConfirmed) {
            document.getElementById('resetForm').submit();
        }
    });
});

// Update labels for switches
document.querySelectorAll('.form-check-input[type="checkbox"]').forEach(function(checkbox) {
    checkbox.addEventListener('change', function() {
        var label = this.nextElementSibling;
        if (label) {
            label.textContent = this.checked ? 'Włączone' : 'Wyłączone';
        }
    });
});
</script>
{/literal}
{/block}
