(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,11241,e=>{"use strict";let a=(0,e.i(56420).default)("arrow-left",[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]]);e.s(["ArrowLeft",0,a],11241)},83353,e=>{"use strict";var a=e.i(18566),t=e.i(2169);e.s(["useAppRouter",0,function(){let e=(0,a.useRouter)(),{startLoading:o}=(0,t.useLoader)();return{...e,push:(a,t)=>{console.log("[Loader] Navigation started:",a),o&&o(),e.push(a,t)},replace:(a,t)=>{console.log("[Loader] Navigation started:",a),o&&o(),e.replace(a,t)}}}])},12498,e=>{"use strict";var a=e.i(65464);let t=new class{async fetchCoupons(e){let{data:t,error:o}=await a.supabase.from("coupons").select("*").eq("vendor_id",e).order("created_at",{ascending:!1});if(o)throw console.error("Error fetching coupons:",o),o;return t||[]}async fetchCouponDetails(e){let{data:t,error:o}=await a.supabase.from("coupons").select("*").eq("id",e).single();if(o)throw o;let s=[],l=[];if("category"===t.apply_type){let{data:t}=await a.supabase.from("coupon_categories").select(`
          category_id,
          categories (
            name
          )
        `).eq("coupon_id",e);s=t||[]}else if("product"===t.apply_type){let{data:t}=await a.supabase.from("coupon_products").select(`
          product_id,
          products (
            product_name
          )
        `).eq("coupon_id",e);l=t||[]}return{...t,selectedCategories:s,selectedProducts:l}}async createCoupon(e,t){let{data:o,error:s}=await a.supabase.from("coupons").insert([e]).select().single();if(s){if("23505"===s.code)throw Error("This coupon code has already been created. Please try a different code or generate a new one.");throw s}let l=o.id;if("category"===e.apply_type&&t.categories?.length>0){let e=t.categories.map(e=>({coupon_id:l,category_id:e}));await a.supabase.from("coupon_categories").insert(e)}else if("product"===e.apply_type&&t.products?.length>0){let e=t.products.map(e=>({coupon_id:l,product_id:e}));await a.supabase.from("coupon_products").insert(e)}return o}async updateCouponStatus(e,t){let{data:o,error:s}=await a.supabase.from("coupons").update({is_active:t}).eq("id",e).select().single();if(s)throw s;return o}async deleteCoupon(e){let{error:t}=await a.supabase.from("coupons").delete().eq("id",e);if(t)throw t;return!0}async fetchVendorProducts(e){let{data:t,error:o}=await a.supabase.from("products").select("id, product_name, category_id").eq("vendor_id",e).order("product_name");return o?(console.warn("Failed to fetch products:",o.message),[]):t||[]}async fetchCategories(){let{data:e,error:t}=await a.supabase.from("categories").select("id, name").order("name");return t?(console.warn("Failed to fetch categories:",t.message),[]):e||[]}async validateCoupon(e,t,o){let{subtotal:s,products:l}=t,{data:r,error:i}=await a.supabase.from("coupons").select("*").eq("code",e).single();if(i||!r)return{isValid:!1,error:"Invalid coupon code"};if(!r.is_active)return{isValid:!1,error:"This coupon is no longer active"};let n=new Date;if(new Date(r.start_date)>n)return{isValid:!1,error:"This coupon is not yet valid"};if(new Date(r.end_date)<n)return{isValid:!1,error:"This coupon has expired"};if(r.usage_limit>0&&r.used_count>=r.usage_limit)return{isValid:!1,error:"Coupon usage limit has been reached"};if(o){let{count:e}=await a.supabase.from("coupon_usages").select("*",{count:"exact",head:!0}).eq("coupon_id",r.id).eq("user_id",o);if(e>=r.per_user_limit)return{isValid:!1,error:"You have reached your usage limit for this coupon"}}if(r.min_order_amount&&s<r.min_order_amount)return{isValid:!1,error:`Minimum order amount is ₹${r.min_order_amount}`};let d=!1,c=0;if("all"===r.apply_type)c=s,d=!0;else if("category"===r.apply_type){let{data:e}=await a.supabase.from("coupon_categories").select("category_id").eq("coupon_id",r.id),t=e.map(e=>e.category_id);for(let e of l)t.includes(e.category_id)&&(c+=e.price*e.quantity,d=!0)}else if("product"===r.apply_type){let{data:e}=await a.supabase.from("coupon_products").select("product_id").eq("coupon_id",r.id),t=e.map(e=>e.product_id);for(let e of l)t.includes(e.id)&&(c+=e.price*e.quantity,d=!0)}if(!d)return{isValid:!1,error:"Your cart does not contain any items eligible for this coupon."};let u=0;return"percentage"===r.type?(u=c*(r.value/100),r.max_discount&&u>r.max_discount&&(u=r.max_discount)):"fixed"===r.type&&(u=r.value),u=Math.min(u,c),{isValid:!0,couponId:r.id,discountAmount:u}}};e.s(["couponsRepository",0,t])},86682,e=>{e.v({actionLink:"coupons-module__6TITaa__actionLink",actionLinks:"coupons-module__6TITaa__actionLinks",actionsBar:"coupons-module__6TITaa__actionsBar",analyticsCard:"coupons-module__6TITaa__analyticsCard",analyticsGrid:"coupons-module__6TITaa__analyticsGrid",cardTitle:"coupons-module__6TITaa__cardTitle",cardValue:"coupons-module__6TITaa__cardValue",container:"coupons-module__6TITaa__container",deleteLink:"coupons-module__6TITaa__deleteLink",errorText:"coupons-module__6TITaa__errorText",formControl:"coupons-module__6TITaa__formControl",formGrid:"coupons-module__6TITaa__formGrid",formGroup:"coupons-module__6TITaa__formGroup",formLabel:"coupons-module__6TITaa__formLabel",formSection:"coupons-module__6TITaa__formSection",header:"coupons-module__6TITaa__header",inputAddon:"coupons-module__6TITaa__inputAddon",inputWithAddon:"coupons-module__6TITaa__inputWithAddon",pageButton:"coupons-module__6TITaa__pageButton",pageControls:"coupons-module__6TITaa__pageControls",pagination:"coupons-module__6TITaa__pagination",primaryButton:"coupons-module__6TITaa__primaryButton",searchInput:"coupons-module__6TITaa__searchInput",secondaryButton:"coupons-module__6TITaa__secondaryButton",sectionTitle:"coupons-module__6TITaa__sectionTitle",selectInput:"coupons-module__6TITaa__selectInput",statusActive:"coupons-module__6TITaa__statusActive",statusBadge:"coupons-module__6TITaa__statusBadge",statusExpired:"coupons-module__6TITaa__statusExpired",statusInactive:"coupons-module__6TITaa__statusInactive",table:"coupons-module__6TITaa__table",tableContainer:"coupons-module__6TITaa__tableContainer",title:"coupons-module__6TITaa__title"})},59533,e=>{"use strict";var a=e.i(43476),t=e.i(71645),o=e.i(11241);let s=(0,e.i(56420).default)("refresh-cw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]);var l=e.i(83353),r=e.i(12498),i=e.i(65464),n=e.i(86682);e.s(["default",0,function(){let e=(0,l.useAppRouter)(),[d,c]=(0,t.useState)(!1);(0,t.useEffect)(()=>{c(!0)},[]);let{formData:u,scopeData:p,categories:m,products:_,loading:f,error:h,categoryScope:y,setCategoryScope:g,handleInputChange:x,handleScopeChange:v,generateCode:j,submitForm:T}=function(){let e=(0,l.useAppRouter)(),[a,o]=(0,t.useState)(!1),[s,n]=(0,t.useState)(null),[d,c]=(0,t.useState)([]),[u,p]=(0,t.useState)([]),[m,_]=(0,t.useState)({code:"",discount_type:"percentage",discount_value:"",min_order_amount:"",max_discount:"",usage_limit:"0",per_user_limit:"1",apply_type:"all",start_date:"",end_date:"",is_active:!0}),[f,h]=(0,t.useState)({categories:[],products:[]}),[y,g]=(0,t.useState)("all");(0,t.useEffect)(()=>{v(),x()},[]);let x=async()=>{try{let{data:{user:e}}=await i.supabase.auth.getUser();if(!e)return;let{data:a}=await i.supabase.from("vendor_profiles").select("id").eq("user_id",e.id).single();if(!a)return;let[t,o]=await Promise.all([r.couponsRepository.fetchCategories(),r.couponsRepository.fetchVendorProducts(a.id)]);c(t),p(o)}catch(e){console.error("Failed to load dependencies",e)}},v=()=>{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",a="UZH-";for(let t=0;t<8;t++)a+=e.charAt(Math.floor(Math.random()*e.length));_(e=>({...e,code:a}))},j=async a=>{a.preventDefault(),n(null);let t=(()=>{if(!m.code)return"Coupon code is required";if(!m.discount_value||0>=Number(m.discount_value))return"Invalid discount value";if(!m.start_date||!m.end_date)return"Please select start and end dates";if(new Date(m.end_date)<=new Date(m.start_date))return"End date must be greater than start date";if("category"===m.apply_type){if(0===f.categories.length)return"Please select at least one category";if("specific"===y&&0===f.products.length)return"Please select at least one product"}return null})();if(t)return void n(t);try{o(!0);let{data:{user:a}}=await i.supabase.auth.getUser();if(!a)throw Error("Not authenticated");let{data:t}=await i.supabase.from("vendor_profiles").select("id").eq("user_id",a.id).single();if(!t)throw Error("Vendor profile not found");let s={code:m.code,type:m.discount_type,value:parseFloat(m.discount_value),min_order_amount:m.min_order_amount?parseFloat(m.min_order_amount):0,max_discount:m.max_discount?parseFloat(m.max_discount):null,usage_limit:parseInt(m.usage_limit,10),per_user_limit:parseInt(m.per_user_limit,10),apply_type:"category"===m.apply_type&&"specific"===y?"product":m.apply_type,start_date:new Date(m.start_date).toISOString(),end_date:new Date(m.end_date).toISOString(),is_active:m.is_active,used_count:0,vendor_id:t.id};await r.couponsRepository.createCoupon(s,f),e.push("/coupons")}catch(e){console.warn("Failed to create coupon:",e.message),n(e.message||"Failed to create coupon")}finally{o(!1)}};return{formData:m,scopeData:f,categories:d,products:u,loading:a,error:s,categoryScope:y,setCategoryScope:g,handleInputChange:e=>{let{name:a,value:t,type:o,checked:s}=e.target,l="checkbox"===o?s:t;"code"===a&&(l=l.toUpperCase()),_(e=>({...e,[a]:l}))},handleScopeChange:(e,a)=>{h(t=>({...t,[e]:a}))},generateCode:v,submitForm:j}}(),b=_.filter(e=>p.categories.includes(e.category_id));return d?(0,a.jsxs)("div",{className:n.default.container,children:[(0,a.jsx)("div",{className:n.default.header,children:(0,a.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:16},children:[(0,a.jsx)("button",{className:n.default.secondaryButton,style:{padding:"8px"},onClick:()=>e.push("/coupons"),children:(0,a.jsx)(o.ArrowLeft,{size:18})}),(0,a.jsxs)("div",{children:[(0,a.jsx)("h1",{className:n.default.title,children:"Create Coupon"}),(0,a.jsx)("p",{style:{color:"var(--color-text-secondary)",marginTop:"4px"},children:"Create a new promotional discount for your customers."})]})]})}),h&&(0,a.jsx)("div",{className:n.default.errorText,children:h}),(0,a.jsxs)("form",{onSubmit:T,children:[(0,a.jsxs)("div",{className:n.default.formSection,children:[(0,a.jsx)("h2",{className:n.default.sectionTitle,children:"Basic Information"}),(0,a.jsxs)("div",{className:n.default.formGrid,children:[(0,a.jsxs)("div",{className:n.default.formGroup,children:[(0,a.jsx)("label",{className:n.default.formLabel,children:"Coupon Code"}),(0,a.jsxs)("div",{style:{display:"flex",gap:8},children:[(0,a.jsx)("input",{type:"text",name:"code",className:n.default.formControl,style:{flex:1},value:u.code,onChange:x,required:!0}),(0,a.jsx)("button",{type:"button",className:n.default.secondaryButton,onClick:j,children:(0,a.jsx)(s,{size:16})})]})]}),(0,a.jsxs)("div",{className:n.default.formGroup,children:[(0,a.jsx)("label",{className:n.default.formLabel,children:"Discount Type"}),(0,a.jsxs)("select",{name:"discount_type",className:n.default.formControl,value:u.discount_type,onChange:x,children:[(0,a.jsx)("option",{value:"percentage",children:"Percentage (%)"}),(0,a.jsx)("option",{value:"fixed",children:"Fixed Amount (₹)"})]})]}),(0,a.jsxs)("div",{className:n.default.formGroup,children:[(0,a.jsx)("label",{className:n.default.formLabel,children:"Discount Value"}),(0,a.jsxs)("div",{className:n.default.inputWithAddon,children:[(0,a.jsx)("span",{className:n.default.inputAddon,children:"percentage"===u.discount_type?"%":"₹"}),(0,a.jsx)("input",{type:"number",name:"discount_value",className:n.default.formControl,value:u.discount_value,onChange:x,min:"0",step:"0.01",required:!0})]})]}),"percentage"===u.discount_type&&(0,a.jsxs)("div",{className:n.default.formGroup,children:[(0,a.jsx)("label",{className:n.default.formLabel,children:"Maximum Discount Amount (Optional)"}),(0,a.jsxs)("div",{className:n.default.inputWithAddon,children:[(0,a.jsx)("span",{className:n.default.inputAddon,children:"₹"}),(0,a.jsx)("input",{type:"number",name:"max_discount",className:n.default.formControl,value:u.max_discount,onChange:x,min:"0"})]})]}),(0,a.jsxs)("div",{className:n.default.formGroup,children:[(0,a.jsx)("label",{className:n.default.formLabel,children:"Minimum Order Amount (Optional)"}),(0,a.jsxs)("div",{className:n.default.inputWithAddon,children:[(0,a.jsx)("span",{className:n.default.inputAddon,children:"₹"}),(0,a.jsx)("input",{type:"number",name:"min_order_amount",className:n.default.formControl,value:u.min_order_amount,onChange:x,min:"0"})]})]}),(0,a.jsxs)("div",{className:n.default.formGroup,children:[(0,a.jsx)("label",{className:n.default.formLabel,children:"Total Usage Limit"}),(0,a.jsx)("input",{type:"number",name:"usage_limit",className:n.default.formControl,value:u.usage_limit,onChange:x,min:"0"}),(0,a.jsx)("span",{style:{fontSize:12,color:"var(--color-text-secondary)"},children:"Set to 0 for unlimited uses."})]}),(0,a.jsxs)("div",{className:n.default.formGroup,children:[(0,a.jsx)("label",{className:n.default.formLabel,children:"Per User Limit"}),(0,a.jsx)("input",{type:"number",name:"per_user_limit",className:n.default.formControl,value:u.per_user_limit,onChange:x,min:"1"})]})]})]}),(0,a.jsxs)("div",{className:n.default.formSection,children:[(0,a.jsx)("h2",{className:n.default.sectionTitle,children:"Coupon Scope"}),(0,a.jsxs)("div",{className:n.default.formGroup,style:{marginBottom:24},children:[(0,a.jsx)("label",{className:n.default.formLabel,children:"Apply To"}),(0,a.jsxs)("div",{style:{display:"flex",gap:16},children:[(0,a.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[(0,a.jsx)("input",{type:"radio",name:"apply_type",value:"all",checked:"all"===u.apply_type,onChange:x}),"Entire Store"]}),(0,a.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[(0,a.jsx)("input",{type:"radio",name:"apply_type",value:"category",checked:"category"===u.apply_type,onChange:x}),"Specific Categories"]})]})]}),"category"===u.apply_type&&(0,a.jsxs)("div",{className:n.default.formGroup,children:[(0,a.jsx)("label",{className:n.default.formLabel,children:"Select Categories"}),(0,a.jsx)("div",{className:n.default.formControl,style:{height:"150px",overflowY:"auto",padding:"12px"},children:(0,a.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:m.map(e=>(0,a.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[(0,a.jsx)("input",{type:"checkbox",checked:p.categories.includes(e.id),onChange:a=>{if(a.target.checked)v("categories",[...p.categories,e.id]);else{v("categories",p.categories.filter(a=>a!==e.id));let a=_.filter(a=>a.category_id===e.id).map(e=>e.id);a.length>0&&v("products",p.products.filter(e=>!a.includes(e)))}},style:{width:"16px",height:"16px"}}),e.name]},e.id))})}),p.categories.length>0&&(0,a.jsxs)("div",{style:{marginTop:24},children:[(0,a.jsx)("label",{className:n.default.formLabel,children:"Scope within selected categories"}),(0,a.jsxs)("div",{style:{display:"flex",gap:16,marginBottom:16},children:[(0,a.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[(0,a.jsx)("input",{type:"radio",name:"category_scope",value:"all",checked:"all"===y,onChange:e=>g(e.target.value)}),"All products in selected categories"]}),(0,a.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[(0,a.jsx)("input",{type:"radio",name:"category_scope",value:"specific",checked:"specific"===y,onChange:e=>g(e.target.value)}),"Specific products in selected categories"]})]}),"specific"===y&&(0,a.jsxs)("div",{className:n.default.formGroup,children:[(0,a.jsx)("label",{className:n.default.formLabel,children:"Select Products"}),(0,a.jsx)("div",{className:n.default.formControl,style:{height:"200px",overflowY:"auto",padding:"12px"},children:b.length>0?(0,a.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:b.map(e=>(0,a.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[(0,a.jsx)("input",{type:"checkbox",checked:p.products.includes(e.id),onChange:a=>{a.target.checked?v("products",[...p.products,e.id]):v("products",p.products.filter(a=>a!==e.id))},style:{width:"16px",height:"16px"}}),e.product_name||e.name]},e.id))}):(0,a.jsx)("span",{style:{color:"var(--color-text-secondary)"},children:"No products found in selected categories"})})]})]})]})]}),(0,a.jsxs)("div",{className:n.default.formSection,children:[(0,a.jsx)("h2",{className:n.default.sectionTitle,children:"Schedule"}),(0,a.jsxs)("div",{className:n.default.formGrid,children:[(0,a.jsxs)("div",{className:n.default.formGroup,children:[(0,a.jsx)("label",{className:n.default.formLabel,children:"Start Date"}),(0,a.jsx)("input",{type:"datetime-local",name:"start_date",className:n.default.formControl,value:u.start_date,onChange:x,required:!0})]}),(0,a.jsxs)("div",{className:n.default.formGroup,children:[(0,a.jsx)("label",{className:n.default.formLabel,children:"End Date"}),(0,a.jsx)("input",{type:"datetime-local",name:"end_date",className:n.default.formControl,value:u.end_date,onChange:x,required:!0})]})]})]}),(0,a.jsxs)("div",{className:n.default.formSection,children:[(0,a.jsx)("h2",{className:n.default.sectionTitle,children:"Status"}),(0,a.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:12,cursor:"pointer"},children:[(0,a.jsx)("input",{type:"checkbox",name:"is_active",checked:u.is_active,onChange:x,style:{width:"20px",height:"20px"}}),(0,a.jsx)("span",{className:n.default.formLabel,children:"Active"})]}),(0,a.jsx)("p",{style:{fontSize:13,color:"var(--color-text-secondary)",marginTop:8},children:"If unchecked, this coupon cannot be used by customers regardless of the validity period."})]}),(0,a.jsxs)("div",{style:{display:"flex",justifyContent:"flex-end",gap:16},children:[(0,a.jsx)("button",{type:"button",className:n.default.secondaryButton,onClick:()=>e.push("/coupons"),children:"Cancel"}),(0,a.jsx)("button",{type:"submit",className:n.default.primaryButton,disabled:f,children:f?"Saving...":"Create Coupon"})]})]})]}):null}],59533)}]);