import { join } from "path";
import { readFileSync } from "fs";
import express from "express";
import serveStatic from "serve-static";
import nodemailer from 'nodemailer';
import shopify from "./shopify.js";
import productCreator from "./product-creator.js";
import PrivacyWebhookHandlers from "./privacy.js";
import mongoose from "mongoose";
import ejs from "ejs";
import axios from "axios";

import Shopify1 from 'shopify-api-node';

const shopify2 = new Shopify1({
    shopName: 'juli-appstore-dev.myshopify.com',
    apiKey: '95a64a43d4183d39730abe29c7985963',
    password: 'Smart',
    autoLimit: true
});
// console.log('shopify : shopify : ',shopify2);

const PORT = parseInt(
  process.env.BACKEND_PORT || process.env.PORT || "3000",
  10
);

const STATIC_PATH =
  process.env.NODE_ENV === "production"
    ? `${process.cwd()}/frontend/dist`
    : `${process.cwd()}/frontend/`;

const app = express();

// Set up Shopify authentication and webhook handling
app.get(shopify.config.auth.path, shopify.auth.begin());
app.get(
  shopify.config.auth.callbackPath,
  shopify.auth.callback(),
  shopify.redirectToShopifyOrAppRoot()
);
app.post(
  shopify.config.webhooks.path,
  shopify.processWebhooks({ webhookHandlers: PrivacyWebhookHandlers })
);

// If you are adding routes outside of the /api path, remember to
// also add a proxy rule for them in web/frontend/vite.config.js

app.use("/api/*", shopify.validateAuthenticatedSession());
app.use("/userdata/*", authenticateUser);
// app.use("/webhook/*",shopify.validateAuthenticatedSession());

app.use(express.json());

const API_KEY = 'bb59dcfcb5077f25c04559971cf7df4b';
const API_Secret_Key  = 'cdfd79f2ab8491ea872d69c38d3c6ad5';
const API_Password = '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';
const Store_Name = 'juli-appstore-dev.myshopify.com';

// 1. connection to mongoose
// 2. create schema 
// 3. models
// 4. crud operations
mongodb://localhost:27017
mongoose.connect("mongodb://localhost:27017/chocoapp")
  .then(() => {
    console.log("--- Connected to Mongoose Successfully ---");
  })
  .catch((error) => {
    console.log("--- Mongoose Can't Connect ---", error);
  })

let userSchema = new mongoose.Schema({
  username: {
    type: String,
    required: true,
  },
  useremail: {
    type: String,
    required: true,
    unique: true,
  }
});

let checkoutSchema = new mongoose.Schema({
  collection_id: {
    type: String,
    required: true,
  },
  location_id: {
    type: String,
    required: true,
  },
  email: {
    type: String,
    required: true,
  }
});

let User = mongoose.model("userdata", userSchema);
let Checkout = mongoose.model("checkoutdata", checkoutSchema);

/**
 * @param {{ query: { shop: any; }; }} req
 * @param {{ send: (arg0: string) => void; }} res
 * @param {() => void} next
 */
async function authenticateUser(req, res, next) {
  let shop = req.query.shop;
  let storeName = await shopify.config.sessionStorage.findSessionsByShop(shop);
  if (shop === storeName[0].shop) {
    next();
  } else {
    res.send("User Not Authorized");
  }
};

// Multiple data save or update
app.post("/api/savedata/multipledata", async (req, res) => {
  try {
  
  
    console.log('Multiple Data : ',req.body);
    for (const doc of req.body) {
      // Check if the document exists based on collection_id, location_id, and email
      const existingDoc = await Checkout.findOne({
        _id:doc.id
      });

      if (existingDoc) {
        // If the document exists, update it
        await Checkout.updateOne(
          { _id: existingDoc._id }, // Use the _id of the existing document for update
          { $set: doc }
        );
      } else {
        // If the document doesn't exist, insert it
        await Checkout.create(doc);
      }
    }

    console.log('Multiple Update/Insert Successfully');
    res.status(200).json({ message: "Multiple Successfully" });

  } catch (error) {
    if (error.name === 'ValidationError') {
      // Return a 400 Bad Request status code
      res.status(400).json({ error: error.message });
    }
    console.log(error.message);
  }
})

app.post("/api/removedata", async (req, res) => {
  const { _id } = req.body; 
  try {
    const deleteData = await Checkout.deleteOne({ _id });
    if (deleteData.deletedCount === 1) {
      console.log('Data deleted successfully:', deleteData);
      res.status(200).json({ message: "Delete Successfully" });
    } else {
      console.log('No document found with the specified _id:', _id);
      res.status(404).json({ error: "No document found with the specified _id" });
    }
  } catch (error) {
    console.error('Error deleting data:', error.message);
    res.status(500).json({ error: error.message });
  }
});

// 
app.post("/api/savedata", async (req, res) => {
  let { collection_id, location_id, email } = req.body;
  try {
    let createCheckout = await Checkout.create({
      collection_id: collection_id,
      location_id: location_id,
      email: email
    });
    console.log("--- Checkout Successfully ---", createCheckout);
    res.status(200).json("--- Checkout Successfully ---");
  } catch (error) {
    // if (error.code === 11000) {
    //   return res.json("--- Checkout  Already Exists ---");
    // } else {
    //   console.log(error.message);
    // }
    console.log(error.message);
  }
})

app.get("/api/getdata", async (req, res) => {
  try {
    let createCheckout = await Checkout.find();
    console.log("--- Checkout fetch Successfully ---", createCheckout);
    res.status(200).json(createCheckout);
  } catch (error) {
    console.error("Error fetching data:", error);
    res.status(500).json({ error: "Internal server error" });
  }
});


// get Collection
app.get("/api/collections/all", async (_req, res) => {
  const countData = await shopify.api.rest.CustomCollection.all({
    session: res.locals.shopify.session,
  });
  res.status(200).send(countData);
});

// get Collection
app.get("/api/collections/all", async (_req, res) => {
  const countData = await shopify.api.rest.CustomCollection.all({
    session: res.locals.shopify.session,
  });
  res.status(200).send(countData);
});

// get Location
app.get("/api/pickup/location", async (_req, res) => {
  const countData = await shopify.api.rest.Location.all({
    session: res.locals.shopify.session,
  });
  res.status(200).send(countData);
});


