{% extends "page.html" %}
{% block page_content %}
<style>
.tab-bar { display:flex; gap:0; margin-bottom:24px; border-bottom:2px solid var(--border); }
.tab-bar .tab { padding:10px 20px; cursor:pointer; border-bottom:2px solid transparent;
                margin-bottom:-2px; color:var(--text-muted); font-weight:500; }
.tab-bar .tab.active { color:var(--accent); border-bottom-color:var(--accent); }
.tab-content { display:none; }
.tab-content.active { display:block; }
.menu-group { margin-bottom:16px; }
.menu-group h4 { margin:0 0 8px; color:var(--text-muted); font-size:13px; text-transform:uppercase; }
.menu-item { display:flex; align-items:center; gap:8px; padding:8px 12px;
             border:1px solid var(--border); border-radius:6px; margin-bottom:4px; cursor:pointer; }
.menu-item:hover { background:var(--bg-secondary); }
.menu-item input[type="checkbox"] { width:18px; height:18px; cursor:pointer; }
.menu-item .label { flex:1; }
</style>
<div class="card">
    <div class="card-header"><h2>Настройка Ролей</h2></div>
    <div class="tab-bar">
        <div class="tab active" onclick="switchTab('engineer')">Инженер</div>
        <div class="tab" onclick="switchTab('technician')">Техник</div>
    </div>

    <div class="tab-content active" id="tab-engineer">
        <form id="role-form-engineer" class="menu-group">
            <p style="margin:0 0 12px;color:var(--text-muted);">Отметьте пункты меню, доступные инженеру:</p>
            <div id="menu-engineer"></div>
            <div class="form-actions" style="margin-top:16px;">
                <button type="submit" class="btn btn-primary">Сохранить</button>
            </div>
        </form>
    </div>

    <div class="tab-content" id="tab-technician">
        <form id="role-form-technician" class="menu-group">
            <p style="margin:0 0 12px;color:var(--text-muted);">Отметьте пункты меню, доступные технику:</p>
            <div id="menu-technician"></div>
            <div class="form-actions" style="margin-top:16px;">
                <button type="submit" class="btn btn-primary">Сохранить</button>
            </div>
        </form>
    </div>
</div>

<script>
var MENU_ITEMS = [];

function switchTab(name){
    document.querySelectorAll('.tab-content').forEach(function(t){ t.classList.remove('active'); });
    document.querySelectorAll('.tab').forEach(function(t){ t.classList.remove('active'); });
    document.getElementById('tab-' + name).classList.add('active');
    document.querySelector('.tab[onclick*="' + name + '"]').classList.add('active');
}

function loadPermissions(){
    Promise.all([
        fetch('/service/api/menu-items').then(function(r){ return r.json() }),
        fetch('/service/api/role-permissions').then(function(r){ return r.json() })
    ]).then(function(results){
        MENU_ITEMS = results[0];
        var data = results[1];
        ['engineer','technician'].forEach(function(role){
            var container = document.getElementById('menu-' + role);
            container.innerHTML = '';
            var permMap = {};
            (data[role] || []).forEach(function(p){ permMap[p.menu_key] = p.visible; });
            var currentSection = '';
            MENU_ITEMS.forEach(function(item){
                if(item.section !== currentSection){
                    currentSection = item.section;
                    var hdr = document.createElement('h4');
                    hdr.textContent = item.section;
                    container.appendChild(hdr);
                }
                var div = document.createElement('div');
                div.className = 'menu-item';
                var checked = permMap[item.key] !== false;
                div.innerHTML = '<input type="checkbox" name="' + item.key + '" ' + (checked?'checked':'') + '>' +
                    '<span class="label">' + item.label + '</span>';
                div.querySelector('input[type="checkbox"]').addEventListener('change', function(){
                    div.style.opacity = this.checked ? '1' : '0.5';
                });
                div.style.opacity = checked ? '1' : '0.5';
                container.appendChild(div);
            });
        });
    });
}

['engineer','technician'].forEach(function(role){
    document.getElementById('role-form-' + role).addEventListener('submit', function(e){
        e.preventDefault();
        var perms = [];
        this.querySelectorAll('input[type="checkbox"]').forEach(function(cb){
            perms.push({menu_key: cb.name, visible: cb.checked});
        });
        fetch('/service/api/role-permissions/save', {
            method: 'POST', headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({role: role, permissions: perms})
        }).then(function(r){ return r.json() }).then(function(d){
            if(d.ok) alert('Настройки роли "' + role + '" сохранены');
        });
    });
});

loadPermissions();
</script>
{% endblock %}