$(function(){loadOptions();loadItems();$('#searchBox').on('input',debounce(loadItems,300));$('#btnAdd').on('click',function(){clearForm();$('#modalTitle').text('Add Office');$('#itemId').val(0);new bootstrap.Modal(document.getElementById('itemModal')).show();});$('#btnSave').on('click',saveItem);$(document).on('click','.btn-edit',function(){var r=_cache.find(function(x){return String(x.id)===String($(this).data('id'));});if(!r)return;$('#itemId').val(r.id);$('#itemName').val(r.name);});});var _cache=[];
function clearForm(){$('#itemId,#itemName').val('');$('#itemAuthorityId,#itemStateId,#itemLgaId').val('');}
function loadOptions(){$.get('api/compliance.php?action=setup_options',function(r){if(r.status!=='success')return;var auth=r.data.authorities||[],st=r.data.states||[],lg=r.data.lgas||[];var ha='<option value="">Select authority</option>',hs='<option value="">Select state</option>',hl='<option value="">Select LGA</option>';auth.forEach(function(a){ha+='<option value="'+a.id+'">'+esc(a.label)+'</option>';});st.forEach(function(s){hs+='<option value="'+s.id+'">'+esc(s.label)+'</option>';});lg.forEach(function(l){hl+='<option value="'+l.id+'">'+esc(l.label)+'</option>';});$('#itemAuthorityId').html(ha);$('#itemStateId').html(hs);$('#itemLgaId').html(hl);},'json');}
function loadItems(){$.get('api/compliance.php',{action:'setup_list',setup_type:'offices',search:$('#searchBox').val()},function(r){if(r.status!=='success')return;var data=r.data||[];_cache=data;$('#kpiTotal').text(data.length);var html='';if(!data.length)html='<tr><td colspan="5" class="text-center py-4 text-muted">No offices</td></tr>';else data.forEach(function(x){html+='<tr><td class="fw-semibold">'+esc(x.name)+'</td><td>'+esc(x.context||'-')+'</td><td>-</td><td>-</td><td class="text-end"><button class="btn btn-sm btn-outline-primary btn-edit" data-id="'+x.id+'"><i class="bi bi-pencil"></i></button></td></tr>';});$('#tableBody').html(html);},'json');}
function saveItem(){var p={setup_type:'offices',name:$('#itemName').val().trim(),authority_id:$('#itemAuthorityId').val(),office_state_id:$('#itemStateId').val(),office_lga_id:$('#itemLgaId').val(),csrf_token:window.CSRF_TOKEN};if(!p.name){showAlert('Office name is required','danger');return;}$.post('api/compliance.php?action=save_setup_item',p,function(r){if(r.status!=='success'){showAlert(r.message,'danger');return;}bootstrap.Modal.getInstance(document.getElementById('itemModal')).hide();loadItems();showAlert('Office saved!','success');},'json').fail(function(){showAlert('Server error','danger');});}
function showAlert(msg,type){var box=$('#alertBox');box.removeClass('d-none alert-success alert-danger alert-warning alert-info').addClass('alert-'+type).text(msg);setTimeout(function(){box.addClass('d-none');},5000);}
function esc(t){return $('<div>').text(t||'').html();}
function debounce(fn,ms){var t;return function(){var c=this,a=arguments;clearTimeout(t);t=setTimeout(function(){fn.apply(c,a);},ms);};}