// Create a transporter object using SMTP transport
let transporter = nodemailer.createTransport({
  host: 'smtp.gmail.com',
  port: 58,
  service: 'gmail',
  auth: {
    user: 'smartinfo.tl5@gmail.com', // Your Gmail address
    pass: 'oyjn tkco mjsq sbzq' // Your Gmail password or app-specific password
  }
});

// Define email options

app.post('/webhook/fulfillment',  async (req, res) => {
  // console.log('fulfillment Webhook received:', req.body);
  
  res.status(200).send('fulfillment Webhook received successfully!');
});

app.post('/webhook/checkout',  async (req, res) => {
  // console.log('checkout Webhook received:', req.body);
  
  res.status(200).send('checkout Webhook received successfully!');
});

async function getLocationAndCollection(orderId) {
  try {
    const order = await shopify.order.get(orderId);
    const locationId = order.location_id;
    // const collectionId = order.source_name; // Assuming collection_id is stored in source_name
    return { locationId };
  } catch (error) {
    console.error('Error:', error.response.body);
    throw error;
  }
}

// Define a route for webhook endpoint
app.post('/webhook/order',  async (req, res) => {
  console.log('Order Webhook received:', req.body);

// Convert product_ids to string
const orderId = req.body.id;
const productIds = req.body.line_items.map(item => item.product_id.toString());
console.log('productIds : ',productIds);
let collectionDataArray = [];

try {
  for (const productId of productIds) {
    const singleCollectionUrl = `https://${API_KEY}:${API_Password}@${Store_Name}/admin/api/2024-04/collects.json?product_id=${productId}`;

    const collectionResponse = await axios.get(singleCollectionUrl);
    const collectionData = collectionResponse.data.collects;

    collectionData.forEach((data, index) => {
      console.log(`Collection ${index + 1} for Product ID ${productId}: `, data);
      collectionDataArray.push(data);
    });
  }
} catch (error) {
  console.error('Error fetching collection data:', error);
}

// Fetch location ID associated with the order
const locationResponse = await axios.get(`https://${API_KEY}:${API_Password}@${Store_Name}/admin/api/2024-04/orders/${orderId}/fulfillment_orders.json`);
const locationId = locationResponse.data.fulfillment_orders[0].assigned_location_id; // Assuming there's only one fulfillment order


console.log('locationId : ',locationId);
// Find all entries in Checkout matching collection_id and location_id
const findByCondition = await Checkout.find({
  collection_id: { $in: collectionDataArray.map(item => item.collection_id) },
  location_id: locationId
});

console.log('findByCondition : ',findByCondition);

  // End

// https://bb59dcfcb5077f25c04559971cf7df4b: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@juli-appstore-dev.myshopify.com/admin/api/2024-04/order.json
//Collection_id = // https://bb59dcfcb5077f25c04559971cf7df4b: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@juli-appstore-dev.myshopify.com/admin/api/2024-04/collects.json?product_id=9093646778652
// location_id = https://bb59dcfcb5077f25c04559971cf7df4b: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@juli-appstore-dev.myshopify.com/admin/api/2024-04/orders/5824775684380/fulfillment_orders.json
  
  // const findByCondition = await Checkout.findOne({
  //   collection_id: '470303015196',
  //   location_id: '96324780316'
  // });
  // console.log("--- findByCondition ---", findByCondition);

  // Call the function to send the email
  // sendEmail(req.body);

  res.status(200).send('Webhook received successfully!');
});

