module.exports=[817124,e=>{"use strict";var t=e.i(501416),r=e.i(535963),a=e.i(135699),o=e.i(130266),n=e.i(656020),i=e.i(406138),s=e.i(364729),l=e.i(191815),d=e.i(849564),p=e.i(795913),c=e.i(479278),u=e.i(92974),f=e.i(653299),g=e.i(137549),x=e.i(132892),m=e.i(839588),h=e.i(193695);e.i(590748);var R=e.i(608018),b=e.i(925130),y=e.i(781051),N=e.i(596405),v=e.i(256869),w=e.i(752556),E=e.i(216449),I=e.i(254799),A=e.i(978642),C=e.i(439482);async function T(e){try{let t,r;await (0,y.connectDB)();let{orderNumber:a,orderId:o}=await e.json();if(!a&&!o)return b.NextResponse.json({error:"Either orderNumber or orderId must be provided",code:"MISSING_ORDER_IDENTIFIER"},{status:400});if(o){if(!(t=await v.default.findById(o).lean()))return b.NextResponse.json({error:"Order not found",code:"ORDER_NOT_FOUND"},{status:404})}else if(!(t=await v.default.findOne({orderNumber:a}).lean()))return b.NextResponse.json({error:"Order not found",code:"ORDER_NOT_FOUND"},{status:404});let n=await N.default.findOne({orderNumber:t.orderNumber}).lean();if(n)return b.NextResponse.json({error:"Badge already exists for this order",code:"BADGE_ALREADY_EXISTS",badge:n},{status:400});let i=(0,I.randomUUID)(),s=`${t.firstName} ${t.lastName}`,l=t.email,d=t.phone,p=[];try{p="string"==typeof t.cartItems?JSON.parse(t.cartItems):t.cartItems||[]}catch(e){console.error("Error parsing cart items:",e),p=[]}let c=p.map(e=>({excursionId:e.excursionId||e.id||"N/A",excursionName:e.name||e.excursionName||"N/A",date:e.date||"N/A",adults:e.adults||0,children:e.children||0})),u=new Date,f=new Date;f.setDate(f.getDate()+365);let g=new Date,x=await N.default.create({orderId:t._id,orderNumber:t.orderNumber,badgeCode:i,touristName:s,email:l,phone:d,tripDetails:JSON.stringify(c),status:"active",validFrom:u,validUntil:f,generatedAt:g}),m=e.headers.get("origin")||e.headers.get("host")||"http://localhost:3000",h=m.includes("localhost")?"http://":"https://",R=m.startsWith("http")?m:`${h}${m}`,w=`${R}/fr/badge/${i}`;try{r=await (0,C.generateQRCode)(w)}catch(e){return console.error("QR code generation error:",e),b.NextResponse.json({...x.toObject(),emailSent:!1,emailError:"Failed to generate QR code"},{status:201})}try{let e=function({orderNumber:e,firstName:t,lastName:r,email:a,phone:o,cartItems:n,totalMad:i,badgeCode:s,badgeQrCodeUrl:l,paymentMethod:d,status:p}){let c=n.map(e=>`
    <tr>
      <td style="padding: 12px; border-bottom: 1px solid #e5e5e5;">${e.name||e.excursionName||"N/A"}</td>
      <td style="padding: 12px; border-bottom: 1px solid #e5e5e5;">${e.date||"N/A"}</td>
      <td style="padding: 12px; border-bottom: 1px solid #e5e5e5;">${e.adults||0} adultes, ${e.children||0} enfants</td>
    </tr>
  `).join("");return`
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Confirmation de r\xe9servation #${e}</title>
</head>
<body style="margin: 0; padding: 0; font-family: 'Lexend Deca', Arial, sans-serif; background-color: #f0f7fb;">
  <table width="100%" cellpadding="0" cellspacing="0" style="background-color: #f0f7fb; padding: 40px 20px;">
    <tr>
      <td align="center">
        <table width="600" cellpadding="0" cellspacing="0" style="background-color: #ffffff; border-radius: 8px; overflow: hidden; box-shadow: 0 4px 12px rgba(0,0,0,0.1);">
          <!-- Header -->
          <tr>
            <td style="background: linear-gradient(135deg, #FFB73F, #e69d1a); padding: 40px 20px; text-align: center;">
              <h1 style="margin: 0; color: #ffffff; font-family: 'Libre Baskerville', serif; font-size: 28px;">DiffaTours</h1>
              <p style="margin: 10px 0 0 0; color: #ffffff; font-size: 16px;">Confirmation de r\xe9servation</p>
            </td>
          </tr>
          
          <!-- Content -->
          <tr>
            <td style="padding: 40px 30px;">
              <h2 style="margin: 0 0 20px 0; color: #1a1a1a; font-family: 'Libre Baskerville', serif; font-size: 24px;">
                Merci pour votre r\xe9servation, ${t}!
              </h2>
              
              <p style="margin: 0 0 20px 0; color: #666666; font-size: 16px; line-height: 1.6;">
                Votre r\xe9servation a \xe9t\xe9 confirm\xe9e. Voici les d\xe9tails de votre commande:
              </p>
              
              <!-- Order Info -->
              <table width="100%" cellpadding="0" cellspacing="0" style="margin: 30px 0;">
                <tr>
                  <td style="padding: 10px 0; color: #666666;">Num\xe9ro de commande:</td>
                  <td style="padding: 10px 0; color: #1a1a1a; font-weight: 600; text-align: right;">#${e}</td>
                </tr>
                <tr>
                  <td style="padding: 10px 0; color: #666666;">Email:</td>
                  <td style="padding: 10px 0; color: #1a1a1a; text-align: right;">${a}</td>
                </tr>
                <tr>
                  <td style="padding: 10px 0; color: #666666;">T\xe9l\xe9phone:</td>
                  <td style="padding: 10px 0; color: #1a1a1a; text-align: right;">${o}</td>
                </tr>
                <tr>
                  <td style="padding: 10px 0; color: #666666;">Statut:</td>
                  <td style="padding: 10px 0; color: #1a1a1a; text-align: right; text-transform: uppercase;">${p}</td>
                </tr>
              </table>
              
              <!-- Cart Items -->
              <h3 style="margin: 30px 0 15px 0; color: #1a1a1a; font-family: 'Libre Baskerville', serif; font-size: 20px;">
                Vos excursions
              </h3>
              
              <table width="100%" cellpadding="0" cellspacing="0" style="border: 1px solid #e5e5e5; border-radius: 4px;">
                <thead>
                  <tr style="background-color: #f0f7fb;">
                    <th style="padding: 12px; text-align: left; color: #1a1a1a; font-weight: 600;">Excursion</th>
                    <th style="padding: 12px; text-align: left; color: #1a1a1a; font-weight: 600;">Date</th>
                    <th style="padding: 12px; text-align: left; color: #1a1a1a; font-weight: 600;">Participants</th>
                  </tr>
                </thead>
                <tbody>
                  ${c}
                </tbody>
              </table>
              
              <!-- Total -->
              <table width="100%" cellpadding="0" cellspacing="0" style="margin: 20px 0;">
                <tr>
                  <td style="padding: 15px 0; color: #1a1a1a; font-size: 18px; font-weight: 700;">Total:</td>
                  <td style="padding: 15px 0; color: #FFB73F; font-size: 24px; font-weight: 700; text-align: right;">${i.toFixed(2)} MAD</td>
                </tr>
              </table>
              
              <!-- Badge Section -->
              <div style="margin: 40px 0; padding: 30px; background-color: #f0f7fb; border-radius: 8px; text-align: center;">
                <h3 style="margin: 0 0 15px 0; color: #1a1a1a; font-family: 'Libre Baskerville', serif; font-size: 20px;">
                  Votre Badge Touristique
                </h3>
                <p style="margin: 0 0 20px 0; color: #666666; font-size: 14px;">
                  Pr\xe9sentez ce QR code lors de vos excursions
                </p>
                <img src="${l}" alt="QR Code Badge" style="width: 200px; height: 200px; margin: 0 auto; display: block;" />
                <p style="margin: 20px 0 0 0; color: #1a1a1a; font-size: 16px; font-weight: 600;">
                  Code: ${s}
                </p>
              </div>
              
              <p style="margin: 30px 0 0 0; color: #666666; font-size: 14px; line-height: 1.6;">
                Si vous avez des questions, n'h\xe9sitez pas \xe0 nous contacter.<br>
                Nous vous souhaitons d'excellentes excursions!
              </p>
            </td>
          </tr>
          
          <!-- Footer -->
          <tr>
            <td style="padding: 30px; background-color: #1a1a1a; text-align: center;">
              <p style="margin: 0; color: #ffffff; font-size: 14px;">
                \xa9 ${new Date().getFullYear()} DiffaTours. Tous droits r\xe9serv\xe9s.
              </p>
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</body>
</html>
  `}({orderNumber:t.orderNumber,firstName:t.firstName,lastName:t.lastName,email:t.email,phone:t.phone,cartItems:p,totalMad:t.totalMad,badgeCode:i,badgeQrCodeUrl:r,paymentMethod:t.paymentMethod||"N/A",status:t.status||"confirmed"}),a={from:`"DiffaTours R\xe9servations" <${process.env.EMAIL_USER}>`,to:t.email,subject:`✅ Confirmation de r\xe9servation #${t.orderNumber} - DiffaTours`,html:e};return await A.gmailTransporter.sendMail(a),console.log(`Confirmation email sent to ${t.email} with badge ${i}`),b.NextResponse.json({...x.toObject(),emailSent:!0},{status:201})}catch(e){return console.error("Email sending error:",e),b.NextResponse.json({...x.toObject(),emailSent:!1,emailError:e instanceof Error?e.message:"Unknown error"},{status:201})}}catch(e){return console.error("POST error:",e),b.NextResponse.json({error:"Internal server error: "+e.message},{status:500})}}async function D(e){try{await (0,y.connectDB)();let{userId:t}=await (0,E.auth)();if(!t)return b.NextResponse.json({error:"Authentication required",code:"AUTHENTICATION_REQUIRED"},{status:401});let r=await w.default.findOne({clerkId:t}).lean();if(!r)return b.NextResponse.json({error:"User not found",code:"USER_NOT_FOUND"},{status:404});if("admin"!==r.role&&"super_admin"!==r.role)return b.NextResponse.json({error:"Admin access required",code:"ADMIN_ACCESS_REQUIRED"},{status:403});let a=e.nextUrl.searchParams,o=a.get("status"),n=a.get("search"),i=Math.min(parseInt(a.get("limit")??"50"),100),s=parseInt(a.get("offset")??"0");if(isNaN(i)||i<1)return b.NextResponse.json({error:"Invalid limit parameter",code:"INVALID_LIMIT"},{status:400});if(isNaN(s)||s<0)return b.NextResponse.json({error:"Invalid offset parameter",code:"INVALID_OFFSET"},{status:400});let l={};if(o){if(!["active","revoked","expired","used"].includes(o))return b.NextResponse.json({error:"Invalid status parameter",code:"INVALID_STATUS"},{status:400});l.status=o}n&&(l.$or=[{touristName:{$regex:n,$options:"i"}},{email:{$regex:n,$options:"i"}},{orderNumber:{$regex:n,$options:"i"}},{badgeCode:{$regex:n,$options:"i"}}]);let d=await N.default.countDocuments(l),p=(await N.default.find(l).sort({createdAt:-1}).limit(i).skip(s).lean()).map(e=>({id:e._id,badge_code:e.badgeCode,order_number:e.orderNumber,tourist_name:e.touristName,tourist_email:e.email,trip_info:e.tripDetails,status:e.status,valid_until:e.validUntil,created_at:e.createdAt,scans_count:0}));return b.NextResponse.json({badges:p,total:d,limit:i,offset:s},{status:200})}catch(e){return console.error("GET error:",e),b.NextResponse.json({error:"Internal server error: "+e.message},{status:500})}}e.s(["GET",()=>D,"POST",()=>T],567139);var _=e.i(567139);let O=new t.AppRouteRouteModule({definition:{kind:r.RouteKind.APP_ROUTE,page:"/api/badges/route",pathname:"/api/badges",filename:"route",bundlePath:""},distDir:".next",relativeProjectDir:"",resolvedPagePath:"[project]/Desktop/Aynnaka/DiffaTours-main 2/src/app/api/badges/route.ts",nextConfigOutput:"",userland:_}),{workAsyncStorage:$,workUnitAsyncStorage:S,serverHooks:U}=O;function k(){return(0,a.patchFetch)({workAsyncStorage:$,workUnitAsyncStorage:S})}async function j(e,t,a){O.isDev&&(0,o.addRequestMeta)(e,"devRequestTimingInternalsEnd",process.hrtime.bigint());let b="/api/badges/route";b=b.replace(/\/index$/,"")||"/";let y=await O.prepare(e,t,{srcPage:b,multiZoneDraftMode:!1});if(!y)return t.statusCode=400,t.end("Bad Request"),null==a.waitUntil||a.waitUntil.call(a,Promise.resolve()),null;let{buildId:N,params:v,nextConfig:w,parsedUrl:E,isDraftMode:I,prerenderManifest:A,routerServerContext:C,isOnDemandRevalidate:T,revalidateOnlyGenerated:D,resolvedPathname:_,clientReferenceManifest:$,serverActionsManifest:S}=y,U=(0,l.normalizeAppPath)(b),k=!!(A.dynamicRoutes[U]||A.routes[_]),j=async()=>((null==C?void 0:C.render404)?await C.render404(e,t,E,!1):t.end("This page could not be found"),null);if(k&&!I){let e=!!A.routes[_],t=A.dynamicRoutes[U];if(t&&!1===t.fallback&&!e){if(w.experimental.adapterPath)return await j();throw new h.NoFallbackError}}let P=null;!k||O.isDev||I||(P="/index"===(P=_)?"/":P);let M=!0===O.isDev||!k,F=k&&!M;S&&$&&(0,i.setReferenceManifestsSingleton)({page:b,clientReferenceManifest:$,serverActionsManifest:S,serverModuleMap:(0,s.createServerModuleMap)({serverActionsManifest:S})});let q=e.method||"GET",B=(0,n.getTracer)(),H=B.getActiveScopeSpan(),z={params:v,prerenderManifest:A,renderOpts:{experimental:{authInterrupts:!!w.experimental.authInterrupts},cacheComponents:!!w.cacheComponents,supportsDynamicResponse:M,incrementalCache:(0,o.getRequestMeta)(e,"incrementalCache"),cacheLifeProfiles:w.cacheLife,waitUntil:a.waitUntil,onClose:e=>{t.on("close",e)},onAfterTaskError:void 0,onInstrumentationRequestError:(t,r,a)=>O.onRequestError(e,t,a,C)},sharedContext:{buildId:N}},L=new d.NodeNextRequest(e),V=new d.NodeNextResponse(t),K=p.NextRequestAdapter.fromNodeNextRequest(L,(0,p.signalFromNodeResponse)(t));try{let i=async e=>O.handle(K,z).finally(()=>{if(!e)return;e.setAttributes({"http.status_code":t.statusCode,"next.rsc":!1});let r=B.getRootSpanAttributes();if(!r)return;if(r.get("next.span_type")!==c.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=`${q} ${a}`;e.setAttributes({"next.route":a,"http.route":a,"next.span_name":t}),e.updateName(t)}else e.updateName(`${q} ${b}`)}),s=!!(0,o.getRequestMeta)(e,"minimalMode"),l=async o=>{var n,l;let d=async({previousCacheEntry:r})=>{try{if(!s&&T&&D&&!r)return t.statusCode=404,t.setHeader("x-nextjs-cache","REVALIDATED"),t.end("This page could not be found"),null;let n=await i(o);e.fetchMetrics=z.renderOpts.fetchMetrics;let l=z.renderOpts.pendingWaitUntil;l&&a.waitUntil&&(a.waitUntil(l),l=void 0);let d=z.renderOpts.collectedTags;if(!k)return await (0,f.sendResponse)(L,V,n,z.renderOpts.pendingWaitUntil),null;{let e=await n.blob(),t=(0,g.toNodeOutgoingHttpHeaders)(n.headers);d&&(t[m.NEXT_CACHE_TAGS_HEADER]=d),!t["content-type"]&&e.type&&(t["content-type"]=e.type);let r=void 0!==z.renderOpts.collectedRevalidate&&!(z.renderOpts.collectedRevalidate>=m.INFINITE_CACHE)&&z.renderOpts.collectedRevalidate,a=void 0===z.renderOpts.collectedExpire||z.renderOpts.collectedExpire>=m.INFINITE_CACHE?void 0:z.renderOpts.collectedExpire;return{value:{kind:R.CachedRouteKind.APP_ROUTE,status:n.status,body:Buffer.from(await e.arrayBuffer()),headers:t},cacheControl:{revalidate:r,expire:a}}}}catch(t){throw(null==r?void 0:r.isStale)&&await O.onRequestError(e,t,{routerKind:"App Router",routePath:b,routeType:"route",revalidateReason:(0,u.getRevalidateReason)({isStaticGeneration:F,isOnDemandRevalidate:T})},C),t}},p=await O.handleResponse({req:e,nextConfig:w,cacheKey:P,routeKind:r.RouteKind.APP_ROUTE,isFallback:!1,prerenderManifest:A,isRoutePPREnabled:!1,isOnDemandRevalidate:T,revalidateOnlyGenerated:D,responseGenerator:d,waitUntil:a.waitUntil,isMinimalMode:s});if(!k)return null;if((null==p||null==(n=p.value)?void 0:n.kind)!==R.CachedRouteKind.APP_ROUTE)throw Object.defineProperty(Error(`Invariant: app-route received invalid cache entry ${null==p||null==(l=p.value)?void 0:l.kind}`),"__NEXT_ERROR_CODE",{value:"E701",enumerable:!1,configurable:!0});s||t.setHeader("x-nextjs-cache",T?"REVALIDATED":p.isMiss?"MISS":p.isStale?"STALE":"HIT"),I&&t.setHeader("Cache-Control","private, no-cache, no-store, max-age=0, must-revalidate");let c=(0,g.fromNodeOutgoingHttpHeaders)(p.value.headers);return s&&k||c.delete(m.NEXT_CACHE_TAGS_HEADER),!p.cacheControl||t.getHeader("Cache-Control")||c.get("Cache-Control")||c.set("Cache-Control",(0,x.getCacheControlHeader)(p.cacheControl)),await (0,f.sendResponse)(L,V,new Response(p.value.body,{headers:c,status:p.value.status||200})),null};H?await l(H):await B.withPropagatedContext(e.headers,()=>B.trace(c.BaseServerSpan.handleRequest,{spanName:`${q} ${b}`,kind:n.SpanKind.SERVER,attributes:{"http.method":q,"http.target":e.url}},l))}catch(t){if(t instanceof h.NoFallbackError||await O.onRequestError(e,t,{routerKind:"App Router",routePath:U,routeType:"route",revalidateReason:(0,u.getRevalidateReason)({isStaticGeneration:F,isOnDemandRevalidate:T})}),k)throw t;return await (0,f.sendResponse)(L,V,new Response(null,{status:500})),null}}e.s(["handler",()=>j,"patchFetch",()=>k,"routeModule",()=>O,"serverHooks",()=>U,"workAsyncStorage",()=>$,"workUnitAsyncStorage",()=>S],817124)}];

//# sourceMappingURL=e99c8_next_dist_esm_build_templates_app-route_16ed0e8a.js.map