$(document).ready(function(){const y=document.getElementById("dashFilterMk"),_=document.getElementById("dashFilterAgronomis"),k=document.getElementById("dashFilterFA"),d=$("#date-range"),h=$("#sort-by"),w=$("#sort-dir"),M=$("#table-loading");let l={marketing_manager_id:["semua"],agronomist_id:["semua"],field_assistant_id:["semua"],start_date:moment().startOf("week").format("YYYY-MM-DD"),end_date:moment().endOf("week").format("YYYY-MM-DD"),sort_by:"check_in",sort_dir:"desc"};d.length&&d.daterangepicker({opens:"left",startDate:moment(l.start_date),endDate:moment(l.end_date),locale:{format:"DD/MM/YYYY"}});function m(e){e.on("item_add",function(t,r){t==="semua"?e.getValue().length>1&&e.setValue(["semua"],!0):e.getValue().includes("semua")&&e.removeItem("semua",!0)}),e.on("item_remove",function(t,r){e.getValue().length===0&&e.setValue(["semua"],!0)})}let a=null,n=null,o=null;y&&(a=new TomSelect(y,{placeholder:"Pilih Marketing Manager..."}),m(a)),_&&(n=new TomSelect(_,{placeholder:"Pilih Agronomis..."}),m(n)),k&&(o=new TomSelect(k,{placeholder:"Pilih Field Assistant..."}),m(o));function u(e,t,r="Semua"){e&&(e.clear(!0),e.clearOptions(),e.removeOption("semua"),e.addOption({value:"semua",text:r}),t.forEach(s=>{e.addOption({value:s.id,text:s.name})}),e.setValue(["semua"],!0),e.enable())}function f(e,t){return!t||t.length===0||t.length===1&&t[0]==="semua"?"":t.map(r=>`${e}[]=${encodeURIComponent(r)}`).join("&")}async function v(){if(a){a.disable(),a.clear(!0),a.clearOptions(),a.removeOption("semua"),a.addOption({value:"semua",text:"Memuat..."}),a.setValue(["semua"],!0);try{const t=await(await fetch(window.Laravel.routes.listMk)).json();t.success&&u(a,t.data)}catch(e){console.error("Error loading Marketing Managers:",e),u(a,[],"Semua"),a.enable()}}}async function g(e=["semua"]){if(n){n.disable(),n.clear(!0),n.clearOptions(),n.removeOption("semua"),n.addOption({value:"semua",text:"Memuat..."}),n.setValue(["semua"],!0);try{const t=f("marketing_manager_id",e),r=`${window.Laravel.routes.listAgronomis}${t?"?"+t:""}`,i=await(await fetch(r)).json();i.success&&u(n,i.data)}catch(t){console.error("Error loading Agronomists:",t),u(n,[],"Semua"),n.enable()}}}async function c(e=["semua"],t=["semua"]){if(o){o.disable(),o.clear(!0),o.clearOptions(),o.removeOption("semua"),o.addOption({value:"semua",text:"Memuat..."}),o.setValue(["semua"],!0);try{const r=f("marketing_manager_id",e),s=f("agronomist_id",t);let i=[r,s].filter(F=>F).join("&");const p=`${window.Laravel.routes.listFa}${i?"?"+i:""}`,b=await(await fetch(p)).json();b.success&&u(o,b.data)}catch(r){console.error("Error loading Field Assistants:",r),u(o,[],"Semua"),o.enable()}}}a&&a.on("change",function(){const e=a.getValue();g(e),c(e,["semua"])}),n&&n.on("change",function(){const e=a?a.getValue():["semua"],t=n.getValue();c(e,t)});function D(){M.css("display","flex")}function Y(){M.css("display","none")}let O=window.initCustomDataTable("#lap-table",{url:window.Laravel.routes.query,selectors:{pagingBtn:"#lap-pag-btns",pagingDetail:"#lap-pag-info"},columns:[{data:null,orderable:!1,render:function(e,t,r,s){const i=s.settings.json.pagination.current_page,p=s.settings.json.pagination.per_page;return(i-1)*p+s.row+1}},{data:null,orderable:!1,render:function(e,t,r,s){return`<div style="font-weight:500;color:var(--gray-900)">${r.user_name||"—"}</div>`}},{data:null,orderable:!1,render:function(e,t,r,s){return`<div>${V(r.user_role)}</div>`}},{data:null,orderable:!1,render:function(e,t,r,s){return`<div style="font-size:13px;color:var(--gray-700)">${r.check_in?moment(r.check_in).format("DD MMM YYYY, HH:mm"):"—"}</div>`}},{data:null,orderable:!1,render:function(e,t,r,s){return`<div style="font-size:13px;color:var(--gray-700)">${r.check_out?moment(r.check_out).format("DD MMM YYYY, HH:mm"):"—"}</div>`}}],extraData:function(e){for(const t in l)Array.isArray(l[t]),e[t]=l[t]},drawCallback:function(e){const t=e.json&&e.json.recordsFiltered?e.json.recordsFiltered:0;$("#lap-badge-count").text(`${t} data`)}});function V(e){return e?`<span class="role-badge ${e==="FA"?"role-fa":e==="Agronomis"?"role-agro":"role-mm"}">${e}</span>`:"—"}window.applyReportFilter=function(){D();const e=d.data("daterangepicker");l={marketing_manager_id:a?a.getValue():["semua"],agronomist_id:n?n.getValue():["semua"],field_assistant_id:o?o.getValue():["semua"],start_date:e.startDate.format("YYYY-MM-DD"),end_date:e.endDate.format("YYYY-MM-DD"),sort_by:h.val(),sort_dir:w.val()},O.ajax.reload(function(){Y()})},window.resetReportFilter=function(){a&&a.setValue(["semua"]),n&&n.setValue(["semua"]),o&&o.setValue(["semua"]);const e=moment().startOf("week"),t=moment().endOf("week");d.data("daterangepicker").setStartDate(e),d.data("daterangepicker").setEndDate(t),h.val("check_in"),w.val("desc"),a&&v(),n&&g(),o&&c(),applyReportFilter()},v(),g(),c(),Y()});