function sendEmail(data) {

  

  let mailOptions = {
    from: 'smartinfo.tl5@gmail.com', // Sender address
    to: 'siprogramming1@gmail.com', // List of recipients
    subject: 'Test Email', // Subject line
    text: 'Hello from Nodemailer!', // Plain text body
    html: `<html>
   <head>
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
     <style>
       body {
         margin: 0;
       }
       h1 a:hover {
         font-size: 30px;
         color: #333;
       }
       h1 a:active {
         font-size: 30px;
         color: #333;
       }
       h1 a:visited {
         font-size: 30px;
         color: #333;
       }
       a:hover {
         text-decoration: none;
       }
       a:active {
         text-decoration: none;
       }
       a:visited {
         text-decoration: none;
       }
       .button__text:hover {
         color: #fff;
         text-decoration: none;
       }
       .button__text:active {
         color: #fff;
         text-decoration: none;
       }
   
       .button__text:visited {
         color: #fff;
         text-decoration: none;
       }
   
       a:hover {
         color: #1990C6;
       }
   
       a:active {
         color: #1990C6;
       }
   
       a:visited {
         color: #1990C6;
       }
   
       @media (max-width: 600px) {
         .container {
           width: 94% !important;
         }
   
         .main-action-cell {
           float: none !important;
           margin-right: 0 !important;
         }
   
         .secondary-action-cell {
           text-align: center;
           width: 100%;
         }
   
         .header {
           margin-top: 20px !important;
           margin-bottom: 2px !important;
         }
   
         .shop-name__cell {
           display: block;
         }
   
         .order-number__cell {
           display: block;
           text-align: left !important;
           margin-top: 20px;
         }
   
         .po-number__cell {
           display: block;
           text-align: left !important;
           margin-top: 5px;
         }
   
         .button {
           width: 100%;
         }
   
         .or {
           margin-right: 0 !important;
         }
   
         .apple-wallet-button {
           text-align: center;
         }
   
         .customer-info__item {
           display: block;
           width: 100% !important;
         }
   
         .spacer {
           display: none;
         }
   
         .subtotal-spacer {
           display: none;
         }
   
         .return__mobile-padding {
           margin-top: 19px;
           padding-top: 19px;
         }
       }
     </style>
   </head>
   
   <body style="margin: 0;">
     <title>Thank you for your purchase!
     </title>
     <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
     <meta name="viewport" content="width=device-width">
     <table class="body"
       style="height: 100% !important; width: 100% !important; border-spacing: 0; border-collapse: collapse;">
       <tbody>
         <tr>
           <td
             style="font-family: -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, &quot;Roboto&quot;, &quot;Oxygen&quot;, &quot;Ubuntu&quot;, &quot;Cantarell&quot;, &quot;Fira Sans&quot;, &quot;Droid Sans&quot;, &quot;Helvetica Neue&quot;, sans-serif;">
             <table class="header row"
               style="width: 100%; border-spacing: 0; border-collapse: collapse; margin: 40px 0 20px;">
               <tbody>
                 <tr>
                   <td class="header__cell"
                     style="font-family: -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, &quot;Roboto&quot;, &quot;Oxygen&quot;, &quot;Ubuntu&quot;, &quot;Cantarell&quot;, &quot;Fira Sans&quot;, &quot;Droid Sans&quot;, &quot;Helvetica Neue&quot;, sans-serif;">
                     <center>
                       <table class="container"
                         style="width: 560px; text-align: left; border-spacing: 0; border-collapse: collapse; margin: 0 auto;">
                         <tbody>
                           <tr>
                             <td
                               style="font-family: -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, &quot;Roboto&quot;, &quot;Oxygen&quot;, &quot;Ubuntu&quot;, &quot;Cantarell&quot;, &quot;Fira Sans&quot;, &quot;Droid Sans&quot;, &quot;Helvetica Neue&quot;, sans-serif;">
                               <table class="row"
                                 style="width: 100%; border-spacing: 0; border-collapse: collapse;">
                                 <tbody>
                                   <tr>
                                     <td class="shop-name__cell"
                                       style="font-family: -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, &quot;Roboto&quot;, &quot;Oxygen&quot;, &quot;Ubuntu&quot;, &quot;Cantarell&quot;, &quot;Fira Sans&quot;, &quot;Droid Sans&quot;, &quot;Helvetica Neue&quot;, sans-serif;">
                                       <h1 class="shop-name__text"
                                         style="font-weight: normal; font-size: 30px; color: #333; margin: 0;">
                                         <a
                                           style="font-size: 30px; color: #333; text-decoration: none;">juli_appstore_dev</a>
                                       </h1>
                                     </td>
                                     <td
                                       style="font-family: -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, &quot;Roboto&quot;, &quot;Oxygen&quot;, &quot;Ubuntu&quot;, &quot;Cantarell&quot;, &quot;Fira Sans&quot;, &quot;Droid Sans&quot;, &quot;Helvetica Neue&quot;, sans-serif;">
                                     </td>
                                   </tr>
                                   <tr>
                                     <td class="order-number__cell"
                                       style="font-family: -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, &quot;Roboto&quot;, &quot;Oxygen&quot;, &quot;Ubuntu&quot;, &quot;Cantarell&quot;, &quot;Fira Sans&quot;, &quot;Droid Sans&quot;, &quot;Helvetica Neue&quot;, sans-serif; text-transform: uppercase; font-size: 14px; color: #999;"
                                       align="right">
                                       <span class="order-number__text"
                                         style="font-size: 16px;">
                                         Order  <%= data.id %>
                                       </span>
                                     </td>
                                   </tr>
                                 </tbody>
                               </table>
                             </td>
                           </tr>
                         </tbody>
                       </table>
                     </center>
                   </td>
                 </tr>
               </tbody>
             </table>
             <table class="row content" style="width: 100%; border-spacing: 0; border-collapse: collapse;">
               <tbody>
                 <tr>
                   <td class="content__cell"
                     style="font-family: -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, &quot;Roboto&quot;, &quot;Oxygen&quot;, &quot;Ubuntu&quot;, &quot;Cantarell&quot;, &quot;Fira Sans&quot;, &quot;Droid Sans&quot;, &quot;Helvetica Neue&quot;, sans-serif; padding-bottom: 40px; border-width: 0;">
                     <center>
                       <table class="container"
                         style="width: 560px; text-align: left; border-spacing: 0; border-collapse: collapse; margin: 0 auto;">
                         <tbody>
                           <tr>
                             <td
                               style="font-family: -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, &quot;Roboto&quot;, &quot;Oxygen&quot;, &quot;Ubuntu&quot;, &quot;Cantarell&quot;, &quot;Fira Sans&quot;, &quot;Droid Sans&quot;, &quot;Helvetica Neue&quot;, sans-serif;">
                               <h2
                                 style="font-weight: normal; font-size: 24px; margin: 0 0 10px;">
                                 Thank you for your purchase!
                               </h2>
                               <p
                                 style="color: #777; line-height: 150%; font-size: 16px; margin: 0;">
                                 We're getting your order ready to be shipped. We will notify
                                 you when it has been sent.
                               </p>
                               <table class="row actions"
                                 style="width: 100%; border-spacing: 0; border-collapse: collapse; margin-top: 20px;">
                                 <tbody>
                                   <tr>
                                     <td class="empty-line"
                                       style="font-family: -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, &quot;Roboto&quot;, &quot;Oxygen&quot;, &quot;Ubuntu&quot;, &quot;Cantarell&quot;, &quot;Fira Sans&quot;, &quot;Droid Sans&quot;, &quot;Helvetica Neue&quot;, sans-serif; line-height: 0em;">
                                       &nbsp;</td>
                                   </tr>
                                   <tr>
                                     <td class="actions__cell"
                                       style="font-family: -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, &quot;Roboto&quot;, &quot;Oxygen&quot;, &quot;Ubuntu&quot;, &quot;Cantarell&quot;, &quot;Fira Sans&quot;, &quot;Droid Sans&quot;, &quot;Helvetica Neue&quot;, sans-serif;">
                                       <table class="button main-action-cell"
                                         style="border-spacing: 0; border-collapse: collapse; float: left; margin-right: 15px;">
                                         <tbody>
                                           <tr>
                                             <td class="button__cell"
                                               style="font-family: -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, &quot;Roboto&quot;, &quot;Oxygen&quot;, &quot;Ubuntu&quot;, &quot;Cantarell&quot;, &quot;Fira Sans&quot;, &quot;Droid Sans&quot;, &quot;Helvetica Neue&quot;, sans-serif; border-radius: 4px;"
                                               align="center"
                                               bgcolor="#1990C6"><a
                                               href="<%= data.order_status_url %>"
                                                 class="button__text"
                                                 style="font-size: 16px; text-decoration: none; display: block; color: #fff; padding: 20px 25px;">View
                                                 your order</a></td>
                                           </tr>
                                         </tbody>
                                       </table>
                                       <table class="link secondary-action-cell"
                                         style="border-spacing: 0; border-collapse: collapse; margin-top: 19px;">
                                         <tbody>
                                           <tr>
                                             <td class="link__cell"
                                               style="font-family: -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, &quot;Roboto&quot;, &quot;Oxygen&quot;, &quot;Ubuntu&quot;, &quot;Cantarell&quot;, &quot;Fira Sans&quot;, &quot;Droid Sans&quot;, &quot;Helvetica Neue&quot;, sans-serif; border-radius: 4px;"
                                               align="center">or <a
                                                 style="font-size: 16px; text-decoration: none; color: #1990C6;">Visit
                                                 our store</a>
                                             </td>
                                           </tr>
                                         </tbody>
                                       </table>
                                     </td>
                                   </tr>
                                 </tbody>
                               </table>
                             </td>
                           </tr>
                         </tbody>
                       </table>
                     </center>
                   </td>
                 </tr>
               </tbody>
             </table>
             <table class="row section" style="width: 100%; border-spacing: 0; border-collapse: collapse;">
               <tbody>
                 <tr>
                   <td class="section__cell"
                     style="font-family: -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, &quot;Roboto&quot;, &quot;Oxygen&quot;, &quot;Ubuntu&quot;, &quot;Cantarell&quot;, &quot;Fira Sans&quot;, &quot;Droid Sans&quot;, &quot;Helvetica Neue&quot;, sans-serif; padding: 40px 0;">
                     <center>
                       <table class="container"
                         style="width: 560px; text-align: left; border-spacing: 0; border-collapse: collapse; margin: 0 auto;">
                         <tbody>
                           <tr>
                             <td
                               style="font-family: -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, &quot;Roboto&quot;, &quot;Oxygen&quot;, &quot;Ubuntu&quot;, &quot;Cantarell&quot;, &quot;Fira Sans&quot;, &quot;Droid Sans&quot;, &quot;Helvetica Neue&quot;, sans-serif;">
                               <h3
                                 style="font-weight: normal; font-size: 20px; margin: 0 0 25px;">
                                 Order summary</h3>
                             </td>
                           </tr>
                         </tbody>
                       </table>
                       <table class="container"
                         style="width: 560px; text-align: left; border-spacing: 0; border-collapse: collapse; margin: 0 auto;">
                         <tbody>
                           <tr>
                             <td
                               style="font-family: -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, &quot;Roboto&quot;, &quot;Oxygen&quot;, &quot;Ubuntu&quot;, &quot;Cantarell&quot;, &quot;Fira Sans&quot;, &quot;Droid Sans&quot;, &quot;Helvetica Neue&quot;, sans-serif;">
                               <table class="row"
                                 style="width: 100%; border-spacing: 0; border-collapse: collapse;">
                                 <tbody>
                                   <tr class="order-list__item" style="width: 100%;">
                                     <td class="order-list__item__cell"
                                       style="font-family: -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, &quot;Roboto&quot;, &quot;Oxygen&quot;, &quot;Ubuntu&quot;, &quot;Cantarell&quot;, &quot;Fira Sans&quot;, &quot;Droid Sans&quot;, &quot;Helvetica Neue&quot;, sans-serif; padding-bottom: 15px;">
                                       <table
                                         style="border-spacing: 0; border-collapse: collapse;">
                                         <tbody>
                                         <% if (data.line_items) { %>
                                         <% data.line_items.forEach(function(item) { %>
                                           <tr>
                                             <td
                                               style="font-family: -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, &quot;Roboto&quot;, &quot;Oxygen&quot;, &quot;Ubuntu&quot;, &quot;Cantarell&quot;, &quot;Fira Sans&quot;, &quot;Droid Sans&quot;, &quot;Helvetica Neue&quot;, sans-serif;">
                                               <img src="https://cdn.shopify.com/s/files/1/0859/8231/4780/files/rails_logo_compact_cropped.gif?v=1709786514"
                                                 align="left" width="60"
                                                 height="60"
                                                 class="order-list__product-image"
                                                 style="margin-right: 15px; border-radius: 8px; border: 1px solid #e5e5e5;">
                                             </td>
                                             <td class="order-list__product-description-cell"
                                               style="font-family: -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, &quot;Roboto&quot;, &quot;Oxygen&quot;, &quot;Ubuntu&quot;, &quot;Cantarell&quot;, &quot;Fira Sans&quot;, &quot;Droid Sans&quot;, &quot;Helvetica Neue&quot;, sans-serif; width: 100%;">
                                               <span
                                                 class="order-list__item-title"
                                                 style="font-size: 16px; font-weight: 600; line-height: 1.4; color: #555;"><%= item.name %>  <%= item.quantity %></span><br>
                                             </td>
                                             <td class="order-list__price-cell"
                                               style="font-family: -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, &quot;Roboto&quot;, &quot;Oxygen&quot;, &quot;Ubuntu&quot;, &quot;Cantarell&quot;, &quot;Fira Sans&quot;, &quot;Droid Sans&quot;, &quot;Helvetica Neue&quot;, sans-serif; white-space: nowrap;">
                                               <p class="order-list__item-price"
                                                 style="color: #555; line-height: 150%; font-size: 16px; font-weight: 600; margin: 4px 0 0 15px;"
                                                 align="right">
                                                 <%= item.quantity * item.price %>
                                               </p>
                                             </td>
                                           </tr>                                          
                                          <% }); %>

                                          <% } else { %>
                                            <li>No line items found. </li>
                                          <% } %>
                                         </tbody>
                                       </table>
                                     </td>
                                   </tr>
                                 </tbody>
                               </table>
                               <table class="row subtotal-lines"
                                 style="width: 100%; border-spacing: 0; border-collapse: collapse; margin-top: 15px; border-top-width: 1px; border-top-color: #e5e5e5; border-top-style: solid;">
                                 <tbody>
                                   <tr>
                                     <td class="subtotal-spacer"
                                       style="font-family: -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, &quot;Roboto&quot;, &quot;Oxygen&quot;, &quot;Ubuntu&quot;, &quot;Cantarell&quot;, &quot;Fira Sans&quot;, &quot;Droid Sans&quot;, &quot;Helvetica Neue&quot;, sans-serif; width: 40%;">
                                     </td>
                                     <td
                                       style="font-family: -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, &quot;Roboto&quot;, &quot;Oxygen&quot;, &quot;Ubuntu&quot;, &quot;Cantarell&quot;, &quot;Fira Sans&quot;, &quot;Droid Sans&quot;, &quot;Helvetica Neue&quot;, sans-serif;">
                                       <table class="row subtotal-table"
                                         style="width: 100%; border-spacing: 0; border-collapse: collapse; margin-top: 20px;">
                                         <tbody>
                                         
                                           <tr class="subtotal-line">
                                             <td class="subtotal-line__title"
                                               style="font-family: -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, &quot;Roboto&quot;, &quot;Oxygen&quot;, &quot;Ubuntu&quot;, &quot;Cantarell&quot;, &quot;Fira Sans&quot;, &quot;Droid Sans&quot;, &quot;Helvetica Neue&quot;, sans-serif; padding: 2px 0;">
                                               <p
                                                 style="color: #777; line-height: 1.2em; font-size: 16px; margin: 4px 0 0;">
                                                 <span
                                                   style="font-size: 16px;">Subtotal</span>
                                               </p>
                                             </td>
                                             <td class="subtotal-line__value"
                                               style="font-family: -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, &quot;Roboto&quot;, &quot;Oxygen&quot;, &quot;Ubuntu&quot;, &quot;Cantarell&quot;, &quot;Fira Sans&quot;, &quot;Droid Sans&quot;, &quot;Helvetica Neue&quot;, sans-serif; padding: 2px 0;"
                                               align="right">
                                               <strong
                                                 style="font-size: 16px; color: #555;"><%= data.subtotal_price %></strong>
                                             </td>
                                           </tr>

                                           <tr class="subtotal-line">
                                             <td class="subtotal-line__title"
                                               style="font-family: -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, &quot;Roboto&quot;, &quot;Oxygen&quot;, &quot;Ubuntu&quot;, &quot;Cantarell&quot;, &quot;Fira Sans&quot;, &quot;Droid Sans&quot;, &quot;Helvetica Neue&quot;, sans-serif; padding: 2px 0;">
                                               <p
                                                 style="color: #777; line-height: 1.2em; font-size: 16px; margin: 4px 0 0;">
                                                 <span
                                                   style="font-size: 16px;">Order
                                                   discount</span>
                                               </p>
                                             </td>
                                             <td class="subtotal-line__value"
                                               style="font-family: -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, &quot;Roboto&quot;, &quot;Oxygen&quot;, &quot;Ubuntu&quot;, &quot;Cantarell&quot;, &quot;Fira Sans&quot;, &quot;Droid Sans&quot;, &quot;Helvetica Neue&quot;, sans-serif; padding: 2px 0;"
                                               align="right">
                                               <strong
                                                 style="font-size: 16px; color: #555;"><%= data.total_discounts %></strong>
                                             </td>
                                           </tr>

                                           <tr class="subtotal-line">
                                             <td class="subtotal-line__title"
                                               style="font-family: -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, &quot;Roboto&quot;, &quot;Oxygen&quot;, &quot;Ubuntu&quot;, &quot;Cantarell&quot;, &quot;Fira Sans&quot;, &quot;Droid Sans&quot;, &quot;Helvetica Neue&quot;, sans-serif; padding: 2px 0;">
                                               <p
                                                 style="color: #777; line-height: 1.2em; font-size: 16px; margin: 4px 0 0;">
                                                 <span
                                                   class="subtotal-line__discount"
                                                   style="font-size: 16px; margin-left: 5px;">
                                                   <img src="https://cdn.shopify.com/shopifycloud/shopify/assets/themes_support/notifications/discounttag-d1f7c6d9334582b151797626a5ae244c56af0791fcd7841f21027dd44830bcc6.png"
                                                     width="18"
                                                     height="18"
                                                     class="discount-tag-icon"
                                                     style="vertical-align: middle; margin-right: 6px;">
                                                   <span
                                                     class="subtotal-line__discount-title"
                                                     style="font-size: 16px; margin-left: -4px;">ORDER5
                                                     (<%= data.total_discounts %>)</span>
                                                 </span>
                                               </p>
                                             </td>
                                           </tr>

                                           <tr class="subtotal-line">
                                             <td class="subtotal-line__title"
                                               style="font-family: -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, &quot;Roboto&quot;, &quot;Oxygen&quot;, &quot;Ubuntu&quot;, &quot;Cantarell&quot;, &quot;Fira Sans&quot;, &quot;Droid Sans&quot;, &quot;Helvetica Neue&quot;, sans-serif; padding: 2px 0;">
                                               <p
                                                 style="color: #777; line-height: 1.2em; font-size: 16px; margin: 4px 0 0;">
                                                 <span
                                                   style="font-size: 16px;">Shipping</span>
                                               </p>
                                             </td>
                                             <td class="subtotal-line__value"
                                               style="font-family: -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, &quot;Roboto&quot;, &quot;Oxygen&quot;, &quot;Ubuntu&quot;, &quot;Cantarell&quot;, &quot;Fira Sans&quot;, &quot;Droid Sans&quot;, &quot;Helvetica Neue&quot;, sans-serif; padding: 2px 0;"
                                               align="right">
                                               <strong
                                                 style="font-size: 16px; color: #555;"><%= data.total_shipping_price_set.shop_money.amount %></strong>
                                             </td>
                                           </tr>

                                      
                                           <tr class="subtotal-line">
                                             <td class="subtotal-line__title"
                                               style="font-family: -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, &quot;Roboto&quot;, &quot;Oxygen&quot;, &quot;Ubuntu&quot;, &quot;Cantarell&quot;, &quot;Fira Sans&quot;, &quot;Droid Sans&quot;, &quot;Helvetica Neue&quot;, sans-serif; padding: 2px 0;">
                                               <p
                                                 style="color: #777; line-height: 1.2em; font-size: 16px; margin: 4px 0 0;">
                                                 <span
                                                   class="subtotal-line__discount"
                                                   style="font-size: 16px; margin-left: 5px;">
                                                   <img src="https://cdn.shopify.com/shopifycloud/shopify/assets/themes_support/notifications/discounttag-d1f7c6d9334582b151797626a5ae244c56af0791fcd7841f21027dd44830bcc6.png"
                                                     width="18"
                                                     height="18"
                                                     class="discount-tag-icon"
                                                     style="vertical-align: middle; margin-right: 6px;">
                                                   <span
                                                     class="subtotal-line__discount-title"
                                                     style="font-size: 16px; margin-left: -4px;">FREESHIPPING
                                                     (-Rs. 0.00)</span>
                                                 </span>
                                               </p>
                                             </td>
                                            </tr>
   
                                           <tr class="subtotal-line">
                                             <td class="subtotal-line__title"
                                               style="font-family: -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, &quot;Roboto&quot;, &quot;Oxygen&quot;, &quot;Ubuntu&quot;, &quot;Cantarell&quot;, &quot;Fira Sans&quot;, &quot;Droid Sans&quot;, &quot;Helvetica Neue&quot;, sans-serif; padding: 2px 0;">
                                               <p
                                                 style="color: #777; line-height: 1.2em; font-size: 16px; margin: 4px 0 0;">
                                                 <span
                                                   style="font-size: 16px;">Taxes</span>
                                               </p>
                                             </td>
                                             <td class="subtotal-line__value"
                                               style="font-family: -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, &quot;Roboto&quot;, &quot;Oxygen&quot;, &quot;Ubuntu&quot;, &quot;Cantarell&quot;, &quot;Fira Sans&quot;, &quot;Droid Sans&quot;, &quot;Helvetica Neue&quot;, sans-serif; padding: 2px 0;"
                                               align="right">
                                               <strong
                                                 style="font-size: 16px; color: #555;"><%= data.total_tax %></strong>
                                             </td>
                                           </tr>

                                         </tbody>
                                       </table>
                                       <div class="payment-terms">
                                       </div>
                                       <table
                                         class="row subtotal-table subtotal-table--total"
                                         style="width: 100%; border-spacing: 0; border-collapse: collapse; margin-top: 20px; border-top-width: 2px; border-top-color: #e5e5e5; border-top-style: solid;">
                                         <tbody>
                                           <tr class="subtotal-line">
                                             <td class="subtotal-line__title"
                                               style="font-family: -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, &quot;Roboto&quot;, &quot;Oxygen&quot;, &quot;Ubuntu&quot;, &quot;Cantarell&quot;, &quot;Fira Sans&quot;, &quot;Droid Sans&quot;, &quot;Helvetica Neue&quot;, sans-serif; padding: 20px 0 0;">
                                               <p
                                                 style="color: #777; line-height: 1.2em; font-size: 16px; margin: 4px 0 0;">
                                                 <span
                                                   style="font-size: 16px;">Total</span>
                                               </p>
                                             </td>
                                             <td class="subtotal-line__value"
                                               style="font-family: -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, &quot;Roboto&quot;, &quot;Oxygen&quot;, &quot;Ubuntu&quot;, &quot;Cantarell&quot;, &quot;Fira Sans&quot;, &quot;Droid Sans&quot;, &quot;Helvetica Neue&quot;, sans-serif; padding: 20px 0 0;"
                                               align="right">
                                               <strong
                                                 style="font-size: 24px; color: #555;"><%= data.total_price %></strong>
                                             </td>
                                           </tr>
                                           <tr class="subtotal-line">
                                             <td class="subtotal-line__title"
                                               style="font-family: -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, &quot;Roboto&quot;, &quot;Oxygen&quot;, &quot;Ubuntu&quot;, &quot;Cantarell&quot;, &quot;Fira Sans&quot;, &quot;Droid Sans&quot;, &quot;Helvetica Neue&quot;, sans-serif; padding: 20px 0 0;">
                                               <p
                                                 style="color: #777; line-height: 1.2em; font-size: 16px; margin: 4px 0 0;">
                                                 <span
                                                   style="font-size: 16px;">Total
                                                   paid today</span>
                                               </p>
                                             </td>
                                             <td class="subtotal-line__value"
                                               style="font-family: -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, &quot;Roboto&quot;, &quot;Oxygen&quot;, &quot;Ubuntu&quot;, &quot;Cantarell&quot;, &quot;Fira Sans&quot;, &quot;Droid Sans&quot;, &quot;Helvetica Neue&quot;, sans-serif; padding: 20px 0 0;"
                                               align="right">
                                               <strong
                                                 style="font-size: 16px; color: #555;">Rs.
                                                 0.00</strong>
                                             </td>
                                           </tr>
                                         </tbody>
                                       </table>
                                       <p class="total-discount"
                                         style="color: #777; line-height: 1.1; font-size: 16px; margin: 10px 0 0;"
                                         align="right">
                                         You saved <span
                                           class="total-discount--amount"
                                           style="font-size: 16px; color: #555;">Rs.
                                           20.00</span>
                                       </p>
                                       <table class="row subtotal-table"
                                         style="width: 100%; border-spacing: 0; border-collapse: collapse; margin-top: 20px;">
                                         <tbody>
                                           <tr>
                                             <td colspan="2"
                                               class="subtotal-table__line"
                                               style="font-family: -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, &quot;Roboto&quot;, &quot;Oxygen&quot;, &quot;Ubuntu&quot;, &quot;Cantarell&quot;, &quot;Fira Sans&quot;, &quot;Droid Sans&quot;, &quot;Helvetica Neue&quot;, sans-serif; border-bottom-width: 1px; border-bottom-color: #e5e5e5; border-bottom-style: solid; height: 1px; padding: 0;">
                                             </td>
                                           </tr>
                                           <tr>
                                             <td colspan="2"
                                               class="subtotal-table__small-space"
                                               style="font-family: -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, &quot;Roboto&quot;, &quot;Oxygen&quot;, &quot;Ubuntu&quot;, &quot;Cantarell&quot;, &quot;Fira Sans&quot;, &quot;Droid Sans&quot;, &quot;Helvetica Neue&quot;, sans-serif; height: 10px;">
                                             </td>
                                           </tr>
                                         </tbody>
                                       </table>
                                     </td>
                                   </tr>
                                 </tbody>
                               </table>
                             </td>
                           </tr>
                         </tbody>
                       </table>
                     </center>
                   </td>
                 </tr>
               </tbody>
             </table>
             <table class="row section" style="width: 100%; border-spacing: 0; border-collapse: collapse;">
               <tbody>
                 <tr>
                   <td class="section__cell"
                     style="font-family: -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, &quot;Roboto&quot;, &quot;Oxygen&quot;, &quot;Ubuntu&quot;, &quot;Cantarell&quot;, &quot;Fira Sans&quot;, &quot;Droid Sans&quot;, &quot;Helvetica Neue&quot;, sans-serif; padding: 40px 0;">
                     <center>
                       <table class="container"
                         style="width: 560px; text-align: left; border-spacing: 0; border-collapse: collapse; margin: 0 auto;">
                         <tbody>
                           <tr>
                             <td
                               style="font-family: -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, &quot;Roboto&quot;, &quot;Oxygen&quot;, &quot;Ubuntu&quot;, &quot;Cantarell&quot;, &quot;Fira Sans&quot;, &quot;Droid Sans&quot;, &quot;Helvetica Neue&quot;, sans-serif;">
                               <h3
                                 style="font-weight: normal; font-size: 20px; margin: 0 0 25px;">
                                 Customer information</h3>
                             </td>
                           </tr>
                         </tbody>
                       </table>
                       <table class="container"
                         style="width: 560px; text-align: left; border-spacing: 0; border-collapse: collapse; margin: 0 auto;">
                         <tbody>
                           <tr>
                             <td
                               style="font-family: -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, &quot;Roboto&quot;, &quot;Oxygen&quot;, &quot;Ubuntu&quot;, &quot;Cantarell&quot;, &quot;Fira Sans&quot;, &quot;Droid Sans&quot;, &quot;Helvetica Neue&quot;, sans-serif;">
                               <table class="row"
                                 style="width: 100%; border-spacing: 0; border-collapse: collapse;">
                                 <tbody>
                                   <tr>
                                   <% if (data.shipping_address && data.shipping_address.length > 0) { %>
                                     <td class="customer-info__item"
                                       style="font-family: -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, &quot;Roboto&quot;, &quot;Oxygen&quot;, &quot;Ubuntu&quot;, &quot;Cantarell&quot;, &quot;Fira Sans&quot;, &quot;Droid Sans&quot;, &quot;Helvetica Neue&quot;, sans-serif; padding-bottom: 40px; width: 50%;"
                                       valign="top">
                                       <h4
                                         style="font-weight: 500; font-size: 16px; color: #555; margin: 0 0 5px;">
                                         Shipping address</h4>
                                       <p
                                         style="color: #777; line-height: 150%; font-size: 16px; margin: 0;">
                                         Steve Shipper<br><%= data.shipping_address.name %>
                                         <br><%= data.shipping_address.address1%><br>
                                         <%= data.shipping_address.city %> <%= data.shipping_address.zip %>
                                         <br><%= data.shipping_address.country %></p>
                                     </td>
                                    <% } %>
                                     <td class="customer-info__item"
                                       style="font-family: -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, &quot;Roboto&quot;, &quot;Oxygen&quot;, &quot;Ubuntu&quot;, &quot;Cantarell&quot;, &quot;Fira Sans&quot;, &quot;Droid Sans&quot;, &quot;Helvetica Neue&quot;, sans-serif; padding-bottom: 40px; width: 50%;"
                                       valign="top">
                                       <h4
                                         style="font-weight: 500; font-size: 16px; color: #555; margin: 0 0 5px;">
                                         Billing address</h4>
                                       <p
                                         style="color: #777; line-height: 150%; font-size: 16px; margin: 0;">
                                         <%= data.billing_address.name %><br>
                                         <%= data.billing_address.address1 %><br>
                                         <%= data.billing_address.city %> <%= data.billing_address.zip %><br>
                                         <%= data.billing_address.country %></p>
                                     </td>
                                   </tr>
                                 </tbody>
                               </table>
                            <% if (data.shipping_lines && data.shipping_lines.length > 0) { %>
                               <table class="row"
                                 style="width: 100%; border-spacing: 0; border-collapse: collapse;">
                                 <tbody>
                                   <tr>
                                   </tr>
                                   <tr>
                                     <td class="customer-info__item"
                                       style="font-family: -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, &quot;Roboto&quot;, &quot;Oxygen&quot;, &quot;Ubuntu&quot;, &quot;Cantarell&quot;, &quot;Fira Sans&quot;, &quot;Droid Sans&quot;, &quot;Helvetica Neue&quot;, sans-serif; padding-bottom: 40px; width: 50%;"
                                       valign="top">
                                       <h4
                                         style="font-weight: 500; font-size: 16px; color: #555; margin: 0 0 5px;">
                                         Shipping method</h4>
                                       <p
                                         style="color: #777; line-height: 150%; font-size: 16px; margin: 0;">
                                         <%= data.shipping_lines[0].title %>
                                       </p>
                                     </td>
                                   </tr>
                                 </tbody>
                               </table>
                            <% } %>
                             </td>
                           </tr>
                         </tbody>
                       </table>
                     </center>
                   </td>
                 </tr>
               </tbody>
             </table>
             <table class="row footer"
               style="width: 100%; border-spacing: 0; border-collapse: collapse; border-top-width: 1px; border-top-color: #e5e5e5; border-top-style: solid;">
               <tbody>
                 <tr>
                   <td class="footer__cell"
                     style="font-family: -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, &quot;Roboto&quot;, &quot;Oxygen&quot;, &quot;Ubuntu&quot;, &quot;Cantarell&quot;, &quot;Fira Sans&quot;, &quot;Droid Sans&quot;, &quot;Helvetica Neue&quot;, sans-serif; padding: 35px 0;">
                     <center>
                       <table class="container"
                         style="width: 560px; text-align: left; border-spacing: 0; border-collapse: collapse; margin: 0 auto;">
                         <tbody>
                           <tr>
                             <td
                               style="font-family: -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, &quot;Roboto&quot;, &quot;Oxygen&quot;, &quot;Ubuntu&quot;, &quot;Cantarell&quot;, &quot;Fira Sans&quot;, &quot;Droid Sans&quot;, &quot;Helvetica Neue&quot;, sans-serif;">
   
                               <p class="disclaimer__subtext"
                                 style="color: #999; line-height: 150%; font-size: 14px; margin: 0;">
                                 If you have any questions, reply to this email or contact us
                                 at <a
                                   style="font-size: 14px; text-decoration: none; color: #1990C6;">customer@smartinfosys.net</a>
                               </p>
                             </td>
                           </tr>
                         </tbody>
                       </table>
                     </center>
                   </td>
                 </tr>
               </tbody>
             </table>
             <img src="https://cdn.shopify.com/shopifycloud/shopify/assets/themes_support/notifications/spacer-1a26dfd5c56b21ac888f9f1610ef81191b571603cb207c6c0f564148473cab3c.png"
               class="spacer" height="1" style="min-width: 600px; height: 0;">
           </td>
         </tr>
       </tbody>
     </table>
   </body>
   
   </html>`
  };

  // Define the mail options
  // let mailOptions = {
  //   from: 'smartinfo.tl5@gmail.com', // Sender address
  // to: 'siprogramming1@gmail.com', // Recipient's email address
  //   subject: 'Test Email', // Subject line
  //   text: 'Hello from Nodemailer!', // Plain text body
  //   html: `
  //     <html>
  //       <body>
  //         <h1>Hello,</h1>
  //         <p>This is a test email with dynamic data:</p>
  //         <p>User: <%= user.name %></p>
  //         <p>Email: <%= user.email %></p>
  //       </body>
  //     </html>
  //   `
  // };

  // Render HTML with dynamic data
  const compiledHtml = ejs.render(mailOptions.html, { data });

  // Update mailOptions with the compiled HTML
  mailOptions.html = compiledHtml;

  // Send the email
  transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
      console.log('Error occurred:', error);
    } else {
      console.log('Email sent:', info.response);
    }
  });
}

