module.exports=[338706,e=>e.a(async(t,r)=>{try{var o=e.i(925130),a=e.i(781051),n=e.i(256869),s=e.i(774664),i=e.i(937970),l=t([s]);async function d(e,{params:t}){try{let{orderNumber:r}=await t,l=await e.json(),d=l?.locale;if(console.log("[EMAIL] Starting email send for order:",r),console.log("[EMAIL] EMAIL_USER configured:",!!process.env.EMAIL_USER),console.log("[EMAIL] EMAIL_PASSWORD configured:",!!process.env.EMAIL_PASSWORD),!process.env.EMAIL_USER||!process.env.EMAIL_PASSWORD)return console.error("[EMAIL] Missing email configuration"),o.NextResponse.json({error:"Server email configuration missing"},{status:500});await (0,a.connectDB)();let c=await n.default.findOne({orderNumber:r});if(!c)return console.log("[EMAIL] Order not found:",r),o.NextResponse.json({error:"Order not found"},{status:404});let p=d||c.locale||"fr";console.log("[EMAIL] Order found, generating PDF with locale:",p);let u=[];try{u=JSON.parse(c.cartItems||"[]")}catch(e){console.warn("Failed to parse cart items:",e),u=[]}let g=u.map(e=>{let t=e.ageGroups?Object.entries(e.ageGroups).filter(([e,t])=>t>0).map(([e,t])=>({ageGroup:e,count:t,price:0})):[];return{excursionName:e.excursionName||"",excursionPrice:e.priceMAD||e.total||0,selectedItems:e.selectedItems||[],ageGroups:t}}),m=await (0,s.generateInvoicePDF)({orderNumber:c.orderNumber,orderDate:c.createdAt,firstName:c.firstName,lastName:c.lastName,email:c.email,phone:c.phone,passport:c.passport,city:c.city,accommodationType:c.accommodationType,hotelName:c.hotelName,address:c.address,cartItems:g,totalMad:c.totalMad,paymentMethod:c.paymentMethod,paymentStatus:c.paymentStatus,currency:c.currency,exchangeRate:c.exchangeRate},p);console.log("[EMAIL] PDF generated successfully, size:",m.length,"bytes");let f={fr:{subject:`Facture - Commande ${r}`,greeting:`Bonjour ${c.firstName} ${c.lastName},`,body:`
          <p>Merci pour votre r\xe9servation avec DiffaTours !</p>
          <p>Veuillez trouver ci-joint votre facture pour la commande <strong>${r}</strong>.</p>
          <p><strong>Montant total :</strong> ${c.totalMad.toFixed(2)} MAD</p>
          <p><strong>Mode de paiement :</strong> ${"cash"===c.paymentMethod?"Espèces (à la prise en charge)":"Paiement en ligne"}</p>
          <p><strong>Statut :</strong> ${"paid"===c.paymentStatus?"Payé":"En attente"}</p>
          <hr style="margin: 20px 0; border: none; border-top: 1px solid #e5e5e5;">
          <p style="color: #666; font-size: 12px;">
            Pour toute question, n'h\xe9sitez pas \xe0 nous contacter.<br>
            Email: contact@diffatours.com<br>
            T\xe9l\xe9phone: +212 XXX XXX XXX
          </p>
        `},en:{subject:`Invoice - Order ${r}`,greeting:`Hello ${c.firstName} ${c.lastName},`,body:`
          <p>Thank you for your booking with DiffaTours!</p>
          <p>Please find attached your invoice for order <strong>${r}</strong>.</p>
          <p><strong>Total amount:</strong> ${c.totalMad.toFixed(2)} MAD</p>
          <p><strong>Payment method:</strong> ${"cash"===c.paymentMethod?"Cash (upon pickup)":"Online Payment"}</p>
          <p><strong>Status:</strong> ${"paid"===c.paymentStatus?"Paid":"Pending"}</p>
          <hr style="margin: 20px 0; border: none; border-top: 1px solid #e5e5e5;">
          <p style="color: #666; font-size: 12px;">
            For any questions, please contact us.<br>
            Email: contact@diffatours.com<br>
            Phone: +212 XXX XXX XXX
          </p>
        `},es:{subject:`Factura - Pedido ${r}`,greeting:`Hola ${c.firstName} ${c.lastName},`,body:`
          <p>\xa1Gracias por su reserva con DiffaTours!</p>
          <p>Adjunto encontrar\xe1 su factura para el pedido <strong>${r}</strong>.</p>
          <p><strong>Monto total:</strong> ${c.totalMad.toFixed(2)} MAD</p>
          <p><strong>M\xe9todo de pago:</strong> ${"cash"===c.paymentMethod?"Efectivo (al recoger)":"Pago en línea"}</p>
          <p><strong>Estado:</strong> ${"paid"===c.paymentStatus?"Pagado":"Pendiente"}</p>
          <hr style="margin: 20px 0; border: none; border-top: 1px solid #e5e5e5;">
          <p style="color: #666; font-size: 12px;">
            Para cualquier pregunta, cont\xe1ctenos.<br>
            Email: contact@diffatours.com<br>
            Tel\xe9fono: +212 XXX XXX XXX
          </p>
        `},it:{subject:`Fattura - Ordine ${r}`,greeting:`Ciao ${c.firstName} ${c.lastName},`,body:`
          <p>Grazie per la tua prenotazione con DiffaTours!</p>
          <p>In allegato troverai la fattura per l'ordine <strong>${r}</strong>.</p>
          <p><strong>Importo totale:</strong> ${c.totalMad.toFixed(2)} MAD</p>
          <p><strong>Metodo di pagamento:</strong> ${"cash"===c.paymentMethod?"Contanti (al ritiro)":"Pagamento online"}</p>
          <p><strong>Stato:</strong> ${"paid"===c.paymentStatus?"Pagato":"In attesa"}</p>
          <hr style="margin: 20px 0; border: none; border-top: 1px solid #e5e5e5;">
          <p style="color: #666; font-size: 12px;">
            Per qualsiasi domanda, contattaci.<br>
            Email: contact@diffatours.com<br>
            Telefono: +212 XXX XXX XXX
          </p>
        `}},h=f[p]||f.fr;console.log("[EMAIL] Sending email to:",c.email),console.log("[EMAIL] Subject:",h.subject);let{data:x,error:y}=await i.resend.emails.send({from:"DiffaTours Facturation <billing@diffatours.com>",to:c.email,subject:h.subject,html:`
        <!DOCTYPE html>
        <html>
          <head>
            <meta charset="UTF-8">
            <style>
              body {
                font-family: Arial, sans-serif;
                line-height: 1.6;
                color: #333;
                max-width: 600px;
                margin: 0 auto;
                padding: 20px;
              }
              .header {
                background: linear-gradient(135deg, #FFB73F, #e69d1a);
                color: white;
                padding: 30px 20px;
                text-align: center;
                border-radius: 8px 8px 0 0;
              }
              .header h1 {
                margin: 0;
                font-size: 28px;
              }
              .content {
                background: #ffffff;
                padding: 30px 20px;
                border: 1px solid #e5e5e5;
                border-top: none;
                border-radius: 0 0 8px 8px;
              }
              .content p {
                margin: 15px 0;
              }
              .footer {
                margin-top: 20px;
                text-align: center;
                color: #999;
                font-size: 12px;
              }
            </style>
          </head>
          <body>
            <div class="header">
              <h1>DIFFATOURS</h1>
            </div>
            <div class="content">
              <h2 style="color: #FFB73F; margin-top: 0;">${h.greeting}</h2>
              ${h.body}
            </div>
            <div class="footer">
              <p>&copy; ${new Date().getFullYear()} DiffaTours. All rights reserved.</p>
            </div>
          </body>
        </html>
      `,attachments:[{filename:`invoice-${r}.pdf`,content:m}]});if(y)throw console.error("Resend invoice email error:",y),Error(`Resend error: ${y.message}`);return console.log("[EMAIL] Invoice email sent successfully via Resend:",x?.id),o.NextResponse.json({success:!0,message:"Invoice sent successfully"})}catch(e){return console.error("[EMAIL] Email invoice error:",e),console.error("[EMAIL] Error stack:",e instanceof Error?e.stack:"No stack trace"),o.NextResponse.json({error:"Failed to send invoice email",details:e instanceof Error?e.message:"Unknown error"},{status:500})}}[s]=l.then?(await l)():l,e.s(["POST",()=>d,"maxDuration",0,60]),r()}catch(e){r(e)}},!1),358111,e=>e.a(async(t,r)=>{try{var o=e.i(501416),a=e.i(535963),n=e.i(135699),s=e.i(130266),i=e.i(656020),l=e.i(406138),d=e.i(364729),c=e.i(191815),p=e.i(849564),u=e.i(795913),g=e.i(479278),m=e.i(92974),f=e.i(653299),h=e.i(137549),x=e.i(132892),y=e.i(839588),v=e.i(193695);e.i(590748);var E=e.i(608018),R=e.i(338706),b=t([R]);[R]=b.then?(await b)():b;let w=new o.AppRouteRouteModule({definition:{kind:a.RouteKind.APP_ROUTE,page:"/api/invoices/email/[orderNumber]/route",pathname:"/api/invoices/email/[orderNumber]",filename:"route",bundlePath:""},distDir:".next",relativeProjectDir:"",resolvedPagePath:"[project]/Desktop/Aynnaka/DiffaTours-main 2/src/app/api/invoices/email/[orderNumber]/route.ts",nextConfigOutput:"",userland:R}),{workAsyncStorage:N,workUnitAsyncStorage:P,serverHooks:I}=w;function A(){return(0,n.patchFetch)({workAsyncStorage:N,workUnitAsyncStorage:P})}async function M(e,t,r){w.isDev&&(0,s.addRequestMeta)(e,"devRequestTimingInternalsEnd",process.hrtime.bigint());let o="/api/invoices/email/[orderNumber]/route";o=o.replace(/\/index$/,"")||"/";let n=await w.prepare(e,t,{srcPage:o,multiZoneDraftMode:!1});if(!n)return t.statusCode=400,t.end("Bad Request"),null==r.waitUntil||r.waitUntil.call(r,Promise.resolve()),null;let{buildId:R,params:b,nextConfig:A,parsedUrl:M,isDraftMode:N,prerenderManifest:P,routerServerContext:I,isOnDemandRevalidate:S,revalidateOnlyGenerated:T,resolvedPathname:$,clientReferenceManifest:C,serverActionsManifest:X}=n,D=(0,c.normalizeAppPath)(o),O=!!(P.dynamicRoutes[D]||P.routes[$]),F=async()=>((null==I?void 0:I.render404)?await I.render404(e,t,M,!1):t.end("This page could not be found"),null);if(O&&!N){let e=!!P.routes[$],t=P.dynamicRoutes[D];if(t&&!1===t.fallback&&!e){if(A.experimental.adapterPath)return await F();throw new v.NoFallbackError}}let _=null;!O||w.isDev||N||(_=$,_="/index"===_?"/":_);let j=!0===w.isDev||!O,k=O&&!j;X&&C&&(0,l.setReferenceManifestsSingleton)({page:o,clientReferenceManifest:C,serverActionsManifest:X,serverModuleMap:(0,d.createServerModuleMap)({serverActionsManifest:X})});let L=e.method||"GET",U=(0,i.getTracer)(),H=U.getActiveScopeSpan(),q={params:b,prerenderManifest:P,renderOpts:{experimental:{authInterrupts:!!A.experimental.authInterrupts},cacheComponents:!!A.cacheComponents,supportsDynamicResponse:j,incrementalCache:(0,s.getRequestMeta)(e,"incrementalCache"),cacheLifeProfiles:A.cacheLife,waitUntil:r.waitUntil,onClose:e=>{t.on("close",e)},onAfterTaskError:void 0,onInstrumentationRequestError:(t,r,o)=>w.onRequestError(e,t,o,I)},sharedContext:{buildId:R}},z=new p.NodeNextRequest(e),B=new p.NodeNextResponse(t),G=u.NextRequestAdapter.fromNodeNextRequest(z,(0,u.signalFromNodeResponse)(t));try{let n=async e=>w.handle(G,q).finally(()=>{if(!e)return;e.setAttributes({"http.status_code":t.statusCode,"next.rsc":!1});let r=U.getRootSpanAttributes();if(!r)return;if(r.get("next.span_type")!==g.BaseServerSpan.handleRequest)return void console.warn(`Unexpected root span type '${r.get("next.span_type")}'. Please report this Next.js issue https://github.com/vercel/next.js`);let a=r.get("next.route");if(a){let t=`${L} ${a}`;e.setAttributes({"next.route":a,"http.route":a,"next.span_name":t}),e.updateName(t)}else e.updateName(`${L} ${o}`)}),l=!!(0,s.getRequestMeta)(e,"minimalMode"),d=async s=>{var i,d;let c=async({previousCacheEntry:a})=>{try{if(!l&&S&&T&&!a)return t.statusCode=404,t.setHeader("x-nextjs-cache","REVALIDATED"),t.end("This page could not be found"),null;let o=await n(s);e.fetchMetrics=q.renderOpts.fetchMetrics;let i=q.renderOpts.pendingWaitUntil;i&&r.waitUntil&&(r.waitUntil(i),i=void 0);let d=q.renderOpts.collectedTags;if(!O)return await (0,f.sendResponse)(z,B,o,q.renderOpts.pendingWaitUntil),null;{let e=await o.blob(),t=(0,h.toNodeOutgoingHttpHeaders)(o.headers);d&&(t[y.NEXT_CACHE_TAGS_HEADER]=d),!t["content-type"]&&e.type&&(t["content-type"]=e.type);let r=void 0!==q.renderOpts.collectedRevalidate&&!(q.renderOpts.collectedRevalidate>=y.INFINITE_CACHE)&&q.renderOpts.collectedRevalidate,a=void 0===q.renderOpts.collectedExpire||q.renderOpts.collectedExpire>=y.INFINITE_CACHE?void 0:q.renderOpts.collectedExpire;return{value:{kind:E.CachedRouteKind.APP_ROUTE,status:o.status,body:Buffer.from(await e.arrayBuffer()),headers:t},cacheControl:{revalidate:r,expire:a}}}}catch(t){throw(null==a?void 0:a.isStale)&&await w.onRequestError(e,t,{routerKind:"App Router",routePath:o,routeType:"route",revalidateReason:(0,m.getRevalidateReason)({isStaticGeneration:k,isOnDemandRevalidate:S})},I),t}},p=await w.handleResponse({req:e,nextConfig:A,cacheKey:_,routeKind:a.RouteKind.APP_ROUTE,isFallback:!1,prerenderManifest:P,isRoutePPREnabled:!1,isOnDemandRevalidate:S,revalidateOnlyGenerated:T,responseGenerator:c,waitUntil:r.waitUntil,isMinimalMode:l});if(!O)return null;if((null==p||null==(i=p.value)?void 0:i.kind)!==E.CachedRouteKind.APP_ROUTE)throw Object.defineProperty(Error(`Invariant: app-route received invalid cache entry ${null==p||null==(d=p.value)?void 0:d.kind}`),"__NEXT_ERROR_CODE",{value:"E701",enumerable:!1,configurable:!0});l||t.setHeader("x-nextjs-cache",S?"REVALIDATED":p.isMiss?"MISS":p.isStale?"STALE":"HIT"),N&&t.setHeader("Cache-Control","private, no-cache, no-store, max-age=0, must-revalidate");let u=(0,h.fromNodeOutgoingHttpHeaders)(p.value.headers);return l&&O||u.delete(y.NEXT_CACHE_TAGS_HEADER),!p.cacheControl||t.getHeader("Cache-Control")||u.get("Cache-Control")||u.set("Cache-Control",(0,x.getCacheControlHeader)(p.cacheControl)),await (0,f.sendResponse)(z,B,new Response(p.value.body,{headers:u,status:p.value.status||200})),null};H?await d(H):await U.withPropagatedContext(e.headers,()=>U.trace(g.BaseServerSpan.handleRequest,{spanName:`${L} ${o}`,kind:i.SpanKind.SERVER,attributes:{"http.method":L,"http.target":e.url}},d))}catch(t){if(t instanceof v.NoFallbackError||await w.onRequestError(e,t,{routerKind:"App Router",routePath:D,routeType:"route",revalidateReason:(0,m.getRevalidateReason)({isStaticGeneration:k,isOnDemandRevalidate:S})}),O)throw t;return await (0,f.sendResponse)(z,B,new Response(null,{status:500})),null}}e.s(["handler",()=>M,"patchFetch",()=>A,"routeModule",()=>w,"serverHooks",()=>I,"workAsyncStorage",()=>N,"workUnitAsyncStorage",()=>P]),r()}catch(e){r(e)}},!1)];

//# sourceMappingURL=Desktop_Aynnaka_DiffaTours-main%202_d8f4d391._.js.map