{% load static %}

<!-- ── USER CARD ─────────────────────────────────────────────── -->
<div class="sb-user">
    <div class="sb-user-avatar">{{ user.get_full_name|default:user.username|first|upper }}</div>
    <div style="min-width:0;">
        <div class="sb-user-name">{{ user.get_full_name|default:user.username }}</div>
        <div class="sb-user-role">
            {% if user.staff_profile.role %}{{ user.staff_profile.get_role_display }}
            {% elif user.is_superuser %}Administrator
            {% else %}Staff{% endif %}
        </div>
    </div>
</div>

<!-- ── EXPAND / COLLAPSE ALL ─────────────────────────────────── -->
<div class="sb-expand-bar">
    <button class="sb-expand-btn" onclick="sbExpandAll()"><i class="fas fa-angles-down"></i> Expand all</button>
    <span class="sb-expand-sep">·</span>
    <button class="sb-expand-btn" onclick="sbCollapseAll()"><i class="fas fa-angles-up"></i> Collapse all</button>
</div>

{# Context processor injects: user_role, is_management, is_teacher_role, is_bursar_role, is_head_role, is_support_only #}

<!-- ══════════════ MAIN ══════════════ -->
<div class="sb-section-header" data-target="sbg-main"><span class="sb-section-label">Main</span><i class="fas fa-chevron-right sb-section-chev"></i></div>
<div class="sb-section-body" id="sbg-main">
    {# School-wide dashboard: management only #}
    {% if user.is_superuser or is_management %}
    <a href="{% url 'staff:staff_dashboard' %}" class="sb-link"><i class="fas fa-th-large sb-icon"></i> Dashboard</a>
    {% endif %}
    {# My Dashboard: teachers + support staff (driver, canteen, security etc.) #}
    {% if user.is_superuser or is_teacher_role or is_support_only %}
    <a href="{% url 'staff:teacher_dashboard' %}" class="sb-link"><i class="fas fa-chalkboard-teacher sb-icon"></i> My Dashboard</a>
    {% endif %}
    {# Bursar shortcut on top #}
    {% if user.is_superuser or is_bursar_role %}
    <a href="{% url 'finance:bursar_dashboard' %}" class="sb-link"><i class="fas fa-cash-register sb-icon"></i> Bursar Dashboard</a>
    {% endif %}
</div>

<!-- ══════════════ STUDENTS ══════════════ -->
{# Support staff (driver/canteen) can see student list to check registrations & fee status #}
{% if user.is_superuser or is_management or is_teacher_role or is_support_only %}
<div class="sb-section-header" data-target="sbg-students"><span class="sb-section-label">Students</span><i class="fas fa-chevron-right sb-section-chev"></i></div>
<div class="sb-section-body" id="sbg-students">
    <a href="{% url 'students:student_list' %}" class="sb-link"><i class="fas fa-user-graduate sb-icon"></i> All Students</a>
    {# Add/manage students: admin and above only #}
    {% if user.is_superuser or user_role in "proprietor,head_master,head_mistress,admin,bursar" %}
    <a href="{% url 'students:student_add' %}" class="sb-link"><i class="fas fa-user-plus sb-icon"></i> Add Student</a>
    <a href="{% url 'students:parent_list' %}" class="sb-link"><i class="fas fa-users sb-icon"></i> Parents / Guardians</a>
    <button class="sb-group-toggle" onclick="toggleGroup('sb-import')" id="btn-sb-import">
        <i class="fas fa-file-import sb-icon"></i> Import / Export<i class="fas fa-chevron-right sb-chevron"></i>
    </button>
    <div class="sb-children" id="sb-import">
        <a href="{% url 'students:import_students_csv' %}" class="sb-link"><i class="fas fa-upload sb-icon"></i> Import CSV</a>
        <a href="{% url 'students:export_students' %}" class="sb-link"><i class="fas fa-download sb-icon"></i> Export CSV</a>
        <a href="{% url 'students:download_student_sample' %}" class="sb-link"><i class="fas fa-file-csv sb-icon"></i> Sample Template</a>
    </div>
    {% endif %}
</div>
{% endif %}

<!-- ══════════════ STAFF ══════════════ -->
<div class="sb-section-header" data-target="sbg-staff"><span class="sb-section-label">Staff</span><i class="fas fa-chevron-right sb-section-chev"></i></div>
<div class="sb-section-body" id="sbg-staff">
    {# Staff directory (contact info): everyone can see colleagues #}
    <a href="{% url 'staff:staff_list' %}" class="sb-link"><i class="fas fa-id-badge sb-icon"></i> Staff Directory</a>
    {# My own profile #}
    {% if user.staff_profile %}
    <a href="{% url 'staff:staff_detail' user.staff_profile.pk %}" class="sb-link"><i class="fas fa-user-circle sb-icon"></i> My Profile</a>
    {% endif %}
    {# Add / edit staff: admin+ only #}
    {% if user.is_superuser or user_role in "proprietor,head_master,head_mistress,admin" %}
    <a href="{% url 'staff:staff_add' %}" class="sb-link"><i class="fas fa-user-tie sb-icon"></i> Add Staff</a>
    {% endif %}
    {# Leave: everyone can request and view own leave #}
    <a href="{% url 'staff:leave_list' %}" class="sb-link"><i class="fas fa-calendar-minus sb-icon"></i> Leave Requests</a>
    <a href="{% url 'staff:leave_add' %}" class="sb-link"><i class="fas fa-calendar-plus sb-icon"></i> Request Leave</a>
    {# Staff attendance tracking: management only #}
    {% if user.is_superuser or is_management %}
    <a href="{% url 'staff:attendance_list' %}" class="sb-link"><i class="fas fa-user-clock sb-icon"></i> Staff Attendance</a>
    {% endif %}
</div>

<!-- ══════════════ ACADEMICS ══════════════ -->
{# Support staff (drivers, cleaners etc.) don't need the academics section #}
{% if user.is_superuser or is_management or is_teacher_role %}
<div class="sb-section-header" data-target="sbg-academics"><span class="sb-section-label">Academics</span><i class="fas fa-chevron-right sb-section-chev"></i></div>
<div class="sb-section-body" id="sbg-academics">
    <a href="{% url 'academics:class_list' %}" class="sb-link"><i class="fas fa-chalkboard sb-icon"></i> Classes</a>
    <a href="{% url 'academics:subject_list' %}" class="sb-link"><i class="fas fa-book-open sb-icon"></i> Subjects</a>
    <a href="{% url 'academics:rc-dashboard' %}" class="sidebar-link"><i class="fas fa-file-alt sb-icon"></i> Report Cards</a>
</div>
{% endif %}

<!-- ══════════════ ATTENDANCE ══════════════ -->
{# Support staff don't mark class attendance #}
{% if user.is_superuser or is_management or is_teacher_role %}
<div class="sb-section-header" data-target="sbg-attendance"><span class="sb-section-label">Attendance</span><i class="fas fa-chevron-right sb-section-chev"></i></div>
<div class="sb-section-body" id="sbg-attendance">
    {% if user.is_superuser or is_management %}
    <a href="{% url 'attendance:attendance_list' %}" class="sb-link"><i class="fas fa-list sb-icon"></i> Attendance List</a>
    {% endif %}
    <a href="{% url 'attendance:mark_attendance' %}" class="sb-link"><i class="fas fa-clipboard-check sb-icon"></i> Mark Attendance</a>
    {% if user.is_superuser or is_management %}
    <a href="{% url 'staff:mark_attendance' %}" class="sb-link"><i class="fas fa-user-check sb-icon"></i> Mark Staff Attendance</a>
    {% endif %}
    <a href="{% url 'reports:attendance_report' %}" class="sb-link"><i class="fas fa-chart-line sb-icon"></i> Attendance Report</a>
</div>
{% endif %}

<!-- ══════════════ FINANCE ══════════════ -->
{# Full finance panel: bursar and above only #}
{% if user.is_superuser or is_bursar_role %}
<div class="sb-section-header" data-target="sbg-finance"><span class="sb-section-label">Finance</span><i class="fas fa-chevron-right sb-section-chev"></i></div>
<div class="sb-section-body" id="sbg-finance">
    <a href="{% url 'finance:bursar_dashboard' %}" class="sb-link"><i class="fas fa-tachometer-alt sb-icon"></i> Bursar Dashboard</a>
    <a href="{% url 'finance:invoice_list' %}" class="sb-link"><i class="fas fa-file-invoice sb-icon"></i> Invoices</a>
    <a href="{% url 'finance:bulk_invoice' %}" class="sb-link"><i class="fas fa-bolt sb-icon"></i> Bulk Generate</a>
    <a href="{% url 'finance:payment_list' %}" class="sb-link"><i class="fas fa-money-bill-wave sb-icon"></i> Payments</a>
    <a href="{% url 'finance:fee_list' %}" class="sb-link"><i class="fas fa-tags sb-icon"></i> Fee Structures</a>
    <a href="{% url 'finance:school_item_list' %}" class="sb-link"><i class="fas fa-tshirt sb-icon"></i> Item Prices</a>
    <a href="{% url 'finance:enrollment_fee_list' %}" class="sb-link"><i class="fas fa-user-graduate sb-icon"></i> Enrollment Fees</a>
    <a href="{% url 'finance:expense_list' %}" class="sb-link"><i class="fas fa-receipt sb-icon"></i> Expenses</a>
    <a href="{% url 'finance:expense_categories' %}" class="sb-link"><i class="fas fa-tags sb-icon"></i> Expense Categories</a>
    <a href="{% url 'finance:discount_list' %}" class="sb-link"><i class="fas fa-percent sb-icon"></i> Discounts</a>
    <a href="{% url 'finance:financial_reports' %}" class="sb-link"><i class="fas fa-chart-bar sb-icon"></i> Financial Reports</a>
</div>
{% elif user_role in "proprietor,head_master,head_mistress,admin" %}
{# Head / admin: read-only finance overview, no management actions #}
<div class="sb-section-header" data-target="sbg-finance"><span class="sb-section-label">Finance</span><i class="fas fa-chevron-right sb-section-chev"></i></div>
<div class="sb-section-body" id="sbg-finance">
    <a href="{% url 'finance:invoice_list' %}" class="sb-link"><i class="fas fa-file-invoice sb-icon"></i> Invoices</a>
    <a href="{% url 'finance:payment_list' %}" class="sb-link"><i class="fas fa-money-bill-wave sb-icon"></i> Payments</a>
    <a href="{% url 'finance:fee_list' %}" class="sb-link"><i class="fas fa-tags sb-icon"></i> Fee Structures</a>
    <a href="{% url 'finance:financial_reports' %}" class="sb-link"><i class="fas fa-chart-bar sb-icon"></i> Financial Reports</a>
</div>
{% endif %}

<!-- ══════════════ COMMUNICATION ══════════════ -->
{# Announcements visible to everyone including support staff #}
<div class="sb-section-header" data-target="sbg-comms"><span class="sb-section-label">Communication</span><i class="fas fa-chevron-right sb-section-chev"></i></div>
<div class="sb-section-body" id="sbg-comms">
    <a href="{% url 'communication:announcement_list' %}" class="sb-link"><i class="fas fa-bullhorn sb-icon"></i> Announcements</a>
    {# SMS compose: teachers and above #}
    {% if user.is_superuser or is_management or is_teacher_role %}
    <a href="{% url 'communication:sms_compose' %}" class="sb-link"><i class="fas fa-comment-sms sb-icon"></i> Send SMS</a>
    {% endif %}
    {# SMS history and parent contacts: management only #}
    {% if user.is_superuser or is_management %}
    <a href="{% url 'communication:sms_list' %}" class="sb-link"><i class="fas fa-history sb-icon"></i> SMS History</a>
    <a href="{% url 'communication:parent_communication' %}" class="sb-link"><i class="fas fa-users sb-icon"></i> Parent Contacts</a>
    {% endif %}
</div>

<!-- ══════════════ REPORTS ══════════════ -->
{% if user.is_superuser or is_management or is_teacher_role %}
<div class="sb-section-header" data-target="sbg-reports"><span class="sb-section-label">Reports</span><i class="fas fa-chevron-right sb-section-chev"></i></div>
<div class="sb-section-body" id="sbg-reports">
    <a href="{% url 'reports:academic_report' %}" class="sb-link"><i class="fas fa-graduation-cap sb-icon"></i> Academic</a>
    <a href="{% url 'reports:attendance_report' %}" class="sb-link"><i class="fas fa-calendar-check sb-icon"></i> Attendance</a>
    {% if user.is_superuser or is_management %}
    <a href="{% url 'reports:financial_report' %}" class="sb-link"><i class="fas fa-file-invoice-dollar sb-icon"></i> Financial</a>
    <a href="{% url 'reports:custom_report' %}" class="sb-link"><i class="fas fa-sliders-h sb-icon"></i> Custom Report</a>
    {% endif %}
</div>
{% endif %}

<!-- ══════════════ ADMINISTRATION ══════════════ -->
{% if user.is_superuser or is_head_role %}
<div class="sb-section-header" data-target="sbg-admin"><span class="sb-section-label">Administration</span><i class="fas fa-chevron-right sb-section-chev"></i></div>
<div class="sb-section-body" id="sbg-admin">
    <a href="{% url 'admin:index' %}" class="sb-link"><i class="fas fa-shield-alt sb-icon"></i> Backend Admin</a>
</div>
{% endif %}

<!-- Sign Out -->
<div class="sb-logout">
    <form method="post" action="{% url 'staff:logout' %}" style="margin:0">
        {% csrf_token %}
        <button type="submit" class="sb-signout-btn">
            <i class="fas fa-sign-out-alt sb-icon"></i> Sign Out
        </button>
    </form>
</div>

<script>
const SB_SECTIONS=['sbg-main','sbg-students','sbg-staff','sbg-academics','sbg-attendance','sbg-finance','sbg-comms','sbg-reports','sbg-admin'];
const SB_KEY='rb-sb-v3';

function sbSave(){
    const s={};
    SB_SECTIONS.forEach(id=>{const el=document.getElementById(id);if(el)s[id]=el.classList.contains('open')?1:0;});
    try{sessionStorage.setItem(SB_KEY,JSON.stringify(s));}catch(e){}
}
function sbOpen(id,save=true){
    const el=document.getElementById(id),hdr=document.querySelector('[data-target="'+id+'"]');
    if(!el)return;
    el.classList.add('open');if(hdr)hdr.classList.add('open');
    if(save)sbSave();
}
function sbClose(id,save=true){
    const el=document.getElementById(id),hdr=document.querySelector('[data-target="'+id+'"]');
    if(!el)return;
    el.classList.remove('open');if(hdr)hdr.classList.remove('open');
    if(save)sbSave();
}
function sbToggle(id){const el=document.getElementById(id);if(el)el.classList.contains('open')?sbClose(id):sbOpen(id);}
function sbExpandAll(){SB_SECTIONS.forEach(id=>sbOpen(id,false));sbSave();}
function sbCollapseAll(){
    const active=document.querySelector('.sb-link.active');
    const keep=active?active.closest('.sb-section-body'):null;
    SB_SECTIONS.forEach(id=>{const el=document.getElementById(id);if(el&&el!==keep)sbClose(id,false);});
    sbSave();
}

document.querySelectorAll('.sb-section-header').forEach(h=>{
    h.addEventListener('click',()=>sbToggle(h.dataset.target));
});

const path=window.location.pathname;
document.querySelectorAll('.sb-link').forEach(a=>{
    const href=a.getAttribute('href');
    if(href&&href!=='/'&&path.startsWith(href)){
        a.classList.add('active');
        const sec=a.closest('.sb-section-body');
        if(sec)sbOpen(sec.id,false);
        const sub=a.closest('.sb-children');
        if(sub){sub.style.display='block';const btn=document.getElementById('btn-'+sub.id);if(btn)btn.classList.add('open');}
    }
});

try{
    const saved=JSON.parse(sessionStorage.getItem(SB_KEY)||'{}');
    SB_SECTIONS.forEach(id=>{
        const el=document.getElementById(id);
        if(!el||el.classList.contains('open'))return;
        if(saved[id]===1)sbOpen(id,false);
    });
}catch(e){}

function toggleGroup(id){
    const el=document.getElementById(id),btn=document.getElementById('btn-'+id);
    if(!el)return;
    const open=el.style.display==='block';
    el.style.display=open?'none':'block';
    if(btn){btn.classList.toggle('open',!open);const c=btn.querySelector('.sb-chevron');if(c)c.style.transform=open?'':'rotate(90deg)';}
    try{sessionStorage.setItem('sb-'+id,open?0:1);}catch(e){}
}
document.querySelectorAll('.sb-children').forEach(el=>{
    if(el.style.display==='block')return;
    try{if(sessionStorage.getItem('sb-'+el.id)==='1'){el.style.display='block';const btn=document.getElementById('btn-'+el.id);if(btn){btn.classList.add('open');const c=btn.querySelector('.sb-chevron');if(c)c.style.transform='rotate(90deg)';}}}catch(e){}
});

document.querySelectorAll('.sb-link').forEach(a=>{
    a.addEventListener('click',()=>{if(window.innerWidth<992)document.body.classList.remove('sidebar-open');});
});
</script>