// Define a route for webhook endpoint
app.post('/webhook', (req, res) => {
  // console.log('Webhook received:', req.body);
  // transporter.sendMail(mailOptions, (error, info) => {
  //   if (error) {
  //       return console.log(error);
  //   }
  //   console.log('Message sent: %s', info.messageId);
  // });
  // const user = {
  //   name: 'John Doe',
  //   email: 'johndoe@example.com'
  // };
  // sendEmail(user);
  res.status(200).send('Webhook received successfully!');
});

// GETTING STOREFRONT DATA
app.post("/userdata/userinfo", async (req, res) => {
  let userData = req.body;
  try {
    let createUser = await User.create({
      username: userData[0],
      useremail: userData[1],
    });
    console.log("--- User Created Successfully ---", createUser);
    res.status(200).json("--- User Created Successfully ---");
  } catch (error) {
    if (error.code === 11000) {
      return res.json("--- User Already Exists ---");
    } else {
      console.log(error.message);
    }
  }
})


// Create webhooks
app.post("/api/webhook/create", async (_req, res) => {
  console.log('External API : ');
  const webhook = new shopify.api.rest.Webhook({ session: res.locals.shopify.session });
  webhook.address = "pubsub://projectName:topicName";
  webhook.topic = "order/checkout";
  webhook.format = "json";
  // await webhook.save({
  //   update: true,
  // });
  res.status(200).send(webhook);
});

