module.exports=[309679,e=>{"use strict";var t=e.i(501416),r=e.i(535963),o=e.i(135699),n=e.i(130266),a=e.i(656020),s=e.i(406138),i=e.i(364729),l=e.i(191815),d=e.i(849564),u=e.i(795913),c=e.i(479278),p=e.i(92974),f=e.i(653299),g=e.i(137549),m=e.i(132892),x=e.i(839588),h=e.i(193695);e.i(590748);var b=e.i(608018),R=e.i(925130),y=e.i(216449),v=e.i(781051),E=e.i(256869),N=e.i(752556),w=e.i(491781),A=e.i(978642);async function I(e,{params:t}){try{console.log("📝 Updating admin order..."),await (0,v.connectDB)(),console.log("✅ Database connected");let r=null;try{let e=await (0,y.auth)();r=e?.userId||null,console.log("🔐 Clerk admin user ID:",r)}catch(e){return console.error("❌ Auth error:",e),R.NextResponse.json({error:"Authentication failed: "+e.message,code:"AUTH_FAILED"},{status:401})}if(!r)return console.error("❌ No user ID found in auth"),R.NextResponse.json({error:"Authentication required",code:"AUTH_REQUIRED"},{status:401});let o=await N.default.findOne({clerkId:r});if(console.log("🔍 User lookup result:",o?`Found user ${o._id}`:"User not found"),!o)return console.error("❌ User not found for clerkId:",r),R.NextResponse.json({error:"User not found",code:"USER_NOT_FOUND"},{status:404});if("admin"!==o.role&&"super_admin"!==o.role)return console.error("❌ Admin access denied for user:",o._id,"Role:",o.role),R.NextResponse.json({error:"Admin access required",code:"ADMIN_ACCESS_REQUIRED"},{status:403});console.log("✅ Admin access verified for user:",o._id);let{id:n}=await t;console.log("🔍 Looking up order with ID:",n);let a=await E.default.findById(n);if(!a)return console.error("❌ Order not found with ID:",n),R.NextResponse.json({error:"Order not found",code:"ORDER_NOT_FOUND"},{status:404});console.log("✅ Order found:",a.orderNumber);let{status:s,paymentStatus:i}=await e.json();console.log("📋 Update request body:",{status:s,paymentStatus:i});let l=["pending","confirmed","paid","cancelled"];if(void 0!==s&&!l.includes(s))return console.error("❌ Invalid status provided:",s),R.NextResponse.json({error:`Invalid status. Must be one of: ${l.join(", ")}`,code:"INVALID_STATUS"},{status:400});let d=["pending","paid","failed","refunded"];if(void 0!==i&&!d.includes(i))return console.error("❌ Invalid payment status provided:",i),R.NextResponse.json({error:`Invalid payment status. Must be one of: ${d.join(", ")}`,code:"INVALID_PAYMENT_STATUS"},{status:400});let u={updatedAt:new Date};void 0!==s&&(u.status=s),void 0!==i&&(u.paymentStatus=i,"paid"===i&&(u.paidAt=Math.floor(Date.now()/1e3))),console.log("📝 Applying updates:",u);let c=await E.default.findByIdAndUpdate(n,u,{new:!0});if(!c)return console.error("❌ Failed to update order:",n),R.NextResponse.json({error:"Failed to update order",code:"UPDATE_FAILED"},{status:500});console.log("✅ Order updated successfully:",c.orderNumber);let p=[];try{p="string"==typeof c.cartItems?JSON.parse(c.cartItems):c.cartItems||[],console.log("📦 Parsed cart items:",p.length,"items")}catch(e){console.error("❌ Error parsing cart items:",e),p=[]}if("confirmed"===s&&(console.log("📧 Creating in-app notification for order:",c.orderNumber),c.userClerkId))try{await w.default.create({userId:c.userClerkId,type:"order_confirmed",title:"Commande confirmée",message:`Votre commande (${c.orderNumber.substring(0,8)}...) a \xe9t\xe9 confirm\xe9e !`,orderId:c._id.toString(),orderNumber:c.orderNumber,read:!1}),console.log("✅ In-app notification created for order confirmation")}catch(e){console.error("❌ Failed to create user notification:",e)}if("cancelled"===s&&(console.log("📧 Sending cancellation notifications for order:",c.orderNumber),c.userClerkId))try{await w.default.create({userId:c.userClerkId,type:"order_rejected",title:"Commande annulée",message:`Votre commande (${c.orderNumber.substring(0,8)}...) a \xe9t\xe9 annul\xe9e. Veuillez contacter le support pour plus d'informations.`,orderId:c._id.toString(),orderNumber:c.orderNumber,read:!1}),console.log("✅ User notification created for order cancellation");try{let e,t=(e=p.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(""),`
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Annulation de r\xe9servation #${c.orderNumber}</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);">
          <tr>
            <td style="background: linear-gradient(135deg, #c67b5c, #a66b4f); 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;">❌ R\xe9servation Annul\xe9e</p>
            </td>
          </tr>
          
          <tr>
            <td style="padding: 40px 30px;">
              <h2 style="margin: 0 0 20px 0; color: #1a1a1a; font-family: 'Libre Baskerville', serif; font-size: 24px;">
                Cher(e) ${c.firstName},
              </h2>
              
              <p style="margin: 0 0 20px 0; color: #666666; font-size: 16px; line-height: 1.6;">
                Nous regrettons de vous informer que votre r\xe9servation a \xe9t\xe9 <strong style="color: #c67b5c;">annul\xe9e</strong>.
              </p>
              
              <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;">#${c.orderNumber}</td>
                </tr>
                <tr>
                  <td style="padding: 10px 0; color: #666666;">Statut:</td>
                  <td style="padding: 10px 0; color: #c67b5c; font-weight: 600; text-align: right;">ANNUL\xc9E</td>
                </tr>
              </table>
              
              <h3 style="margin: 30px 0 15px 0; color: #1a1a1a; font-family: 'Libre Baskerville', serif; font-size: 20px;">
                D\xe9tails de la r\xe9servation
              </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>
                  ${e}
                </tbody>
              </table>
              
              <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;">Montant:</td>
                  <td style="padding: 15px 0; color: #1a1a1a; font-size: 24px; font-weight: 700; text-align: right;">${c.totalMad.toFixed(2)} MAD</td>
                </tr>
              </table>
              
              <div style="margin: 30px 0; padding: 20px; background-color: #fff3cd; border-radius: 8px; border-left: 4px solid #FFB73F;">
                <p style="margin: 0; color: #1a1a1a; font-size: 14px; line-height: 1.6;">
                  <strong>Raisons possibles de l'annulation:</strong><br>
                  • Indisponibilit\xe9 \xe0 la date demand\xe9e<br>
                  • Probl\xe8me avec les informations de r\xe9servation<br>
                  • Capacit\xe9 maximale atteinte<br><br>
                  
                  <strong>Que faire maintenant?</strong><br>
                  • Contactez-nous pour plus d'informations<br>
                  • Si vous avez effectu\xe9 un paiement, vous serez rembours\xe9 sous 7-10 jours<br>
                  • Vous pouvez effectuer une nouvelle r\xe9servation \xe0 une autre date
                </p>
              </div>
              
              <p style="margin: 30px 0 0 0; color: #666666; font-size: 14px; line-height: 1.6;">
                Nous sommes d\xe9sol\xe9s pour ce d\xe9sagr\xe9ment. N'h\xe9sitez pas \xe0 nous contacter pour toute question ou pour effectuer une nouvelle r\xe9servation.<br><br>
                L'\xe9quipe DiffaTours
              </p>
            </td>
          </tr>
          
          <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>
              <p style="margin: 10px 0 0 0; color: #999999; font-size: 12px;">
                Besoin d'aide? Contactez-nous: ${process.env.EMAIL_USER}
              </p>
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</body>
</html>
  `),r={from:`"DiffaTours R\xe9servations" <${process.env.EMAIL_USER}>`,to:c.email,subject:`❌ Annulation de votre r\xe9servation #${c.orderNumber} - DiffaTours`,html:t};await A.gmailTransporter.sendMail(r),console.log("✅ Cancellation email sent to user:",c.email)}catch(e){console.error("❌ Failed to send cancellation email:",e)}}catch(e){console.error("❌ Failed to create user notification:",e)}return R.NextResponse.json(c)}catch(e){return console.error("❌ PUT admin order error:",e),console.error("Error stack:",e.stack),R.NextResponse.json({error:"Internal server error",details:e instanceof Error?e.message:"Unknown error"},{status:500})}}async function D(e,{params:t}){try{console.log("🗑️ Deleting admin order..."),await (0,v.connectDB)(),console.log("✅ Database connected");let e=null;try{let t=await (0,y.auth)();e=t?.userId||null,console.log("🔐 Clerk admin user ID:",e)}catch(e){return console.error("❌ Auth error:",e),R.NextResponse.json({error:"Authentication failed: "+e.message,code:"AUTH_FAILED"},{status:401})}if(!e)return console.error("❌ No user ID found in auth"),R.NextResponse.json({error:"Authentication required",code:"AUTH_REQUIRED"},{status:401});let r=await N.default.findOne({clerkId:e});if(console.log("🔍 User lookup result:",r?`Found user ${r._id}`:"User not found"),!r)return console.error("❌ User not found for clerkId:",e),R.NextResponse.json({error:"User not found",code:"USER_NOT_FOUND"},{status:404});if("admin"!==r.role&&"super_admin"!==r.role)return console.error("❌ Admin access denied for user:",r._id,"Role:",r.role),R.NextResponse.json({error:"Admin access required",code:"ADMIN_ACCESS_REQUIRED"},{status:403});console.log("✅ Admin access verified for user:",r._id);let{id:o}=await t;console.log("🔍 Looking up order to delete with ID:",o);let n=await E.default.findById(o);if(!n)return console.error("❌ Order not found with ID:",o),R.NextResponse.json({error:"Order not found",code:"ORDER_NOT_FOUND"},{status:404});return console.log("✅ Order found, deleting:",n.orderNumber),await E.default.findByIdAndDelete(o),console.log("✅ Order deleted successfully:",n.orderNumber),R.NextResponse.json({success:!0,message:"Order deleted successfully"},{status:200})}catch(e){return console.error("❌ DELETE admin order error:",e),console.error("Error stack:",e.stack),R.NextResponse.json({error:"Internal server error",details:e instanceof Error?e.message:"Unknown error"},{status:500})}}e.s(["DELETE",()=>D,"PUT",()=>I],696458);var C=e.i(696458);let _=new t.AppRouteRouteModule({definition:{kind:r.RouteKind.APP_ROUTE,page:"/api/admin/orders/[id]/route",pathname:"/api/admin/orders/[id]",filename:"route",bundlePath:""},distDir:".next",relativeProjectDir:"",resolvedPagePath:"[project]/Desktop/Aynnaka/DiffaTours-main 2/src/app/api/admin/orders/[id]/route.ts",nextConfigOutput:"",userland:C}),{workAsyncStorage:U,workUnitAsyncStorage:T,serverHooks:k}=_;function O(){return(0,o.patchFetch)({workAsyncStorage:U,workUnitAsyncStorage:T})}async function S(e,t,o){_.isDev&&(0,n.addRequestMeta)(e,"devRequestTimingInternalsEnd",process.hrtime.bigint());let R="/api/admin/orders/[id]/route";R=R.replace(/\/index$/,"")||"/";let y=await _.prepare(e,t,{srcPage:R,multiZoneDraftMode:!1});if(!y)return t.statusCode=400,t.end("Bad Request"),null==o.waitUntil||o.waitUntil.call(o,Promise.resolve()),null;let{buildId:v,params:E,nextConfig:N,parsedUrl:w,isDraftMode:A,prerenderManifest:I,routerServerContext:D,isOnDemandRevalidate:C,revalidateOnlyGenerated:U,resolvedPathname:T,clientReferenceManifest:k,serverActionsManifest:O}=y,S=(0,l.normalizeAppPath)(R),j=!!(I.dynamicRoutes[S]||I.routes[T]),P=async()=>((null==D?void 0:D.render404)?await D.render404(e,t,w,!1):t.end("This page could not be found"),null);if(j&&!A){let e=!!I.routes[T],t=I.dynamicRoutes[S];if(t&&!1===t.fallback&&!e){if(N.experimental.adapterPath)return await P();throw new h.NoFallbackError}}let M=null;!j||_.isDev||A||(M="/index"===(M=T)?"/":M);let $=!0===_.isDev||!j,F=j&&!$;O&&k&&(0,s.setReferenceManifestsSingleton)({page:R,clientReferenceManifest:k,serverActionsManifest:O,serverModuleMap:(0,i.createServerModuleMap)({serverActionsManifest:O})});let q=e.method||"GET",L=(0,a.getTracer)(),H=L.getActiveScopeSpan(),z={params:E,prerenderManifest:I,renderOpts:{experimental:{authInterrupts:!!N.experimental.authInterrupts},cacheComponents:!!N.cacheComponents,supportsDynamicResponse:$,incrementalCache:(0,n.getRequestMeta)(e,"incrementalCache"),cacheLifeProfiles:N.cacheLife,waitUntil:o.waitUntil,onClose:e=>{t.on("close",e)},onAfterTaskError:void 0,onInstrumentationRequestError:(t,r,o)=>_.onRequestError(e,t,o,D)},sharedContext:{buildId:v}},B=new d.NodeNextRequest(e),V=new d.NodeNextResponse(t),K=u.NextRequestAdapter.fromNodeNextRequest(B,(0,u.signalFromNodeResponse)(t));try{let s=async e=>_.handle(K,z).finally(()=>{if(!e)return;e.setAttributes({"http.status_code":t.statusCode,"next.rsc":!1});let r=L.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 o=r.get("next.route");if(o){let t=`${q} ${o}`;e.setAttributes({"next.route":o,"http.route":o,"next.span_name":t}),e.updateName(t)}else e.updateName(`${q} ${R}`)}),i=!!(0,n.getRequestMeta)(e,"minimalMode"),l=async n=>{var a,l;let d=async({previousCacheEntry:r})=>{try{if(!i&&C&&U&&!r)return t.statusCode=404,t.setHeader("x-nextjs-cache","REVALIDATED"),t.end("This page could not be found"),null;let a=await s(n);e.fetchMetrics=z.renderOpts.fetchMetrics;let l=z.renderOpts.pendingWaitUntil;l&&o.waitUntil&&(o.waitUntil(l),l=void 0);let d=z.renderOpts.collectedTags;if(!j)return await (0,f.sendResponse)(B,V,a,z.renderOpts.pendingWaitUntil),null;{let e=await a.blob(),t=(0,g.toNodeOutgoingHttpHeaders)(a.headers);d&&(t[x.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>=x.INFINITE_CACHE)&&z.renderOpts.collectedRevalidate,o=void 0===z.renderOpts.collectedExpire||z.renderOpts.collectedExpire>=x.INFINITE_CACHE?void 0:z.renderOpts.collectedExpire;return{value:{kind:b.CachedRouteKind.APP_ROUTE,status:a.status,body:Buffer.from(await e.arrayBuffer()),headers:t},cacheControl:{revalidate:r,expire:o}}}}catch(t){throw(null==r?void 0:r.isStale)&&await _.onRequestError(e,t,{routerKind:"App Router",routePath:R,routeType:"route",revalidateReason:(0,p.getRevalidateReason)({isStaticGeneration:F,isOnDemandRevalidate:C})},D),t}},u=await _.handleResponse({req:e,nextConfig:N,cacheKey:M,routeKind:r.RouteKind.APP_ROUTE,isFallback:!1,prerenderManifest:I,isRoutePPREnabled:!1,isOnDemandRevalidate:C,revalidateOnlyGenerated:U,responseGenerator:d,waitUntil:o.waitUntil,isMinimalMode:i});if(!j)return null;if((null==u||null==(a=u.value)?void 0:a.kind)!==b.CachedRouteKind.APP_ROUTE)throw Object.defineProperty(Error(`Invariant: app-route received invalid cache entry ${null==u||null==(l=u.value)?void 0:l.kind}`),"__NEXT_ERROR_CODE",{value:"E701",enumerable:!1,configurable:!0});i||t.setHeader("x-nextjs-cache",C?"REVALIDATED":u.isMiss?"MISS":u.isStale?"STALE":"HIT"),A&&t.setHeader("Cache-Control","private, no-cache, no-store, max-age=0, must-revalidate");let c=(0,g.fromNodeOutgoingHttpHeaders)(u.value.headers);return i&&j||c.delete(x.NEXT_CACHE_TAGS_HEADER),!u.cacheControl||t.getHeader("Cache-Control")||c.get("Cache-Control")||c.set("Cache-Control",(0,m.getCacheControlHeader)(u.cacheControl)),await (0,f.sendResponse)(B,V,new Response(u.value.body,{headers:c,status:u.value.status||200})),null};H?await l(H):await L.withPropagatedContext(e.headers,()=>L.trace(c.BaseServerSpan.handleRequest,{spanName:`${q} ${R}`,kind:a.SpanKind.SERVER,attributes:{"http.method":q,"http.target":e.url}},l))}catch(t){if(t instanceof h.NoFallbackError||await _.onRequestError(e,t,{routerKind:"App Router",routePath:S,routeType:"route",revalidateReason:(0,p.getRevalidateReason)({isStaticGeneration:F,isOnDemandRevalidate:C})}),j)throw t;return await (0,f.sendResponse)(B,V,new Response(null,{status:500})),null}}e.s(["handler",()=>S,"patchFetch",()=>O,"routeModule",()=>_,"serverHooks",()=>k,"workAsyncStorage",()=>U,"workUnitAsyncStorage",()=>T],309679)}];

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