$(function(){loadRegions();loadItems();$('#searchBox').on('input',debounce(loadItems,300));$('#regionFilter').on('change',loadItems);$('#btnAdd').on('click',function(){clearForm();$('#modalTitle').text('Add City');$('#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 m=r.context&&r.context.match(/Region: (.+)/);var n=m?m[1]:'';var rg=_regions.find(function(r2){return r2.label===n;});$('#itemRegionId').val(rg?rg.id:'');$('#modalTitle').text('Edit City');new bootstrap.Modal(document.getElementById('itemModal')).show();});});var _cache=[],_regions=[];
function clearForm(){$('#itemId,#itemName').val('');$('#itemRegionId').val('');}
function loadRegions(){$.get('api/compliance.php?action=setup_options',function(r){if(r.status!=='success')return;_regions=r.data.regions||[];var h='<option value="">All regions</option>',h2='<option value="">Select region</option>';_regions.forEach(function(rg){h+='<option value="'+rg.id+'">'+esc(rg.label)+'</option>';h2+='<option value="'+rg.id+'">'+esc(rg.label)+'</option>';});$('#regionFilter').html(h);$('#itemRegionId').html(h2);},'json');}
function loadItems(){$.get('api/compliance.php',{action:'setup_list',setup_type:'cities',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="3" class="text-center py-4 text-muted">No cities</td></tr>';else data.forEach(function(x){html+='<tr><td class="fw-semibold">'+esc(x.name)+'</td><td>'+esc(x.context||'-')+'</td><td class="text-end"><div class="d-flex gap-1 justify-content-end"><button class="btn btn-sm btn-outline-primary btn-edit" data-id="'+x.id+'"><i class="bi bi-pencil"></i></button></div></td></tr>';});$('#tableBody').html(html);},'json');}
function saveItem(){var p={setup_type:'cities',name:$('#itemName').val().trim(),region_id:$('#itemRegionId').val(),csrf_token:window.CSRF_TOKEN};if(!p.name){showAlert('City 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('City 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);};}