// Listout webhooks
app.get("/api/webhook/all", async (_req, res) => {
  console.log('App Full Path : ', shopify.config.auth.path);
  console.log('webhooks Path : ', shopify.config.webhooks.path);
  const webhook = await shopify.api.rest.Webhook.all({
    session: res.locals.shopify.session,
  });
  res.status(200).send(webhook);
});

// Listout single webhooks
app.get("/api/webhook/single", async (_req, res) => {
  const webhook = await shopify.api.rest.Webhook.find({
    session: res.locals.shopify.session,
    id: 4759306,
  });
  res.status(200).send(webhook);
});


app.put("/api/checkout/update", async (_req, res) => {
  // const checkout = await shopify.api.rest.Checkout.find({
  //   session: res.locals.shopify.session,
  //   token: '2834f2c3ad175b8d076544c695b20513'
  // });
  // res.status(200).send({message : 'Hello'});

  // Session is built by the OAuth process

  var checkout = await new shopify.api.rest.Checkout({ session: res.locals.shopify.session });
  checkout.token = "2834f2c3ad175b8d076544c695b20513";
  checkout.shipping_line = {
    "handle": "shopify-Free%20Shipping-0.00"
  };
  // await checkout.save({
  //   update: true,
  // });
  res.status(200).send(checkout);
});

