import{r as t}from"./vendor-react-CWq2BoMo.js";import{u as $,b as x,c as u}from"./vendor-query-BSpUEUJE.js";import{a4 as N}from"./Index-CsHtvMhJ.js";import{u as O}from"./usePhpSellerId-C6BnBLkv.js";import{J as c}from"./index-DVdSf46I.js";const I=[{name:"تلف",name_en:"Damage",type:"shortage",sort_order:1},{name:"سرقة",name_en:"Theft",type:"shortage",sort_order:2},{name:"خطأ في الإدخال",name_en:"Data Entry Error",type:"both",sort_order:3},{name:"انتهاء الصلاحية",name_en:"Expiry",type:"shortage",sort_order:4},{name:"إرجاع غير مسجل",name_en:"Unrecorded Return",type:"surplus",sort_order:5},{name:"استلام غير مسجل",name_en:"Unrecorded Receipt",type:"surplus",sort_order:6},{name:"تبخر/تجفف",name_en:"Evaporation/Drying",type:"shortage",sort_order:7},{name:"خطأ في العد السابق",name_en:"Previous Count Error",type:"both",sort_order:8},{name:"أخرى",name_en:"Other",type:"both",sort_order:99}],E="variance-reasons";function B(){const _=$(),{get:p,post:l}=N(),s=O(),R=e=>({...e,is_active:e.is_active===1||e.is_active==="1"||e.is_active===!0,sort_order:Number(e.sort_order)||0}),{data:o=[],isLoading:A,error:f,refetch:y}=x({queryKey:[E,s],queryFn:async()=>{if(!s)return[];const e=new URLSearchParams;e.append("action","get"),e.append("table","variance_reasons"),e.append("filters",JSON.stringify({seller_id:s})),e.append("orderBy","sort_order"),e.append("orderDir","ASC");const r=await p(`auto-crud.php?${e.toString()}`);return r.success&&Array.isArray(r.data)?r.data.map(R):[]},enabled:!!s,staleTime:6e4}),i=t.useCallback(()=>{_.invalidateQueries({queryKey:[E]})},[_]),S=t.useMemo(()=>o.filter(e=>e.is_active),[o]),h=u({mutationFn:async()=>{if(!s)return 0;const e=new URLSearchParams;e.append("action","get"),e.append("table","variance_reasons"),e.append("filters",JSON.stringify({seller_id:s}));const r=await p(`auto-crud.php?${e.toString()}`);if(r.success&&Array.isArray(r.data)&&r.data.length>0)return 0;let a=0;for(const n of I)try{(await l("auto-crud.php?action=create&table=variance_reasons",{id:crypto.randomUUID(),seller_id:s,...n,is_active:1})).success&&a++}catch(d){console.error("Error creating default reason:",d)}return a},onSuccess:e=>{e>0&&(c.success(`تم إنشاء ${e} سبب افتراضي`),i())}}),v=u({mutationFn:async e=>{if(!s)throw new Error("لم يتم تحديد البائع");const r=o.reduce((d,P)=>Math.max(d,P.sort_order),0),a={id:crypto.randomUUID(),seller_id:s,name:e.name,name_en:e.name_en||null,description:e.description||null,type:e.type||"both",is_active:1,sort_order:e.sort_order||r+1},n=await l("auto-crud.php?action=create&table=variance_reasons",a);if(!n.success)throw new Error(n.message||"فشل في الإنشاء");return n.data},onSuccess:()=>{c.success("تم إنشاء السبب بنجاح"),i()},onError:e=>{c.error(e.message||"فشل في إنشاء السبب")}}),g=u({mutationFn:async({id:e,updates:r})=>{const a={...r};r.is_active!==void 0&&(a.is_active=r.is_active?1:0);const n=await l(`auto-crud.php?action=update&table=variance_reasons&id=${e}`,a);if(!n.success)throw new Error("فشل في التحديث");return n.data},onSuccess:()=>{c.success("تم تحديث السبب"),i()},onError:e=>{c.error(e.message||"فشل في التحديث")}}),w=u({mutationFn:async e=>{const r=await p(`auto-crud.php?action=delete&table=variance_reasons&id=${e}`);if(!r.success)throw new Error("فشل في الحذف");return r.data},onSuccess:()=>{c.success("تم حذف السبب"),i()},onError:e=>{c.error(e.message||"فشل في الحذف")}}),b=u({mutationFn:async e=>{let r=!0;for(let a=0;a<e.length;a++)(await l(`auto-crud.php?action=update&table=variance_reasons&id=${e[a]}`,{sort_order:a+1})).success||(r=!1);if(!r)throw new Error("فشل في إعادة الترتيب");return r},onSuccess:()=>{i()}}),C=t.useCallback(async()=>{try{return await h.mutateAsync()}catch{return 0}},[h]),k=t.useCallback(async e=>{try{return await v.mutateAsync(e)}catch{return null}},[v]),m=t.useCallback(async(e,r)=>{try{return await g.mutateAsync({id:e,updates:r}),!0}catch{return!1}},[g]),D=t.useCallback(async e=>{try{return await w.mutateAsync(e),!0}catch{return!1}},[w]),U=t.useCallback(async e=>{const r=o.find(a=>a.id===e);return r?m(e,{is_active:!r.is_active}):!1},[o,m]),M=t.useCallback(async e=>{try{return await b.mutateAsync(e),!0}catch{return!1}},[b]),F=t.useCallback(e=>o.filter(r=>r.is_active&&(r.type===e||r.type==="both")),[o]),q=t.useCallback(async()=>{await y()},[y]);return{reasons:o,activeReasons:S,isLoading:A,error:f?f.message:null,fetchReasons:q,initializeDefaultReasons:C,createReason:k,updateReason:m,deleteReason:D,toggleActive:U,reorderReasons:M,getReasonsByType:F,refetch:y,invalidateReasons:i}}export{B as u};