// Reading checkout
app.get("/api/checkout/find", async (_req, res) => {
  const orderData = await shopify.api.rest.Checkout.find({
    session: res.locals.shopify.session,
    token: '2834f2c3ad175b8d076544c695b20513'
  });
  res.status(200).send(orderData);
});

// Reading Orders
app.get("/api/orders/all", async (_req, res) => {
  console.log('Session : ', res.locals.shopify.session);
  const orderData = await shopify.api.rest.Order.all({
    session: res.locals.shopify.session,
    status: "any"
  });
  res.status(200).send(orderData);
});

// Reading Collection Count
app.get("/api/collections/count", async (_req, res) => {

  console.log('Hello order Location : ');

  //   const orderId = '5817439486236'; // Replace with the actual order ID
  // const orderLocation = await shopify.api.rest.FulfillmentOrder.all({
  //   session: res.locals.shopify.session,
  //   status: "any"
  //   // token: '2834f2c3ad175b8d076544c695b20513'
  //   // id:orderId
  // })
  // console.log('orderLocation : ',orderLocation);

  // const order = await shopify.api.rest.Order.get(orderId);



  const countData = await shopify.api.rest.CustomCollection.count({
    session: res.locals.shopify.session,
  });
  res.status(200).send(countData);
});

// Reading Product Count
app.get("/api/products/count", async (_req, res) => {

  // const product = await shopify.api.rest.Product.all({
  //   session: res.locals.shopify.session,
  //   status: "any"
  // });

  // console.log('product List : ',product.data);

  // find Collection

 const locationId =  await shopify.api.rest.Fulfillment.find({
  session: res.locals.shopify.session,
    order_id: 5817464258844,
  });

  console.log('find Location List : ',locationId);

  // Add product_id
 const findCollection = await shopify.api.rest.CustomCollection.find({
  session: res.locals.shopify.session,
    ids: "9093646778652",
  });

  console.log('find Collection List : ',findCollection);

  // find product images
 const images = await shopify.api.rest.Image.find({
  session: res.locals.shopify.session,
    product_id: 9093646778652,
  });

  console.log('images List : ',images);


  const countData = await shopify.api.rest.Product.count({
    session: res.locals.shopify.session,
  });
  res.status(200).send(countData);
});

// Reading Store Name
app.get("/api/store/info", async (req, res) => {
  let storeInfo = await shopify.api.rest.Shop.all({
    session: res.locals.shopify.session,
  });
  res.status(200).send(storeInfo);
})

app.get("/api/products/create", async (_req, res) => {
  let status = 200;
  let error = null;

  try {
    await productCreator(res.locals.shopify.session);
  } catch (e) {
    console.log(`Failed to process products/create: ${e.message}`);
    status = 500;
    error = e.message;
  }
  res.status(status).send({ success: status === 200, error });
});

app.use(shopify.cspHeaders());
app.use(serveStatic(STATIC_PATH, { index: false }));

app.use("/*", shopify.ensureInstalledOnShop(), async (_req, res, _next) => {
  return res
    .status(200)
    .set("Content-Type", "text/html")
    .send(readFileSync(join(STATIC_PATH, "index.html")));
});

app.listen(PORT);
