const mongoose = require("mongoose");
const request = require('request-promise');
const Challan = mongoose.model("Challan");
const Order = mongoose.model("Orders");
const User = mongoose.model("User");
const Vendor = mongoose.model("Vendor");
const GateEntry  = mongoose.model("GateEntry");
const PurchaseOrder = mongoose.model("PurchaseOrder")
const bcrypt = require('bcryptjs')
const Adminuser = mongoose.model("Adminuser");
const Products = mongoose.model("Products");
const Category = mongoose.model("Category");
const CsvUpload = mongoose.model("CsvUpload");
// const ObjectsToCsv = require('objects-to-csv');
const WInward = mongoose.model("WInward");
const OrderPickup = mongoose.model("OrderPickup");
const WareHouse = mongoose.model("WareHouses");
const Wmsorder = mongoose.model("Wmsorder");
const Awbgenerate = mongoose.model("Awbgenerate");
const Indiaoffshelf = mongoose.model("Indiaoffshelfs")
const OrderReturn = mongoose.model("OrderReturn")
const OrderReturnAts = mongoose.model("OrderReturnAts")
const Pincode = mongoose.model("Pincode")
const NotWInward = mongoose.model("NotWInward")
const Shelflocations = mongoose.model("Shelflocations")
const TempShelflocations = mongoose.model("TempShelflocations")
const ReturnStockage = mongoose.model("ReturnStockage")
const OnshelfReturnFile = mongoose.model("OnshelfReturnFile")
// const Test = mongoose.model("Test")

const moment = require("moment-timezone")

let date_time = new Date();
let date = ("0" + date_time.getDate()).slice(-2);
let month = ("0" + (date_time.getMonth() + 1)).slice(-2);
let year = date_time.getFullYear();

let current_date = year + "-" + month + "-" + date;

const express = require('express');
const app = express();
app.use(express.static('public/' + current_date));

const { updateShopperrPriceAlgo, getMsrp } = require("../../apps/middlewares/priceAlgo");
const { userValidation } = require('../../validation')

const axios = require('axios');

const AWS = require('aws-sdk');
const _ = require('lodash');
var fs = require('fs');
const path = require('path');

const xlsx = require('xlsx');

const csv = require('csvtojson');

const { parse } = require('json2csv');

// const pdfCreator = require('pdf-creator-node');


ID = 'AKIAZQ3DPSAOW34EMAWP';    
SECRET = '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';
// The name of the bucket that you have created
const BUCKET_NAME = 'test-bucket';
const s3 = new AWS.S3({
    accessKeyId: ID,
    secretAccessKey: SECRET
});


exports.GetUploadInwardCsv = async (req, res) => {

    const page = parseInt(req.query.page)
    const limit = parseInt(req.query.limit)
    const startIndex = (page - 1) * limit

    let totalCount = await CsvUpload.countDocuments({ spId: mongoose.Types.ObjectId(req.query.id), type: 101 }).exec()
    let results = await CsvUpload.find({ spId: mongoose.Types.ObjectId(req.query.id), type: 101 }).sort({ _id: -1 }).limit(limit).skip(startIndex).exec()
    if (results.length > 0) {
        let items = (await Promise.all(results.map((csv) => {
            return (new Promise(async (resolve, reject) => {
                try {
                    let status = '';
                    if (csv.status == 0) {
                        status = 'Pending'
                    } else if (csv.status == 1) {
                        status = 'Success'
                    } else if (csv.status == 2) {
                        status = 'Processing'
                    }
                    else {
                        status = 'Fail'
                    }
                    let item = {
                        'status': status,
                        'action': csv.url,
                        'resUrl': csv.resUrl ? csv.resUrl : '#',
                        'date': csv.date ? new Date(csv.date).toLocaleString(undefined, { timeZone: 'Asia/Kolkata' }) : '',
                    }
                    resolve(item)
                } catch (err) {
                    reject(err)
                }
            }));
        })).then((data) => data).catch((err) => err));
        if (items) {
            return res.status(200).send({ 'error': 0, 'items': items, 'totalCount': totalCount })
        } else {
            return res.send({ 'error': 1, 'Response': 'Something went wrong.' })
        }
    } else {
        return res.send({ 'error': 1, 'Response': 'Something went wrong.' })
    }
};
exports.GetUploadReturnCsv = async (req, res) => {

    const page = parseInt(req.query.page)
    const limit = parseInt(req.query.limit)
    const startIndex = (page - 1) * limit

    let totalCount = await CsvUpload.countDocuments({ spId: mongoose.Types.ObjectId(req.query.id), type: 102 }).exec()
    let results = await CsvUpload.find({ spId: mongoose.Types.ObjectId(req.query.id), type: 102 }).sort({ _id: -1 }).limit(limit).skip(startIndex).exec()
    if (results.length > 0) {
        let items = (await Promise.all(results.map((csv) => {
            return (new Promise(async (resolve, reject) => {
                try {
                    let status = '';
                    if (csv.status == 0) {
                        status = 'Pending'
                    } else if (csv.status == 1) {
                        status = 'Success'
                    } else if (csv.status == 2) {
                        status = 'Processing'
                    }
                    else {
                        status = 'Fail'
                    }
                    let item = {
                        'status': status,
                        'action': csv.url,
                        'resUrl': csv.resUrl ? csv.resUrl : '#',
                        'date': csv.date ? new Date(csv.date).toLocaleString(undefined, { timeZone: 'Asia/Kolkata' }) : '',
                    }
                    resolve(item)
                } catch (err) {
                    reject(err)
                }
            }));
        })).then((data) => data).catch((err) => err));
        if (items) {
            return res.status(200).send({ 'error': 0, 'items': items, 'totalCount': totalCount })
        } else {
            return res.send({ 'error': 1, 'Response': 'Something went wrong.' })
        }
    } else {
        return res.send({ 'error': 1, 'Response': 'Something went wrong.' })
    }
};

exports.ReadCsv = async (req, res) => {

    var limit = 1;
    var csvRequest = await CsvUpload.find({ $and: [{ "status": 0 }, { "type": 101 }] }).limit(parseInt(limit)).sort({ '_id': -1 });

    if (csvRequest.length > 0) {
        let options = {
            uri: csvRequest[0].url,
            encoding: null
        };

        request(options, async function (error, response, body) {
            if (error || response.statusCode !== 200) {
                console.error("Failed to fetch CSV:", error);
            } else {
                try {
                    const workbook = xlsx.read(body, { type: 'buffer' });

                    const sheet1 = workbook.Sheets[workbook.SheetNames[0]];
                    const dataFromSheet1 = xlsx.utils.sheet_to_json(sheet1);

                    const sheet2 = workbook.Sheets[workbook.SheetNames[1]];
                    const dataFromSheet2 = xlsx.utils.sheet_to_json(sheet2);

                    // console.log("Data from Sheet 1:", dataFromSheet1);
                    // console.log("Data from Sheet 2:", dataFromSheet2);

                    // console.log(dataFromSheet2);

                } catch (e) {
                    console.error("Error processing XLS file:", e);
                }
            }
        });
    }

};

exports.UploadInwardCsv = async (req, res) => {

    
    let fileContent = req.files.file.data;
    if (fileContent) {
        // console.log("inside upload product csv")
        let d = new Date();
        let supplierId = req.body.id;
        const s3dir = "inward/" + supplierId + d.getFullYear().toString() + "/" + (d.getMonth() + 1).toString() + "/";
        let filename = makeid(6) + '_' + supplierId + '.csv';
        let fullPath = s3dir + filename;
        // console.log(fullPath);
        // return false;

        const csvUp = await CsvUpload.find({ localFile: req.files.file.name })

        if (csvUp.length > 0) {
            return res.send({ 'error': 1, 'Response': 'File already exist.' });
        }

        // console.log(req.files.file.name)
        // return false;

        let uploadres = await uploadSupplierCsv(fileContent, fullPath, supplierId, 101, req.files.file.name);
        if (uploadres == 'success') {
            // console.log("inside success")
            return res.send({ 'error': 0, 'Response': 'File uploaded Successfully.' });
        } else {
            return res.send({ 'error': 1, 'Response': 'Something went wrong.' });
        }
    } else {
        return res.send({ 'error': 1, 'Response': 'Something went wrong.' });
    }
};
exports.UploadReturnCsv = async (req, res) => {

    
    let fileContent = req.files.file.data;
    if (fileContent) {
        // console.log("inside upload product csv")
        let d = new Date();
        let supplierId = req.body.id;
        const s3dir = "return/" + supplierId + d.getFullYear().toString() + "/" + (d.getMonth() + 1).toString() + "/";
        let filename = makeid(6) + '_' + supplierId + '.csv';
        let fullPath = s3dir + filename;
        // console.log(fullPath);
        // return false;

        const csvUp = await CsvUpload.find({ localFile: req.files.file.name })

        if (csvUp.length > 0) {
            return res.send({ 'error': 1, 'Response': 'File already exist.' });
        }

        // console.log(req.files.file.name)
        // return false;

        let uploadres = await uploadSupplierCsv(fileContent, fullPath, supplierId, 102, req.files.file.name);
        if (uploadres == 'success') {
            // console.log("inside success")
            return res.send({ 'error': 0, 'Response': 'File uploaded Successfully.' });
        } else {
            return res.send({ 'error': 1, 'Response': 'Something went wrong.' });
        }
    } else {
        return res.send({ 'error': 1, 'Response': 'Something went wrong.' });
    }
};

exports.InwardList = async (req, res) => {

    const spID = req.query.spID;
    const storeDomain = req.query.store
    const page = parseInt(req.query.page)
    const limit = parseInt(req.query.limit)
    const startIndex = (page - 1) * limit
    const endIndex = page * limit
    const results = {}
    let query = {};
    if (req.query.fromDate && req.query.toDate) {
        query.created_on = {
            $gte: new Date(req.query.fromDate),
            $lt: new Date(req.query.toDate)
        }
    }

    if (req.query.text) {
        // query.inv_number = req.query.text; 

        query = {
            $or: [
                { 'cff_orderno': req.query.text },
                { inv_number: req.query.text },
                { i_orderno: req.query.text },
                { s_orderno: req.query.text },
                { sku: req.query.text }
            ]
        };
    }

    query = {"invoiceDate":{$ne:null}}

    // query.spID = spID;

    //{ spID: '6613cc084184e227e4815e4e', $or: [ { inv_number: "BL202409160482" }, { cff_orderno: "BL202409160482" }, {i_orderno:"BL202409160482"} ]}

    const orderCount = await WInward.countDocuments(query).exec();
    results.count = orderCount;
    results.startIndex = startIndex;
    if (endIndex < orderCount) {
        results.next = {
            page: page + 1,
            limit: limit
        }
    }
    if (startIndex > 0) {
        results.previous = {
            page: page - 1,
            limit: limit
        }
    }

    try {
        results.results = await WInward.find(query)
            .sort({ invoiceDate: -1 })
            .limit(limit)
            .skip(startIndex)
            .exec();
        res.send(results)
    } catch (e) {
        res.status(500).json({ message: e.message })
    }

};

exports.DataManagementList = async (req, res) => {

    const spID = req.query.spID;
    const storeDomain = req.query.store
    const page = parseInt(req.query.page)
    const limit = parseInt(req.query.limit)
    const startIndex = (page - 1) * limit
    const endIndex = page * limit
    const results = {}
    var query = {};
    

    if (req.query.text) {
        // query.inv_number = req.query.text; 

        query = {
            $or: [
                { 'cff_orderno': req.query.text },
                { inv_number: req.query.text },
                { i_orderno: req.query.text },
                { s_orderno: req.query.text },
                { sku: req.query.text }
            ]
        };
    }

    if (req.query.orderStatus) {
        if(parseInt(req.query.orderStatus)===3){
            query.order_status = parseInt(req.query.orderStatus)
            query.deleivered_date = { $ne: null }
        }else if(parseInt(req.query.orderStatus)===5){
            query.order_status = parseInt(req.query.orderStatus)
            query.return_date = { $ne: null }
        }
        else{
            query.order_status = parseInt(req.query.orderStatus)
        }
        
    }

    if (req.query.refundDateFrom) {
        query.refund_date = {
            $gte: new Date(req.query.refundDateFrom+'T00:00:00.000Z'),
            $lt: new Date(req.query.refundDateTo+'T23:59:59Z')
        }
    }

    if (req.query.orderdateFrom) {
    
        query.orderDate = {
            $gte: new Date(req.query.orderdateFrom+'T00:00:00.000Z'),
            $lt: new Date(req.query.orderdateTo+'T23:59:59Z')
        }
            
    }

    if (req.query.returnDateFrom) {
        query.return_date = {
            $gte: new Date(req.query.returnDateFrom+'T00:00:00.000Z'),
            $lt: new Date(req.query.returnDateTo+'T23:59:59Z')
        }

    }


    // console.log(query)

    // query.spID = spID;

    //{ spID: '6613cc084184e227e4815e4e', $or: [ { inv_number: "BL202409160482" }, { cff_orderno: "BL202409160482" }, {i_orderno:"BL202409160482"} ]}

    const orderCount = await WInward.countDocuments(query).exec();
    // console.log(orderCount)
    results.count = orderCount;
    results.startIndex = startIndex;
    if (endIndex < orderCount) {
        results.next = {
            page: page + 1,
            limit: limit
        }
    }
    if (startIndex > 0) {
        results.previous = {
            page: page - 1,
            limit: limit
        }
    }

    try {
        results.results = await WInward.find(query)
            .sort({ orderDate: -1 })
            .limit(limit)
            .skip(startIndex)
            .exec();
        
        res.send(results)
    } catch (e) {
        res.status(500).json({ message: e.message })
    }

};

exports.OrderPickupList = async (req, res) => {

    const page = parseInt(req.query.page)
    const limit = parseInt(req.query.limit)
    const startIndex = (page - 1) * limit
    const endIndex = page * limit
    const results = {}
    let query = {};

    if (req.query.text) {
        query.op_code = req.query.text;
    }

    const orderCount = await OrderPickup.countDocuments(query).exec();
    results.count = orderCount;
    results.startIndex = startIndex;
    if (endIndex < orderCount) {
        results.next = {
            page: page + 1,
            limit: limit
        }
    }
    if (startIndex > 0) {
        results.previous = {
            page: page - 1,
            limit: limit
        }
    }

    try {
        let OrderPickupData = await OrderPickup.find(query).sort({ op_create_date: -1 }).limit(limit).skip(startIndex);
        

        if (OrderPickupData.length > 0) {
            let orders = OrderPickupData.map(async (item) => {
                const warehouse = await WareHouse.findOne(
                    { warehouse_id: item.warehouse_id }
                ).exec();

                let map_length = item.map.length;
                
                let opm_quantity = 0;
                item.map.forEach((i) => {
                    opm_quantity += parseInt(i.opm_quantity)
                })


                var op_orders_type = '';
                var op_orders_status = '';
                if (item.op_orders_type == 0)
                    op_orders_type = "One Item per Package";
                else if (item.op_orders_type == 1)
                    op_orders_type = "Multiple Items per Package";
                else
                    op_orders_type = "-";

                if (item.op_status == 0)
                    op_orders_status = "Draft (From China)";
                else if (item.op_status == 1)
                    op_orders_status = "Completed";
                else if (item.op_status == 2)
                    op_orders_status = "Generating";
                else if (item.op_status == 3)
                    op_orders_status = "Is distribution (From China)";
                else if (item.op_status == 4)
                    op_orders_status = "Have distribution (From China)";
                else if (item.op_status == 5)
                    op_orders_status = "In the packaging (From China)";
                else if (item.op_status == 6)
                    op_orders_status = "Less goods (From China)";
                else
                    op_orders_status = "-";


                return {
                    "_id": item._id,
                    "op_code": item.op_code,
                    "op_order_cnt": map_length,
                    "op_product_cnt": opm_quantity,
                    "op_sku_cnt": item.op_sku_cnt,
                    "op_status": op_orders_status,
                    "op_orders_type": op_orders_type,
                    "op_note": item.op_note,
                    "op_create_date": item.op_create_date,
                    "warehouse_name": warehouse.warehouse_name
                };
            });

            results.result = await Promise.all(orders);

            res.send(results);
        } else {
            res.json({ message: "No warehouse found" });
        }
    } catch (error) {
        console.error("Error fetching OrderPickupData:", error);
        res.status(500).json({ error: "Internal Server Error" });
    }

};

exports.OrderMap = async (req, res) => {

    const results = {}

    let sku_qty = 0;
    try {
        return res.status(200).json(await OrderPickup.findOne({ op_code: req.params.opcode }, { map: 1, op_order_cnt: 1, op_code: 1, orders_code: 1 }
        ).then(async (data) => {

            let distinctProductIds = new Set();
            let distinctOrderCodes = new Set();
            let totalQuantity = 0;

            const mdata = data.map;

            const item_data = [];
            const batchSize = 12;

            const promises = [];

            for (let i = 0; i < mdata.length; i += batchSize) {
                const batch = mdata.slice(i, i + batchSize);
                const promise = new Promise(async (resolve) => {

                    try {
                        const batchItemData = await Promise.all(batch.map(async (item) => {

                            distinctProductIds.add(item.product_id);
                            distinctOrderCodes.add(item.orders_code);
                            totalQuantity += parseInt(item.opm_quantity);


                            const wmsData = await Wmsorder.aggregate([
                                {
                                    $match: {
                                        "orders_code": item.orders_code
                                    }
                                },
                                {
                                    $unwind: { path: "$product", preserveNullAndEmptyArrays: true }
                                },
                                {
                                    $lookup: {
                                        from: "products",
                                        localField: "product.product_sku",
                                        foreignField: "code",
                                        as: "matched_product"
                                    }
                                },
                                {
                                    $unwind: { path: "$matched_product", preserveNullAndEmptyArrays: true }
                                },
                                {
                                    $project: {
                                        "_id": 0,
                                        "imgUrl": { $arrayElemAt: ["$matched_product.imgUrl.src", 0] },
                                        "product_sku": "$product.product_sku",
                                        "orders_code": item.orders_code,
                                    }
                                }
                            ]);

                            let imageSrc = wmsData[0].imgUrl != 'null' ? wmsData[0].imgUrl : '';
                            let product_sku = wmsData[0].product_sku ? wmsData[0].product_sku : '0';

                            // const wmsData = await Wmsorder.findOne({ orders_code: item.orders_code }, { "product.product_sku": 1 });
                            // let product_sku = wmsData.product[0].product_sku ? wmsData.product[0].product_sku : '0';

                            // const imageData = await Products.findOne({ code: product_sku });
                            // let imageSrc = imageData ? imageData.imgUrl[0].src : '';

                            // return false;

                            return {
                                op_code: item.op_code,
                                orders_code: item.orders_code,
                                opm_sort: item.opm_sort,
                                opm_sortcode: item.opm_sortcode,
                                product_id: item.product_id,
                                opm_quantity: item.opm_quantity,
                                wpb_id: item.wpb_id,
                                sort_number: item.sort_number,
                                container_code: item.container_code,
                                upload_status: item.upload_status,
                                opm_orders_type: item.opm_orders_type,
                                opm_type: item.opm_type,
                                opm_exce_status: item.opm_exce_status,
                                opm_note: item.opm_note,
                                ws_code: item.ws_code,
                                user_id: item.user_id,
                                opm_status: item.opm_status,
                                opm_pda: item.opm_pda,
                                opm_create_date: item.opm_create_date,
                                opm_last_update: item.opm_last_update,
                                opm_package_update: item.opm_package_update,
                                opm_make_date: item.opm_make_date,
                                opm_is_rebinding: item.opm_is_rebinding,
                                opm_exception_quantity: item.opm_exception_quantity,
                                abo_area_code: item.abo_area_code,
                                opm_pickup_user_id: item.opm_pickup_user_id,
                                product_sku: product_sku,
                                images: process.env.S3_BUCKET_FILE_URL + "/" + imageSrc
                            };
                        }));

                        item_data.push(batchItemData);
                        resolve();

                    } catch (error) {
                        console.error("Error processing item:", error);
                        return null;
                    }
                });
                promises.push(promise);
            }

            await Promise.all(promises);

            let countDistinctProductId = distinctProductIds.size;
            let countDistinctOrdersCode = distinctOrderCodes.size;

            results.data = item_data;
            results.qty = totalQuantity;
            results.order_qty = countDistinctOrdersCode;
            results.sku_qty = countDistinctProductId;

            return results;
        }))
    } catch (err) {
        let result = { 'error': 1, 'response': err.toString() }
        return res.status(500).json(result);
    }
};

exports.OffshelfScan = async (req, res) => {

    // console.log(req.params.offshelfNumber);
    let needScanOrders = [];
    let scanedOrdersCodeArr = [];
    let ordersCodeArr = [];
    let fpNum = {};
    const results = {}

    try {
        return res.status(200).json(await OrderPickup.findOne({ op_code: req.params.offshelfNumber }, { op_order_cnt: 1, map: 1, op_status: 1 }
        ).then(async (data) => {
            if (data) {
                // console.log(data._id);
                if (data.op_status === 4) {

                    let updateObj = {
                        op_status: 1,
                        op_dispatch_date: new Date()
                    }

                    let map_length = data.map.length;
                
                    let opm_quantity = 0;
                    data.map.forEach((i) => {
                        opm_quantity += parseInt(i.opm_quantity)
                    })

                    let trackingData = [];

                    // let trackingData = [];

                    let ordersMap = await Promise.all(data.map.map(async (item) => { // Wait for all promises in map to resolve

                        if (!ordersCodeArr.includes(item.orders_code)) {
                            ordersCodeArr.push(item.orders_code);
                        }

                        if (item.opm_status == 1 && !scanedOrdersCodeArr.includes(item.orders_code)) {
                            scanedOrdersCodeArr.push(item.orders_code);
                        }

                        if ((item.opm_status == 0 || item.opm_status == 2) && !needScanOrders.includes(item.orders_code)) {
                            needScanOrders.push(item.orders_code);
                            fpNum[item.orders_code] = item.sort_number;
                            let snum = parseInt(item.sort_number, 10);
                        }
                        
                        

                    }));


                    // results.op_order_cnt = data.op_order_cnt;
                    results.op_order_cnt = map_length;
                    results.needScanOrders = needScanOrders;

                    // $data['ScanOrdersTotal'] = count($ordersCodeArr)-count($needScanOrders);
                    results.ScanOrdersTotal = ordersCodeArr.length - needScanOrders.length;
                    results.ItemsTotal = ordersCodeArr.length;
                    results.scanedOrdersCode = scanedOrdersCodeArr.length;
                    // console.log(ordersCodeArr.length)


                    // OrderPickup.updateOne({ "_id": mongoose.Types.ObjectId(data._id) }, { $set: updateObj }, { upsert: false }).exec().then(() => {

                    // })
                    // console.log(results);
                    return results;

                } else if (data.op_status === 1) {
                    let result = { 'error': 1, 'response': 'Already Scanned' }
                    return res.status(200).json(result);
                } else {
                    let result = { 'error': 1, 'response': 'No data found' }
                    return res.status(200).json(result);
                }
            } else {
                let result = { 'error': 1, 'response': 'No data found' }
                return res.status(200).json(result);
            }

        }))
    } catch (err) {
        let result = { 'error': 1, 'response': err.toString() }
        return res.status(500).json(result);
    }
};

exports.GetQuantity = async (req, res) => {

    try {
        const data = await OrderReturn.find({ $or: [ { awb: req.body.awb}, {marketplace_order_id: req.body.awb }  ] });
        
        let finalData = [];
        if(data.length>0){
            await Promise.all(data.map(async (item) => {
                
                const result = await Products.aggregate([
                {
                    $match: {
                    "code": item.sku
                    }
                },
                {
                    $project: {
                    firstImgSrc: { $arrayElemAt: ["$imgUrl.src", 0] }
                    }
                }
                ]);
                
                // console.log(process.env.IMAGE_URL+'/'+result[0].firstImgSrc)
                
                let data1 = {
                    'scan':item.type?item.type:'return',
                    'sku': item.sku,
                    'qty':item.quantity,
                    'account_name':item.account_name,
                    'imgUrl' : process.env.S3_BUCKET_FILE_URL+'/'+result[0].firstImgSrc
                }

                // console.log(data1)
    
                finalData.push(data1)
            }));

            
        }
        
        var obj = {};
        // obj["scan"] = 'return';

        // data.push(obj)

        // console.log(finalData)

        return res.status(200).json(finalData);
        

    } catch (err) {
        let result = { 'error': 1, 'response': 'Awb not found' }
        return res.status(500).json(result);
    }

};

exports.GetQuantityReturn = async (req, res) => {

    try {
        const data = await OrderReturn.find({ awb: req.body.awb });
        if (data.length > 0) {
            if (data[0].account_name == undefined || data[0].account_name == '') {
                const orderData = await Order.find({ mkpOrderId: data[0].marketplace_order_id });
                const userData = await User.find({ "_id": mongoose.Types.ObjectId(orderData[0].merchantId) });
                data[0].account_name = userData[0].fName;
            }

            var obj = {};
            obj["scan"] = 'return-rto';

            data.push(obj)

            return res.status(200).json(data);
        } else {
            const data1 = await WInward.find({ return_awb: req.body.awb });
            if (data1.length > 0) {
                if (data1[0].account_name == undefined || data1[0].account_name == '') {
                    const orderData = await Order.find({ orderSerial: data1[0].s_orderno });
                    const userData = await User.find({ "_id": mongoose.Types.ObjectId(orderData[0].merchantId) });
                    data1[0].account_name = userData[0].fName;
                }

                var obj = {};
                obj["scan"] = 'return';

                data1.push(obj)

                return res.status(200).json(data1);
            } else {
                let result = { 'error': 1, 'response': 'Awb not found' }
                return res.status(200).json(result);
            }
        }

    } catch (err) {
        let result = { 'error': 1, 'response': 'Awb not found' }
        return res.status(500).json(result);
    }

};

exports.AwbScanUpdate = async (req, res) => {

    // console.log(req.body)
    // console.log(req.body.arrayData)
    // console.log(JSON.stringify(req.body.arrayData))
    
    // console.log(typeof req.body.arrayData)
    // const arrayData = JSON.stringify(req.body.arrayData)
    // const parsedData = req.body.arrayData.map(item => JSON.parse(item));

    const parsedData = JSON.parse(req.body.arrayData);

    // parsedData.forEach(async(item) => {
    //     console.log(item)

    // })

    // console.log(typeof parsedData)
    // console.log(parsedData)

    let awb_scan = req.body.awb_scan
    // let sku = req.body.sku
    // let quantity = req.body.quantity
    // let qc_action = req.body.qc_action
    let remark = req.body.remark
    let customer_name = req.body.customer_name
    let scan_type = req.body.scan_type
    let claim = req.body.claim
    
    // let saleableQty = req.body.saleableQty
    // let nonsaleableQty = req.body.nonsaleableQty
    // let damageQty = req.body.damageQty

    // return false;
    parsedData.forEach(async(item) => {
        // console.log(item)

        let sku = item.sku
        let qc_action = item.qcAction
        let saleableQty = item.saleableQuantity
        let nonsaleableQty = item.nonSaleableQuantity
        let damageQty = item.damageQuantity

        if (qc_action == 'saleable') {
            claim = 0;
        } else {
            claim = req.body.claim
        }

        try {
        
            let skustring1 = sku.replace("STK01", "");
    
            // const refund = new Refund({
            //     return_awb: awb_scan,
            //     created_date:new Date(),
            //     sku:skustring1,
            //     quantity:quantity,
            //     action:qc_action,
            //     claim:claim,
            //     saleableQty:saleableQty,
            //     nonSaleableQty:nonsaleableQty,
            //     damageQty:damageQty,
            //     remark:remark,
            //     account_name:customer_name,
            //     type:scan_type
            //   });
            //   await refund.save();
    
            /********888888888888888888 */
            const orderReturnData = await OrderReturn.findOne({ $or: [ { "awb": awb_scan }, {marketplace_order_id: awb_scan } ], "sku" : sku });
            // console.log(orderReturnData)
            // return false;
    
            if(orderReturnData){
                
                if(orderReturnData.scan_status==1){
                    let result = { 'error': 2, 'response': 'Already Scanned' }
                    return res.status(200).json(result);
                }
                
                const returnData = {
                    // sku:skustring1,
                    // quantity:quantity,
                    action:qc_action,
                    claim:claim,
                    saleableQty:saleableQty,
                    nonSaleableQty:nonsaleableQty,
                    damageQty:damageQty,
                    remark:remark,
                    account_name:customer_name,
                    type:scan_type,
                    scan_status:1
                }
                
                // console.log(returnData)
                await OrderReturn.updateOne({ $or: [ { "awb": awb_scan }, {marketplace_order_id: awb_scan } ], "sku" : sku }, { $set: returnData }, { upsert: false });
               
                const dataAts = await OrderReturnAts.findOne({ marketplace_order_id: orderReturnData.marketplace_order_id });
                if (dataAts) { await OrderReturnAts.updateOne({ $or: [ { "awb": awb_scan }, {marketplace_order_id: awb_scan } ], "sku" : sku }, { $set: returnData }, { upsert: false }); }
				
                // console.log(returnData.marketplace_order_id)
                // console.log(orderReturnData)
                const data = await WInward.findOne({ mkpOrderId: orderReturnData.marketplace_order_id });
                if (data) {
    
                    let updateObj = {
                        remark: remark,
                        qc: qc_action,
                        claim: claim,
                        // type: scan_type,
                        returnSaleableQty:saleableQty,
                        returnNonSaleableQty:nonsaleableQty,
                        returnDamagedQty:damageQty,
                        return_awb: awb_scan,
                        received_scan_date: new Date(),
                        order_status:5
                    }
                    // console.log(updateObj)
                    await WInward.updateOne({ "_id": mongoose.Types.ObjectId(data._id) }, { $set: updateObj }, { upsert: false });
                    
                }
                
                const returnstockage = new ReturnStockage({
                    sku:skustring1,
                    action:qc_action,
                    claim:claim,
                    saleableQty:saleableQty,
                    nonSaleableQty:nonsaleableQty,
                    damageQty:damageQty,
                    remark:remark,
                    account_name:customer_name,
                    // type:scan_type,
                    scan_status:1,
                    marketplace_order_id : orderReturnData.marketplace_order_id,
                    awb:awb_scan
                  });
                await returnstockage.save();
                
                let result = { 'error': 0, 'response': 'Return updated' }
                return res.status(200).json(result);
    
            }else{
                let result = { 'error': 1, 'response': 'No data found' }
                return res.status(200).json(result);
            }
    
            /************************ */
    
            /*const returnData = {
                sku:skustring1,
                // quantity:quantity,
                action:qc_action,
                claim:claim,
                saleableQty:saleableQty,
                nonSaleableQty:nonsaleableQty,
                damageQty:damageQty,
                remark:remark,
                account_name:customer_name,
                type:scan_type
            }
    
            await OrderReturn.updateOne({ $or: [ { "awb": awb_scan }, {marketplace_order_id: req.body.awb } ] }, { $set: returnData }, { upsert: false });
            
            const data = '';
            if(scan_type=='return'){
                data = await WInward.findOne({ $or: [ { return_awb: awb_scan}, {mkpOrderId: awb_scan }  ] });
            }else{
                data = await WInward.findOne({ $or: [ { rto_awb: awb_scan}, {mkpOrderId: awb_scan }  ] });
            }*/
            
            
    
                /*if (qc_action === 'non_saleable' || qc_action === 'damage') {
                    let result = { 'error': 0, 'response': 'Return updated' }
                    return res.status(200).json(result);
                } else {
                    
                    let skustring = data.sku.replace("STK01", "");
                    const products = await Products.findOne({ "code": skustring },{"stock":1});
    
                    // let updateQty = 0;
                    // // console.log(products)
                    // if(products){
                    //     if(products.stock.in_qty){
                    //         updateQty = parseInt(products.stock.in_qty)+parseInt(quantity)
                    //     }else{
                    //         updateQty = quantity
                    //     }
                    // }else{
                    //     updateQty = quantity
                    // }
                    
                    // let updatePObj = {
                    //     // quantity: quantity,
                    //     "stock.in_qty": updateQty
    
                    // }
                    
                    // console.log(updatePObj)
    
                    // await Products.updateOne({ "code": skustring }, { $set: updatePObj }, { upsert: false });
    
                    let result = { 'error': 0, 'response': 'Return updated' }
                    return res.status(200).json(result);
                }
    
            } else {
                let result = { 'error': 1, 'response': 'No data found' }
                return res.status(200).json(result);
            }*/
        } catch (err) {
            let result = { 'error': 1, 'response': err.toString() }
            return res.status(500).json(result);
        }
    })

    // return false;
    
};

exports.AwbScanUpdateBulk = async (req, res) => {

     //console.log(req)
    //console.log(req.files.file);
    //return false;

    var fileContent = req.files.file.data
    let csv_data = await csv().fromString(fileContent.toString());
    
    try {

        let responseSent = false;

        let logs = []
        let lineNumber = 0; 
		
        await Promise.all(csv_data.map(async (item ,index) => {
            lineNumber++;

            // console.log(index+2, item.mkpOrderId)
			let saleableQuantityFinal = 0;
            let binLocation = item.binLocation;
            let sku = item.sku;
            let quantity = item.qty;
            let processby = item.inventoryBucket;
            let saleableQuantity = item.saleableQuantity?item.saleableQuantity:0;
            let nonSaleableQuantity = item.nonSaleableQuantity?item.nonSaleableQuantity:0;
            let damageQuantity = item.damageQuantity?item.damageQuantity:0;
            let remark = item.remark;
            let mkpOrderId = item.mkpOrderId;
    
            // const binLocation = item.binLocation;
            // const processby = item.processby;

            //console.log(item);return false;
    
            // return false;
            try{
                // const sku = item.sku;
                // let skustring1 = sku.replace("STK01", "");
                let skustring1 = sku;

                let receivedQty= parseInt(saleableQuantity)+parseInt(nonSaleableQuantity)+parseInt(damageQuantity)
				//console.log(parseInt(saleableQuantity));return false;
                if(quantity>=receivedQty && receivedQty>0){
                    // const orderReturn = await OrderReturn.findOne({ "sku" : skustring1, marketplace_order_id:mkpOrderId });
                    // let indexnum = parseInt(index)+2
                    // if(orderReturn){
                        // console.log(lineNumber)
                        
                        // return false;
                        // if(orderReturn.onshelfStatus==1){
                        //     // console.log(index+2, item.mkpOrderId)
                            
                        //     let err = {
                        //         'message': "Already scanned-"+skustring1+'. On line number-'+indexnum
                        //     }

                        //     logs.push(err)
                            
                        // }else{

                        //     let err1 = {
                        //         'message': "Scanned-"+skustring1+'. On line number-'+indexnum
                        //     }

                        //     logs.push(err1)
                            
                            var query = {
                                // shelf: { $regex: new RegExp(binLocation, 'i') } // 'i' for case-insensitive
                                shelf: binLocation,
                                code:sku
                            };
                    
                            const quantity = req.body.quantity;
                            
                             saleableQuantityFinal = parseInt(saleableQuantity);
                            //console.log(saleableQuantityFinal);return false;
                    
                            if(saleableQuantityFinal>0){
                                
                                const products = await Products.findOne({ code : skustring1 }, { stock:1 })
                                if(products){
                                    // console.log(skustring1+'--')
                                    let in_qty = 0;
                                    let blk_qty = 0;
                                    let updateObj = {}
                                    if(products.stock.in_qty){
                                        in_qty = products.stock.in_qty
                                    }
                        
                                    if(products.stock.blk_qty){
                                        blk_qty = products.stock.blk_qty
                                    }
                                    
                                    let qtyUpdate = [];
                                    if(processby=='India'){
                                        updateObj = {
                                            'stock.in_qty':parseInt(in_qty)+parseInt(saleableQuantityFinal)
                                        }
                                    }
                        
                                    if(processby=='Bulk'){
                                        updateObj = {
                                            'stock.blk_qty':parseInt(blk_qty)+parseInt(saleableQuantityFinal)
                                        }
                                    }
                        
                                    if(processby=='China' || processby=='China1'){
                                        updateObj = {
                                            "stock.in_qty": parseInt(in_qty)+parseInt(saleableQuantityFinal)
                                        }
                                    }
                        
                                    
                                    // console.log(updateObj)
                                    await Products.updateOne({ "code": skustring1 }, { $set: updateObj }, { upsert: false });
                                }else{
                                    console.log(skustring1)
                                }
                                
                    
                            }

                            // console.log(query)
                    
                            // return false;
                            const shelflocations = await Shelflocations.findOne(query)
                            if(shelflocations){
                            
                            let qty = parseInt(shelflocations.quantity)+parseInt(saleableQuantityFinal);
            
                            const updateObj = {
                                code: skustring1,
                                quantity: qty,
                                // qcaction: item.qcaction,
                                saleableQty:saleableQuantityFinal,
                                nonSaleableQty: nonSaleableQuantity,
                                damageQty: damageQuantity,
                                remark: remark,
                                updatedAt:new Date(),
                                beforeQty:shelflocations.quantity
                                }
                                // console.log(updateObj)
                                const shelflocation = await Shelflocations.updateOne(query, {$set: updateObj})
            
                                const insertObj = new TempShelflocations({
                                    code: skustring1,
                                    quantity: qty,
                                    // qcaction: req.body.qcaction,
                                    saleableQty: saleableQuantityFinal,
                                    nonSaleableQty: nonSaleableQuantity,
                                    damageQty: damageQuantity,
                                    remark: remark,
                                    shelf : binLocation,
                                    systemRemark:'shelflocations updated'
                                    });
                        
                                await insertObj.save();
                    
                                // return res.status(200).json({ response: "Shelflocation updated successfully!" });
                                if (!responseSent) {
                                    res.status(200).json({ error:0, response: "Shelflocation updated successfully!" });
                                    responseSent = true; // Prevent sending another response
                                }
                    
                            }else{
                                const shelflocations1 = await Shelflocations.findOne({}, {sort:1}).sort({_id:-1}).limit(1);
                    
                                const insertObj = new Shelflocations({
                                code: skustring1,
                                quantity: saleableQuantityFinal,
                                // qcaction: qcaction,
                                saleableQty: saleableQuantity,
                                nonSaleableQty: nonSaleableQuantity,
                                damageQty: damageQuantity,
                                remark: remark,
                                shelf : binLocation,
                                sort:shelflocations1.sort,
                                beforeQty:saleableQuantity
                                });
                                // console.log(insertObj)
                                await insertObj.save();
            
                                const tempObj = new TempShelflocations({
                                    code: skustring1,
                                    quantity: saleableQuantityFinal,
                                    // qcaction: qcaction,
                                    saleableQty: saleableQuantity,
                                    nonSaleableQty: nonSaleableQuantity,
                                    damageQty: damageQuantity,
                                    remark: remark,
                                    shelf : binLocation,
                                    systemRemark:'shelflocations inserted'
                                    });
                        
                                await tempObj.save();
                    
                                // return res.status(200).json({ response: "Shelflocation added successfully!" });
                                if (!responseSent) {
                                    res.status(200).json({ error:0, response: "Shelflocation added successfully!" });
                                    responseSent = true; // Prevent sending another response
                                }
                    
                            }
                            // let returnObj = {
                            //     onshelfStatus:1,
                            //     onshelfRemark:'PR'
                            // }
                            // // console.log(returnObj)
                            // const orderReturnUpdate = await OrderReturn.updateOne({"sku" : skustring1, marketplace_order_id:mkpOrderId}, {$set: returnObj})
                    //     }
                    // }else {
                        
                    //     let err2 = {
                    //         'message': "Not found-"+skustring1+'. On line number-'+indexnum
                    //     }

                    //     logs.push(err2)

                    //     // if (!responseSent) {
                    //     //     res.status(200).json({ error: 1, response: "No data found" });
                    //     //     responseSent = true; // Prevent sending another response
                    //     // }
                    // }
                    
                    
                }
    
            }catch(error){
                console.error("Error fetching gatEntries:", error);
                // return res.status(500).json({ error: "Something went wrong" });

                let err2 = {
                    'message': error
                }

                logs.push(err2)

                if (!responseSent) {
                    res.status(500).json({ error: "Something went wrong" });
                    responseSent = true; // Prevent sending another response
                }
            }
    
        }));

        let returnPath = '';
        if(logs.length>0){
                        
            let txt = logs;
            // let txtString = txt.join('\n');
            let txtString = txt
                .filter(log => log.message) // Ensure there's a message field
                .map(log => log.message)    // Extract the message field from each object
                .join('\n'); 

            let date_time = new Date();
            let date = ("0" + date_time.getDate()).slice(-2);
            let month = ("0" + (date_time.getMonth() + 1)).slice(-2);
            let year = date_time.getFullYear();

            let date_folder = year + "-" + month + "-" + date;

            // const directoryPath = 'public/labels/'+date_folder;

            const directoryPath = path.join('public', 'logs', date_folder);
            const mainDirectory = path.join('public', 'logs');
            // Ensure the folder exists, if not create it
            if (!fs.existsSync(mainDirectory)) {
                fs.mkdirSync(mainDirectory);
            }
            if (!fs.existsSync(directoryPath)) {
                fs.mkdirSync(directoryPath);
            }
            
            const fileName = 'logs.txt';
            // const filePath = path.join(folderPath, fileName);
            // const filePath = 'public/labels/'+fileName;
            const filePath = directoryPath+'/'+fileName;
            returnPath = process.env.APP_URL+'/logs/'+date_folder+'/'+fileName;


            //http://13.202.65.84:4009/logs/2025-02-03/logs.txt
            
            // Write the CSV data to the file
            fs.writeFile(filePath, txtString, (err) => {
                if (err) {
                    // console.error('Error writing file:', err);
                } else {
                    // console.log('CSV file saved successfully at:', filePath);
                }
            });
        }

        if (!responseSent) {
			
			
            res.status(200).json({ error:0, response: "CSV processed successfully!", file:returnPath });
        }
        

		

		const newFile = new OnshelfReturnFile({
		  fileName: req.files.file.name,
		  uploadedAt: moment().format(), // Current date-time
		  fileData: csv_data,
		});

		await newFile.save();
    } catch (error) {
        console.error("Error processing CSV:", error);
        res.status(500).json({ error: "Something went wrong during CSV processing" });
    }

};

exports.ConfirmBarcode = async (req,res) => {
   
    let offshelfSearch = req.body.offshelfSearch;
    let orderTotal = req.body.orderTotal;
    // let packingDimension = req.body.packingDimension;

    let sku = req.body.barcodeNumber.replace("STK01", "");
    let orders_code = '';
    let customer_order_code = '';
    let ref_tracking_number = '';
    let wms_orders_code = '';
    let wms_ship_date = '';
    let wms_orders_shipdate = '';
    let scanedOrdersCodeArr = [];
   
    const orderPickupData = await OrderPickup.find({ op_code: offshelfSearch }, {map:1});
    // console.log(orderPickupData[0].map);
    // return false;
    const mapData = orderPickupData[0].map;
    // for(const item of orderPickupData){
        let j = 0;
 
        let matchFound = false;
        let orderLabelPincode = '';
        let trackingData = [];
 
        for (const key of Object.keys(mapData)) {
            let child = mapData[key];
            // console.log(child.opm_status)
            if(child.opm_status==0){
              
                const orders = await Wmsorder.find({
                    orders_code: child.orders_code,
                    "product.product_sku": sku.trim()
                });
                // console.log(child.orders_code+'--'+sku.trim())
                if (orders.length > 0) {
                    matchFound = true;
                    
                    const wardData = await WInward.findOne({ cff_orderno: orders[0].orders_code }, { cff_orderno: 1, trackingId: 1 });
                    // console.log(orders[0].orders_code)
                    let combine_code = '';
                    combine_code = orders[0].ordership[0]?.combine_code || ''; // Handle possible nulls gracefully
                    
                    if(wardData){
                        let windata = {
                            cff_orderno: wardData.cff_orderno,
                            trackingId: wardData.trackingId,
                            combine_code: combine_code
                        }
                        let updateInward = {
							dispatch_date: new Date(),
							// packingDimension: packingDimension
						};
						// console.log(Winward[0]._id);
						await WInward.updateOne({_id: mongoose.Types.ObjectId(wardData._id)}, { $set: updateInward });
						
                        trackingData.push(windata);
                    }
                    

                    if(orders[0].orders_status==11){
                        let result = { 'error': 1, 'response': 'Refunded Order ' }
                        const filterref = {
							op_code: offshelfSearch,
							'map.op_code': offshelfSearch,
							'map.orders_code': orders[0].orders_code,
						};
			 
						
						
							const updateref = {
								$set: { 'map.$.opm_status': 2 }
							};
						
						
						//open comment
						await OrderPickup.updateOne(filterref, updateref);
						
                        return res.status(200).json(result);
                    }else{
                        // console.log(2222222)
                    }

                    // return false;
                    
                    orderLabelPincode = await Pincode.findOne({ pincode: orders[0].consignee_zip });
                    
                    const item_order = await Promise.all(orders.map(async(order) => {
                        
                        const orderCodes = await Promise.all(order.product.map(async(product) => {
                            orders_code = product.orders_code;
                            
                            return product.orders_code;
                        }) );
                        const orderShips = await Promise.all(order.ordership.map(async(ship) => {
                            ref_tracking_number = ship.ref_tracking_number;
                            return ship.orders_code;
                        }));
                        customer_order_code = order.customer_order_code;
                        wms_orders_code = order.orders_code;
                        wms_ship_date = order.ship_date;
                    }));
 
                } else {
                    // console.log(2222222+'--'+child.orders_code); // Log or process as needed
                }
 
            }
        }
        
        // console.log(wms_ship_date)

        // console.log(customer_order_code+'----'+wms_orders_code)
        // return false;
        let scan_qty = 0;
        let scan_qty_status = 0;
        if (matchFound) {
           
            let query = {
                op_code: offshelfSearch,
                orders_code: wms_orders_code
            }
 
            const checkScan = await OrderPickup.find({op_code: offshelfSearch});
            let scan_order_map = 0;
            if(checkScan.length>0){
               
                for(pickup of checkScan){
                    for(map of pickup.map){

                        if(map.opm_status === 1){
                            scan_order_map++;
                        }
 
                        if(map.orders_code===wms_orders_code && map.opm_status === 1){
                            let result = { 'error': 1, 'response': 'Already Scanned '+wms_orders_code }
                            return res.status(200).json(result);
                        }
                    }
                }
            }
           
            for(const item of orderPickupData){
                for(const child of item.map){
                    
                    if(child.orders_code==wms_orders_code){
                        // opm_quantity = child.opm_quantity
                        // console.log(child.opm_quantity+'=='+child.scan_quantity)
                        if(child.opm_quantity==child.scan_quantity){
                            // console.log(1111111)
                            scan_qty_status=1;
                        }else{
                            // console.log(222222)
                            // console.log(child.scan_quantity)
                            if(child.scan_quantity>0){
                                scan_qty = child.scan_quantity+1;
                                // console.log(4444444)
                                if(child.opm_quantity==scan_qty){
                                    // console.log(33333)
                                    scan_qty_status=1;
                                }else{
                                    scan_qty_status=0;
                                }

                            }else{
                                // console.log(555555555)
                                scan_qty = 1;
                                if(child.opm_quantity==scan_qty){
                                    // console.log(33333)
                                    scan_qty_status=1;
                                }else{
                                    scan_qty = 1;
                                    scan_qty_status=0;
                                }
                                
                                
                            }
                            
                            // scan_qty_status++;
                        }
                    }
                    
                    if(child.opm_status==1 && !scanedOrdersCodeArr.includes(child.orders_code)){
                        scanedOrdersCodeArr.push(child.orders_code);
                    }
                }
            }
            // return false;
            /*********** check product quantity ********* */
            
            // console.log(scan_qty)
            // console.log(scan_qty_status)
            // console.log(wms_orders_code)
            // return false
 
            const filter = {
                op_code: offshelfSearch,
                'map.op_code': offshelfSearch,
                'map.orders_code': wms_orders_code,
            };
 
            // const update = {
            //     $set: { 'map.$.opm_status': 1 }
            // };
            
            let update = {};
            if(scan_qty_status==1){
                update = {
                    $set: { 'map.$.opm_status': 1, 'map.$.scan_quantity': scan_qty }
                };
            }else{
                update = {
                    $set: { 'map.$.scan_quantity': scan_qty }
                };
            }

			
			
            // console.log(update)
            // return false;
            //opm_quantity
            
            //open comment
            await OrderPickup.updateOne(filter, update);
 
            let pdfFile = customer_order_code+'__'+ref_tracking_number+'.pdf';
            // let url = 'https://logistics.shopperr.in/img/shiprocket/BL202405021822__77053547771.pdf';

            // console.log(pdfFile)
            // return false;

            //wms_ship_date
            // console.log(wms_ship_date)

            // if(moment(wms_ship_date, 'YYYY-MM-DD',true) <= moment('2024-12-16', 'YYYY-MM-DD')){
            //     console.log("if");
            //     urlPrint = process.env.LOGISTICS_URL2;
            // } else {
            //     console.log("else");
            //     urlPrint = process.env.LOGISTICS_URL;
            // }

            // console.log(urlPrint)
            // return false;

            // let url = process.env.LOGISTICS_URL+'/img/'+process.env.SHIPPING_METHOD+'/'+pdfFile;
            // let url = urlPrint+'/img/'+process.env.SHIPPING_METHOD+'/'+pdfFile;
            // console.log(ref_tracking_number)
            const awbgenerate = await Awbgenerate.findOne({AWBNo: ref_tracking_number}, {label:1})
  
            // console.log(awbgenerate)
            
            let inpost = 0;
            let pdfBuffer = '';
            let axiosStatus = 0;
            let pdfFile_inpost = '';

            if(awbgenerate){
                try{
                    const response = await axios({
                        url: 'http:'+awbgenerate.label,
                        method: 'GET',
                        responseType: 'arraybuffer'
                    });
                
                    pdfBuffer = response.data;
                    // console.log(pdfBuffer)

                }catch(err){
                    // console.log(err)
                    if(err!=''){
                        axiosStatus = err.response.status;
                    }
                }
            }else{
                axiosStatus = 404
            }
            // return false;

            let date_time = new Date();
            let date = ("0" + date_time.getDate()).slice(-2);
            let month = ("0" + (date_time.getMonth() + 1)).slice(-2);
            let year = date_time.getFullYear();
            let hours = date_time.getHours();
            let minutes = date_time.getMinutes();
            let seconds = date_time.getSeconds();

            let date_folder = year + "-" + month + "-" + date;

            // const directoryPath = 'public/labels/'+date_folder;

            const directoryPath = path.join('public', 'labels', date_folder);

            if (!fs.existsSync(directoryPath)) {
                fs.mkdirSync(directoryPath, { recursive: true });
            }

            if(axiosStatus==404){
                // console.log('INPOST')
                inpost = 1;

                const wmsorders = await Wmsorder.find({ customer_order_code: customer_order_code }, {ordership:1});
                if(wmsorders.length>0){
                    wmsorders[0].ordership.forEach(async (wms) => {
                        // let pdfFile_url = `http://labels.sfcservice.com/order/print/index/?printType=1&ismerge=1&isIE=0&orderCodeList=${wms.tracking_number}`;
				        let pdfFile_url = `http://labels.sfcservice.com/order/print/index/?printType=1&ismerge=1&isIE=0&orderCodeList=${wms.tracking_number}&print_type=pdf`;	
                        // console.log(pdfFile_url)
                        // let pdfFile_url = `http://labels.sfcservice.com/order/print/index/?orderCodeList=${wms.tracking_number}&printType=1&isPrintDeclare=1&declare=0&ismerge=1&print_type=pdf&final_label=1`;
                        // console.log('pdfFile_inpost')
                        const response = await axios({
                            url: pdfFile_url,
                            method: 'GET',
                            responseType: 'arraybuffer'
                        });
                       
                        pdfBuffer = response.data;

                        // let date_time = new Date();
                        // let date = ("0" + date_time.getDate()).slice(-2);
                        // let month = ("0" + (date_time.getMonth() + 1)).slice(-2);
                        // let year = date_time.getFullYear();
                        // let hours = date_time.getHours();
                        // let minutes = date_time.getMinutes();
                        // let seconds = date_time.getSeconds();
            
                        // let date_folder = year + "-" + month + "-" + date;
            
                        // const directoryPath = 'public/'+date_folder;
            
                        if (!fs.existsSync(directoryPath)) {
                            // If it doesn't exist, create the directory
                            fs.mkdirSync(directoryPath);
            
                            // console.log(`Directory '${directoryPath}' created.`);
                        } else {
                            // console.log(`Directory '${directoryPath}' already exists.`);
                        }
            
                        fs.writeFile('public/labels/'+date_folder+"/"+pdfFile, pdfBuffer, err => {
                            if (err) {
                            // console.error(err);
                            } else {
                            //   console.log('file written successfully');
                            }
                        });

                        // pdfFile_inpost = process.env.APP_URL+'/'+ date_folder+'/'+ pdfFile
                    })
                }
            }


            let pdfFile_url = '';
            if(inpost==0){
                // let date_time = new Date();
                // let date = ("0" + date_time.getDate()).slice(-2);
                // let month = ("0" + (date_time.getMonth() + 1)).slice(-2);
                // let year = date_time.getFullYear();
                // let hours = date_time.getHours();
                // let minutes = date_time.getMinutes();
                // let seconds = date_time.getSeconds();
    
                // let date_folder = year + "-" + month + "-" + date;
    
                // const directoryPath = 'public/'+date_folder;
    
                if (!fs.existsSync(directoryPath)) {
                    // If it doesn't exist, create the directory
                    fs.mkdirSync(directoryPath);
    
                    // console.log(`Directory '${directoryPath}' created.`);
                } else {
                    // console.log(`Directory '${directoryPath}' already exists.`);
                }
    
                fs.writeFile('public/labels/'+date_folder+"/"+pdfFile, pdfBuffer, err => {
                    if (err) {
                    // console.error(err);
                    } else {
                    //   console.log('file written successfully');
                    }
                });

                // pdfFile_url = process.env.APP_URL+'/'+ date_folder+'/'+ pdfFile
                pdfFile_url = process.env.APP_URL+'/'+ date_folder+'/'+ pdfFile

            }else{
                // pdfFile_url = pdfFile_inpost


            }

            pdfFile_url = process.env.APP_URL+'/labels/'+ date_folder+'/'+ pdfFile

            // console.log(pdfFile_url)
            // return false;
 
            scanedOrdersCodeArr.push(wms_orders_code);
            //   console.log(scanedOrdersCodeArr)
 
            if(scanedOrdersCodeArr.length==orderTotal){
               
                // console.log(scanedOrdersCodeArr.length+'=='+orderTotal)
                let updateObj = {
                    op_status: 1,
                    last_update: new Date()
                };
               
                await OrderPickup.updateOne({op_code: offshelfSearch}, { $set: updateObj });
            }
           
            if(orderPickupData.length==0){
 
                let result = { 'error': 1, 'response': 'Order not found' }
                return res.status(500).json(result);
            }
            else{
            //    console.log(customer_order_code)
                const Winward = await WInward.find({ i_orderno:customer_order_code, cff_orderno:wms_orders_code });
                // const Winward = await WInward.find({ cff_orderno:customer_order_code, i_orderno:wms_orders_code });
                // const Winward = await WInward.find({ cff_orderno:"WSTK012404216260", i_orderno:"BL202404215095" });
                if(Winward.length>0){
                    // console.log(Winward[0]._id);
               
                    let updateInward = {
                        order_status: 1,
                        last_update: new Date(),
                        dispatch_date: new Date(),
                        // packingDimension: packingDimension
                    };
                    // console.log(Winward[0]._id);
                    await WInward.updateOne({_id: mongoose.Types.ObjectId(Winward[0]._id)}, { $set: updateInward });

                    // let updateOrder = {
                    //     packingDimension: packingDimension
                    // };
                    // await Order.updateOne({orderSerial: Winward[0].s_orderno}, { $set: updateOrder });
                }
                var pinMsg = "";
                var pin =0;
                if(orderLabelPincode){
                    pinMsg = 'Order to Maharashatra cannot pack with Plastic bag(include any packing materail contains plastic ). Pls pack with Carton, Parper bag,cloth bag.!';
                    pin = 1;
                }
               
                let result = { 'error': 0, 'product_sku': sku, 'orders_code': orders_code, 'customer_order_code':customer_order_code, 'ref_tracking_number':ref_tracking_number, 'offshelf':offshelfSearch, 'pdfFile': pdfFile, 'wms_orders_code':wms_orders_code, 'scanedOrdersCode':scanedOrdersCodeArr.length, 'pin':pin, 'pinmsg':pinMsg, 'trackingData':trackingData }
                return res.status(200).json(result);
            }
        } else {
            let result = { 'error': 1, 'response': 'Not found' };
            return res.status(200).json(result);
        }
 
};


exports.unlinkPdf = async (req, res) => {

    try {
        let pdfFile = customer_order_code + '__' + ref_tracking_number + '.pdf';
        // let url = 'https://logistics.shopperr.in/img/shiprocket/BL202405021822__77053547771.pdf';
        let url = process.env.LOGISTICS_URL + '/img/' + process.env.SHIPPING_METHOD + '/' + pdfFile;

        const response = await axios({
            url: url,
            method: 'GET',
            responseType: 'arraybuffer'
        });

        const pdfBuffer = response.data;

        return res.status(200).json(result);
    } catch (error) {
        let result = { 'error': 1, 'message': error };
        return res.status(200).json(result);
    }

};

exports.rePrint = async (req, res) => {

    try {
        
        // let packingDimension = req.body.packingDimension;
        
        var wstk = req.body.ordersCode;
        var query = {};
        query = {
            $or: [
                { orders_code: wstk },
                { "ordership.ref_tracking_number": wstk },
            ]
        };
        // console.log(query)
        let urlPrint = '';
        const orderLabelData = await Wmsorder.findOne(query);
        // console.log(orderLabelData);
        // return false;
       // console.log(moment(orderLabelData.ship_date, 'YYYY-MM-DD',true),moment('2024-12-16', 'YYYY-MM-DD'));
        // if(moment(orderLabelData.ship_date, 'YYYY-MM-DD',true) <= moment('2024-12-16', 'YYYY-MM-DD')){
		// 	console.log("if");
		// 	urlPrint = process.env.LOGISTICS_URL2;
		// } else {
		// 	console.log("else");
		// 	urlPrint = process.env.LOGISTICS_URL;
		// }
        let pdfBuffer = '';
        let axiosStatus = '';
        let pdfFile  = '';
        let orderLabelPincode = {};
        if(!orderLabelData){
            // console.log("ifiiiiiiiiiiiiiiiii");
            const awbgenerate = await Awbgenerate.findOne({AWBNo: wstk}, {label:1, Order_id:1, AWBNo:1, pincode:1})
            // orderLabelPincode = awbgenerate.pincode
            
            orderLabelPincode = awbgenerate
            orderLabelPincode = await Pincode.findOne({ pincode: orderLabelPincode.pincode });

            pdfFile = awbgenerate.Order_id + '__' + awbgenerate.AWBNo + '.pdf';
            // console.log('http:'+awbgenerate.label)
            try{
                const response = await axios({
                    url: 'http:'+awbgenerate.label,
                    method: 'GET',
                    responseType: 'arraybuffer'
                });
                
                pdfBuffer = response.data;
                
            }catch(err){
                // console.log(err)
                if(err!=''){
                    axiosStatus = err.response.status;
                }
            }
        } else {
            // console.log("---------------------");
            orderLabelPincode = await Pincode.findOne({ pincode: orderLabelData.consignee_zip });
            pdfFile = orderLabelData.customer_order_code + '__' + orderLabelData.ordership[0].ref_tracking_number + '.pdf';
            // let url = urlPrint + '/img/' + process.env.SHIPPING_METHOD + '/' + pdfFile;
            const awbgenerate = await Awbgenerate.findOne({AWBNo: orderLabelData.ordership[0].ref_tracking_number}, {label:1})
            // console.log('http:'+awbgenerate.label)
            if(awbgenerate){
                try{
                    const response = await axios({
                        url: 'http:'+awbgenerate.label,
                        method: 'GET',
                        responseType: 'arraybuffer'
                    });
                    
                    pdfBuffer = response.data;
                    
                }catch(err){
                    // console.log(err)
                    if(err!=''){
                        axiosStatus = err.response.status;
                    }
                }
            }else{
                axiosStatus = 404;
                console.log('axiosStatus')
                console.log(axiosStatus)
                // return;
            }
            
        }
        
        // console.log(axiosStatus)
        // return false;

        let date_time = new Date();
        let date = ("0" + date_time.getDate()).slice(-2);
        let month = ("0" + (date_time.getMonth() + 1)).slice(-2);
        let year = date_time.getFullYear();
        let hours = date_time.getHours();
        let minutes = date_time.getMinutes();
        let seconds = date_time.getSeconds();

        let date_folder = year + "-" + month + "-" + date;

        const directoryPath = 'public/reprint/' + date_folder;
        
        if (!fs.existsSync(directoryPath)) {
            fs.mkdirSync(directoryPath, { recursive: true });
        }

        // if (!fs.existsSync(directoryPath)) {
        //     // If it doesn't exist, create the directory
        //     fs.mkdirSync(directoryPath);

        //     // console.log(`Directory '${directoryPath}' created.`);
        // } else {
        //     // console.log(`Directory '${directoryPath}' already exists.`);
        // }
        
        fs.writeFile('public/reprint/' + date_folder + "/" + pdfFile, pdfBuffer, err => {
            if (err) {
                // console.error(err);
            } else {
                //   console.log('file written successfully');
            }
        });

        if(axiosStatus==404){
            // console.log('INPOST')
            orderLabelPincode = await Pincode.findOne({ pincode: orderLabelData.consignee_zip });
			let pdfFile = orderLabelData.customer_order_code + '__' + orderLabelData.ordership[0].ref_tracking_number + '.pdf';
			let url = process.env.LOGISTICS_URL + '/img/' + process.env.SHIPPING_METHOD + '/' + pdfFile;
			let pdfBuffer = '';
			let axiosStatus = '';
            // console.log(url)
			try{
				// console.log(11111111)
                const response = await axios({
					url: url,
					method: 'GET',
					responseType: 'arraybuffer'
				});
				
				pdfBuffer = response.data;
				
			}catch(err){
				// console.log(err)
				if(err!=''){
					axiosStatus = err.response.status;
				}
			}

			if(axiosStatus==404){
				inpost = 1;
				let pdfFile_url = `http://labels.sfcservice.com/order/print/index/?printType=1&ismerge=1&isIE=0&orderCodeList=${orderLabelData.ordership[0].tracking_number}&print_type=pdf`;	
				// let pdfFile_url = `http://labels.sfcservice.com/order/print/index/?orderCodeList=${orderLabelData.ordership[0].ref_tracking_number}&printType=1&isPrintDeclare=1&declare=0&ismerge=1&print_type=pdf&final_label=1`;
				console.log(pdfFile_url)
                
				const response = await axios({
					url: pdfFile_url,
					method: 'GET',
					responseType: 'arraybuffer'
				});
				
				pdfBuffer = response.data;

                //  console.log(response.data)

                let date_time = new Date();
                let date = ("0" + date_time.getDate()).slice(-2);
                let month = ("0" + (date_time.getMonth() + 1)).slice(-2);
                let year = date_time.getFullYear();
                
                let date_folder = year + "-" + month + "-" + date;

                const directoryPath = 'public/reprint/' + date_folder;

                console.log(directoryPath,pdfFile)
                
                if (!fs.existsSync(directoryPath)) {
                    fs.mkdirSync(directoryPath, { recursive: true });
                }
                

				// if (!fs.existsSync(directoryPath)) {
				// 	// If it doesn't exist, create the directory
				// 	fs.mkdirSync(directoryPath);

				// 	// console.log(`Directory '${directoryPath}' created.`);
				// } else {
				// 	// console.log(`Directory '${directoryPath}' already exists.`);
				// }

				fs.writeFile('public/reprint/'+date_folder+"/"+pdfFile, pdfBuffer, err => {
					if (err) {
					 console.error(err);
					} else {
					  console.log('file written successfully');
					}
				});
			}

            // console.log(444444)

            
        }
        // console.log(55555555)
        // return false;
        // console.log(pdfBuffer)
        // const pdfBuffer = response.data;

        // return false;
        
        
        // console.log(orderLabelData.customer_order_code)
        if(orderLabelData){
            const Winward = await WInward.find({ i_orderno: orderLabelData.customer_order_code });
            // const Winward = await WInward.find({ cff_orderno:customer_order_code, i_orderno:wms_orders_code });
            // const Winward = await WInward.find({ cff_orderno:"WSTK012404216260", i_orderno:"BL202404215095" });
            // console.log(Winward)
            if (Winward.length > 0) {
                // console.log(Winward[0]._id);

                let updateInward = {
                    order_status: 1,
                    last_update: new Date(),
                    dispatch_date: new Date(),
                    // packingDimension: packingDimension
                };
                // console.log(Winward[0]._id);
                // console.log(updateInward)
                await WInward.updateOne({ _id: mongoose.Types.ObjectId(Winward[0]._id) }, { $set: updateInward });

                // let updateOrder = {
                //     packingDimension: packingDimension
                // };
                
                // await Order.updateOne({orderSerial: Winward[0].s_orderno}, { $set: updateOrder });

            }
        }
        
        var pinMsg = "";
        var pin = 0;
        console.log(orderLabelPincode);
        if (orderLabelPincode) {
			
            pinMsg = 'Order to Maharashatra cannot pack with Plastic bag(include any packing materail contains plastic ). Pls pack with Carton, Parper bag,cloth bag.!';
            pin = 1;
        }
        let result = { 'pin': pin, 'pinmsg': pinMsg, pdfFile: pdfFile };
        return res.status(200).json(result);
    } catch (error) {
        let result = { 'error': 2, 'message': error };
        return res.status(200).json(result);
    }

};

exports.rePrintIndia = async (req, res) => {

    try {
        
        // let packingDimension = req.body.packingDimension;
        
        var wstk = req.body.ordersCode;
        var query = {};
        query = {
            $or: [
                { AWBNo: wstk },
                {Order_id: wstk}
            ]
        };
        let urlPrint = '';
        const orderLabelData = await Awbgenerate.findOne(query);
        
        if(moment(orderLabelData.response_date, 'YYYY-MM-DD',true) <= moment('2024-12-16', 'YYYY-MM-DD')){
			// console.log("if");
			urlPrint = process.env.LOGISTICS_URL2;
		} else {
			// console.log("else");
			urlPrint = process.env.LOGISTICS_URL;
		}
        const orderLabelPincode = await Pincode.findOne({ pincode: orderLabelData.consignee_zip });
        let pdfFile = orderLabelData.Order_id + '__' + orderLabelData.AWBNo + '.pdf';
        let url = urlPrint + '/img/' + process.env.SHIPPING_METHOD + '/' + pdfFile;
        let pdfBuffer = '';
        let axiosStatus = '';

        try{
            const response = await axios({
                url: url,
                method: 'GET',
                responseType: 'arraybuffer'
            });
            
            pdfBuffer = response.data;
            
        }catch(err){
            // console.log(err)
            if(err!=''){
                axiosStatus = err.response.status;
            }
        }

        if(axiosStatus==404){
            // console.log('INPOST')
            const orderLabelPincode = await Pincode.findOne({ pincode: orderLabelData.consignee_zip });
			let pdfFile = orderLabelData.Order_id + '__' + orderLabelData.AWBNo + '.pdf';
			let url = process.env.LOGISTICS_URL2 + '/img/' + process.env.SHIPPING_METHOD + '/' + pdfFile;
			let pdfBuffer = '';
			let axiosStatus = '';

			try{
				const response = await axios({
					url: url,
					method: 'GET',
					responseType: 'arraybuffer'
				});
				
				pdfBuffer = response.data;
				
			}catch(err){
				// console.log(err)
				if(err!=''){
					axiosStatus = err.response.status;
				}
			}
			
			if(axiosStatus==404){
				inpost = 1;
					
				let pdfFile_url = `http://labels.sfcservice.com/order/print/index/?orderCodeList=${orderLabelData.ordership[0].ref_tracking_number}&printType=1&isPrintDeclare=1&declare=0&ismerge=1&print_type=pdf&final_label=1`;
				//  console.log(pdfFile_url)
				const response = await axios({
					url: pdfFile_url,
					method: 'GET',
					responseType: 'arraybuffer'
				});
				
				pdfBuffer = response.data;

				if (!fs.existsSync(directoryPath)) {
					// If it doesn't exist, create the directory
					fs.mkdirSync(directoryPath);

					// console.log(`Directory '${directoryPath}' created.`);
				} else {
					// console.log(`Directory '${directoryPath}' already exists.`);
				}

				fs.writeFile('public/labels/'+date_folder+"/"+pdfFile, pdfBuffer, err => {
					if (err) {
					// console.error(err);
					} else {
					//   console.log('file written successfully');
					}
				});
			}
            
        }

        // const pdfBuffer = response.data;
        
        let date_time = new Date();
        let date = ("0" + date_time.getDate()).slice(-2);
        let month = ("0" + (date_time.getMonth() + 1)).slice(-2);
        let year = date_time.getFullYear();
        let hours = date_time.getHours();
        let minutes = date_time.getMinutes();
        let seconds = date_time.getSeconds();

        let date_folder = year + "-" + month + "-" + date;

        const directoryPath = 'public/reprint/' + date_folder;
        
        if (!fs.existsSync(directoryPath)) {
            fs.mkdirSync(directoryPath, { recursive: true });
        }

        // if (!fs.existsSync(directoryPath)) {
        //     // If it doesn't exist, create the directory
        //     fs.mkdirSync(directoryPath);

        //     // console.log(`Directory '${directoryPath}' created.`);
        // } else {
        //     // console.log(`Directory '${directoryPath}' already exists.`);
        // }

        fs.writeFile('public/reprint/' + date_folder + "/" + pdfFile, pdfBuffer, err => {
            if (err) {
                // console.error(err);
            } else {
                //   console.log('file written successfully');
            }
        });
        // console.log(orderLabelData.customer_order_code)
        const Winward = await WInward.find({ trackingId: orderLabelData.AWBNo });
        // const Winward = await WInward.find({ cff_orderno:customer_order_code, i_orderno:wms_orders_code });
        // const Winward = await WInward.find({ cff_orderno:"WSTK012404216260", i_orderno:"BL202404215095" });
        // console.log(Winward)
        if (Winward.length > 0) {
            // console.log(Winward[0]._id);

            let updateInward = {
                order_status: 1,
                last_update: new Date(),
                dispatch_date: new Date(),
                // packingDimension: packingDimension
            };
            // console.log(Winward[0]._id);
            // console.log(updateInward)
            await WInward.updateOne({ _id: mongoose.Types.ObjectId(Winward[0]._id) }, { $set: updateInward });

            // let updateOrder = {
            //     packingDimension: packingDimension
            // };
            
            // await Order.updateOne({orderSerial: Winward[0].s_orderno}, { $set: updateOrder });

        }
        var pinMsg = "";
        var pin = 0;
        console.log(orderLabelPincode);
        if (orderLabelPincode) {
			console.log("inside if"+JSON.stringify(orderLabelPincode));
            pinMsg = 'Order to Maharashatra cannot pack with Plastic bag(include any packing materail contains plastic ). Pls pack with Carton, Parper bag,cloth bag.!';
            pin = 1;
        }
        let result = { 'pin': pin, 'pinmsg': pinMsg, pdfFile: pdfFile };
        return res.status(200).json(result);
    } catch (error) {
        let result = { 'error': 2, 'message': error };
        return res.status(200).json(result);
    }

};

exports.IndiaOffshelfScan = async (req,res) => {
    
	// console.log(req.params.offshelfNumber); 
    let needScanOrders = [];
    let scanedOrdersCodeArr = [];
    let ordersCodeArr = [];
    let fpNum = {};
    const results = {}

    try{
		return res.status(200).json(await Indiaoffshelf.findOne({ shelfNumber : req.params.offshelfNumber }
		).then(async(data) => {
            if(data){
                // console.log(data._id);
                // if(data.op_status===0){
                    
                    let totalCount = await Indiaoffshelf.countDocuments({ shelfNumber : req.params.offshelfNumber }).exec()
                    let totalCountScan = await Indiaoffshelf.countDocuments({ shelfNumber : req.params.offshelfNumber, op_status:1 }).exec()

                    results.op_order_cnt = totalCount;

                    results.ItemsTotal = totalCount;
                    results.scanedOrdersCode = totalCountScan;
                    
                    // console.log(totalCount)

                    const scanqtydata = await Indiaoffshelf.aggregate([
                        {
                            $match: {
                                shelfNumber: req.params.offshelfNumber
                            }
                        },
                        {"$group" : {_id:"$shelfNumber", qtyTotal: { $sum: "$quantity" }, scanTotal: { $sum: "$scanQuantity" }}}
                    ]);

                    // console.log(scanqtydata[0].qtyTotal)

                    const qtyTotal = scanqtydata[0].qtyTotal
                    const scanTotal = scanqtydata[0].scanTotal

                    if(qtyTotal==scanTotal){
                        let result = {'error' : 1 , 'response' : 'Already Scanned' }
                        return res.status(200).json(result);
                    }

                    const scanqty = await Indiaoffshelf.aggregate([
                        {
                          $match: {
                            shelfNumber: req.params.offshelfNumber // Match the shelfNumber
                          }
                        },
                        {
                          $group: {
                            _id: "$shelfNumber", // Group by shelfNumber
                            scanTotal: { $sum: "$scanQuantity" } // Sum the scanQuantity
                          }
                        }
                      ]);

                    // console.log(scanqty[0].scanTotal)
                    results.scanedQty = scanqty[0].scanTotal;
                    
                    return results;

                /*}else if(data.op_status===1){
                    let result = {'error' : 1 , 'response' : 'Already Scanned' }
                    return res.status(200).json(result);
                }else{
                    let result = {'error' : 1 , 'response' : 'No data found' }
                    return res.status(200).json(result);
                }*/
            }else{
                let result = {'error' : 1 , 'response' : 'No data found' }
                return res.status(200).json(result);
            }
            
		}))
	} catch (err) {
        let result = {'error' : 1 , 'response' : err.toString() }
        return res.status(500).json(result);
    }
};

exports.IndiaOffshelfList = async (req, res) => {
    const page = parseInt(req.query.page)
    const limit = parseInt(req.query.limit)
    const startIndex = (page - 1) * limit
    const endIndex = page * limit
    const results = {}
    let  query ={  };
    
    let orderCountData = [];
    if(req.query.text){
        // query.shelfNumber = req.query.text;

        orderCountData = await Indiaoffshelf.aggregate([
            {
                $match: {
                    shelfNumber: req.query.text
                }
            },
            {
                "$group": {
                    _id: "$shelfNumber", // Group by shelfNumber
                }
            },
            {
                "$count": "totalResults" // Count the number of grouped results
            }
        ]);
    }else{
        orderCountData = await Indiaoffshelf.aggregate([
            {
                "$group": {
                    _id: "$shelfNumber", // Group by shelfNumber
                }
            },
            {
                "$count": "totalResults" // Count the number of grouped results
            }
        ]);
    }

    // const orderCount = await Indiaoffshelf.countDocuments(query).exec();

    if(orderCountData.length>0){

        const orderCount = orderCountData[0].totalResults;
        // console.log(orderCount[0].totalResults); // This will give you the total number of results
        
        results.count= orderCount;
        results.startIndex= startIndex;
        if (endIndex < orderCount) {
            results.next = {
            page: page + 1,
            limit: limit
            }
        }
        if (startIndex > 0) {
            results.previous = {
            page: page - 1,
            limit: limit
            }
        }
        // console.log(query)
        try {
            // let OrderPickupData = await Indiaoffshelf.find(query).sort({createdDate:-1}).limit(limit).skip(startIndex);

            let scanqty = [];
            if(req.query.text){
                scanqty = await Indiaoffshelf.aggregate([
                    {
                        $match: {
                            shelfNumber: req.query.text
                        }
                    },
                    {"$group" : {_id:"$shelfNumber", createdDate:{ $first: "$createdDate"}, op_status:{ $first: "$op_status"}, shelfCount:{$sum:1}, qtyTotal: { $sum: "$quantity" }, scanTotal: { $sum: "$scanQuantity" }}}
                ]).sort({createdDate:-1}).limit(limit).skip(startIndex); 
            }else{
                scanqty = await Indiaoffshelf.aggregate([
                    {"$group" : {_id:"$shelfNumber", createdDate:{ $first: "$createdDate"}, op_status:{ $first: "$op_status"}, shelfCount:{$sum:1}, qtyTotal: { $sum: "$quantity" }, scanTotal: { $sum: "$scanQuantity" }}}
                ]).sort({createdDate:-1}).limit(limit).skip(startIndex);
            }

            if (scanqty.length > 0) {
                let orders = scanqty.map(async (item) => {
                
                    return {
                        "shelfNumber": item._id,
                        "op_order_cnt": item.shelfCount,
                        "op_qty_cnt": item.qtyTotal,
                        "op_scan_cnt": item.scanTotal,
                        "op_status": item.op_status,
                        "op_create_date": item.createdDate,
                    };

                });
            
                results.result = await Promise.all(orders);
                
                res.send(results);

            } else {
                res.json({ message: "No data found" });
            }
        } catch (error) {
            console.error("Error fetching OrderPickupData:", error);
            res.status(500).json({ error: "Internal Server Error" });
        }  
    }else{
        res.status(200).json({ error: "Offshelf list empty" });
    }
};

exports.IndiaConfirmBarcode = async (req,res) => {
    
    let offshelfSearch = req.body.offshelfSearch;
    let orderTotal = req.body.orderTotal;
    // let packingDimension = req.body.packingDimension;
    
    const orderPickupData = await Indiaoffshelf.find({ shelfNumber:offshelfSearch, sku: req.body.barcodeNumber, op_status:0 });

    
    // for(const item of orderPickupData){
        let j = 0;

        let matchFound = false;

        if(orderPickupData.length>0){
            let updatePerformed = false; // Flag to track if an update has been made

            for (const item of orderPickupData) {
                if (updatePerformed) break; // Exit the loop if an update has already been performed

                let scanQuantity = 0;
                let update = {};

                const ref_tracking_number = item.trackingNumber
                const orderSerial = item.orderSerial

                if (item.quantity !== item.scanQuantity) {
                    scanQuantity = item.scanQuantity + 1;

                    if (scanQuantity === item.quantity) {
                        update = {
                            $set: { 'op_status': 1, 'scanQuantity': scanQuantity }
                        };
                    } else {
                        update = {
                            $set: { 'scanQuantity': scanQuantity }
                        };
                    }

                    const filter = {
                        _id: mongoose.Types.ObjectId(item._id),
                    };

                    await Indiaoffshelf.updateOne(filter, update);

                    updatePerformed = true; // Set the flag to true after the update

                    if(moment(item.createdDate, 'YYYY-MM-DD',true) <= moment('2024-12-16', 'YYYY-MM-DD')){
                        // console.log("if");
                        urlPrint = process.env.LOGISTICS_URL2;
                    } else {
                        // console.log("else");
                        urlPrint = process.env.LOGISTICS_URL;
                    }

                    // console.log(urlPrint)
                    // return false;

                    let pdfFile = orderSerial+'__'+ref_tracking_number+'.pdf';
                    // let url = 'https://logistics.shopperr.in/img/shiprocket/BL202405021822__77053547771.pdf';
                    // let url = process.env.LOGISTICS_URL+'/img/'+process.env.SHIPPING_METHOD+'/'+pdfFile;
                    let url = urlPrint+'/img/'+process.env.SHIPPING_METHOD+'/'+pdfFile;

                    const awbgenerate = await Awbgenerate.findOne({AWBNo: ref_tracking_number}, {label:1})

                    // console.log(awbgenerate.label)

                    // console.log(url);
                    // return false;
                    const response = await axios({
                        url: 'http:'+awbgenerate.label,
                        method: 'GET',
                        responseType: 'arraybuffer'
                    });
                    
                    const pdfBuffer = response.data;

                    let date_time = new Date();
                    let date = ("0" + date_time.getDate()).slice(-2);
                    let month = ("0" + (date_time.getMonth() + 1)).slice(-2);
                    let year = date_time.getFullYear();
                    

                    let date_folder = year + "-" + month + "-" + date;

                    const directoryPath = 'public/labels/'+date_folder;

                    if (!fs.existsSync(directoryPath)) {
                        // If it doesn't exist, create the directory
                        fs.mkdirSync(directoryPath);

                        // console.log(`Directory '${directoryPath}' created.`);
                    } else {
                        // console.log(`Directory '${directoryPath}' already exists.`);
                    }

                    fs.writeFile('public/labels/'+date_folder+"/"+pdfFile, pdfBuffer, err => {
                        if (err) {
                        // console.error(err);
                        } else {
                        //   console.log('file written successfully');
                        }
                    });

                    let totalCountScan = await Indiaoffshelf.countDocuments({ shelfNumber:offshelfSearch, sku: req.body.barcodeNumber, op_status:1 }).exec()
                    
                    const scanqty = await Indiaoffshelf.aggregate([
                        {
                          $match: {
                            shelfNumber: offshelfSearch,
                            sku: req.body.barcodeNumber
                          }
                        },
                        {
                          $group: {
                            _id: "$shelfNumber", // Group by shelfNumber
                            scanTotal: { $sum: "$scanQuantity" } // Sum the scanQuantity
                          }
                        }
                      ]);

                    // console.log(scanqty[0].scanTotal)
                    // results.scanedQty = scanqty[0].scanTotal;

                    // console.log(orderSerial)

                    const Winward = await WInward.find({ s_orderno:orderSerial });
                    
                    if(Winward.length>0){
                        // console.log(Winward[0]._id);
                
                        let updateInward = {
                            order_status: 1,
                            last_update: new Date(),
                            dispatch_date: new Date(),
                            // packingDimension: packingDimension
                        };
                        // console.log(Winward[0]._id);
                        await WInward.updateOne({_id: mongoose.Types.ObjectId(Winward[0]._id)}, { $set: updateInward });

                        // let updateOrder = {
                        //     packingDimension: packingDimension
                        // };
                        // await Order.updateOne({orderSerial: Winward[0].s_orderno}, { $set: updateOrder });
                    
                    }
                    
                    let result = { 'error': 0, 'pdfFile': pdfFile, scanedOrdersCode : totalCountScan, scanedQty : scanqty[0].scanTotal }
                    return res.status(200).json(result);
                }

                    
            }
        }else{
                const orderPickupData1 = await Indiaoffshelf.countDocuments({ shelfNumber:offshelfSearch, sku: req.body.barcodeNumber });

                const scanqty1 = await Indiaoffshelf.aggregate([
                    {
                      $match: {
                        shelfNumber: offshelfSearch,
                        sku: req.body.barcodeNumber,
                        op_status:1
                      }
                    },
                    {
                      $group: {
                        _id: "$shelfNumber", // Group by shelfNumber
                        statusTotal: { $sum: "$op_status" } // Sum the scanQuantity
                      }
                    }
                  ]);
              
                if(orderPickupData1===scanqty1[0].statusTotal){
                    let result = { 'error': 1, 'response': 'Already Scanned' }
                    return res.status(200).json(result);
                }else{
                    let result = { 'error': 1, 'response': 'Offshelf not found' }
                    return res.status(200).json(result);
                }
            
                
            }


        // }else{
        //     let result = { 'error': 1, 'response': 'Order not found' }
        //     return res.status(500).json(result);
        // }

        

        // return false;

        // console.log(customer_order_code+'----'+wms_orders_code)
        // return false;
        
        /*if (matchFound) {
            
            // let query = {
            //     op_code: offshelfSearch,
            //     orders_code: wms_orders_code
            // }

            // const checkScan = await OrderPickup.find({op_code: offshelfSearch});
            // let scan_order_map = 0;
            // if(checkScan.length>0){
                
            //     for(pickup of checkScan){
            //         for(map of pickup.map){
                        
            //             if(map.opm_status === 1){
            //                 scan_order_map++;
            //             }

            //             if(map.orders_code===wms_orders_code && map.opm_status === 1){
            //                 let result = { 'error': 1, 'response': 'Already Scanned '+wms_orders_code }
            //                 return res.status(200).json(result);
            //             }
            //         }
            //     }
            // }
           
            // for(const item of orderPickupData){
            //     for(const child of item.map){
            //         if(child.opm_status==1 && !scanedOrdersCodeArr.includes(child.orders_code)){
            //             scanedOrdersCodeArr.push(child.orders_code);
            //         }
            //     }
            // }

            // const filter = {
            //     op_code: offshelfSearch,
            //     'map.op_code': offshelfSearch,
            //     'map.orders_code': wms_orders_code
            // };

            // const update = {
            //     $set: { 'map.$.opm_status': 1 }
            // };

            // await OrderPickup.updateOne(filter, update);

            
        } else {
            let result = { 'error': 1, 'response': 'Not found' };
            return res.status(200).json(result);
        }*/

};

exports.offshelfPrintData = async (req, res) => {

    const results = {}
    
    let sku_qty = 0;
    try{
		return res.status(200).json(await Indiaoffshelf.find({ shelfNumber : req.params.offshelf, shelflocation: {$ne : ""} }
		).then(async (data) => {
            
            // let distinctProductSkus = new Set();
            let distinctProductSkus = 0;
            let distinctOrderCodes = new Set();
            let totalQuantity = 0;

            
            const mdata = data;

            const item_data = [];
            const batchSize = 12;

            const promises = [];

            // console.log(mdata.length)
            distinctProductSkus = mdata.length;

            const uniqueSku = await Indiaoffshelf.distinct('sku', {shelfNumber : req.params.offshelf});
            // const uniqueSku = await Indiaoffshelf.find({shelfNumber : req.params.offshelf});
            // console.log(uniqueSku);
            // return false;
            const skuCount = uniqueSku.length;
            
            
            for (let i = 0; i < mdata.length; i += batchSize) {
                const batch = mdata.slice(i, i + batchSize);
                const promise = new Promise(async (resolve) => {
                    
                    try {
                        const batchItemData = await Promise.all(batch.map(async (item) => {
                            
                            // distinctProductSkus.add(item.sku);
                            distinctOrderCodes.add(item.shelfNumber);
                            totalQuantity += parseInt(item.quantity);

                            let sku = item.sku.replace("STK01", "");
                            
                            const productData = await Products.find({code:sku},{"imgUrl.src":1, code:1})
                            // console.log('sku'+sku+'-----')
                            // console.log(productData[0].imgUrl[0].src)
                            // return false;

                            let imageSrc = '';
                            if (productData && productData.length > 0 && productData[0].imgUrl) {
                                imageSrc = productData[0].imgUrl[0].src !='null' ? productData[0].imgUrl[0].src : '';
                            }
                            
                            // let product_sku = productData[0].product_sku ? productData[0].product_sku : '0';

                            return {
                                shelfNumber: item.shelflocation,
                                opm_sort: item.opm_sort,
                                opm_quantity: item.quantity,
                                opm_status: item.op_status,
                                opm_create_date: item.createdDate,
                                opm_package_update: item.opm_package_update,
                                shelflocation: item.shelflocation,
                                product_sku: item.sku,
                                orderSerial: item.orderSerial,
                                images:process.env.S3_BUCKET_FILE_URL+"/"+imageSrc,
                                bin:item.bin?item.bin:''
                            };
                        }));
                        // console.log(batchItemData)
                        item_data.push(batchItemData);
                        resolve();

                    } catch (error) {
                        console.error("Error processing item:", error);
                        return null;
                    }
                });
                promises.push(promise);
            }

            await Promise.all(promises);

            // let countDistinctProductId = distinctProductSkus;
            let countDistinctOrdersCode = distinctProductSkus;

            results.data = item_data;
            results.qty = totalQuantity;
            results.order_qty = countDistinctOrdersCode;
            results.sku_qty = skuCount;
            
            return results;
		}))
	} catch (err) {
        let result = {'error' : 1 , 'response' : err.toString() }
        return res.status(500).json(result);
    }
};

exports.ReturnAwbScanUpdate = async (req, res) => {
    let awb_scan = req.body.awb_scan
    let sku = req.body.sku
    let quantity = req.body.quantity
    let qc_action = req.body.qc_action
    let remark = req.body.remark
    let customer_name = req.body.customer_name
    let scan_type = req.body.scan_type

    if (qc_action == 'saleable') {
        claim = 0;
    } else {
        claim = req.body.claim
    }

    try {
        const data = await WInward.findOne({ rto_awb: awb_scan });

        if (data) {

            let updateObj = {
                remark: remark,
                qc: qc_action,
                claim: claim,
                type: scan_type
            }

            await WInward.updateOne({ "_id": mongoose.Types.ObjectId(data._id) }, { $set: updateObj }, { upsert: false });

            if (qc_action === 'non_saleable') {
                let result = { 'error': 0, 'response': 'Return updated' }
                return res.status(200).json(result);
            } else {
                let updatePObj = {
                    quantity: quantity,
                    "stock.in_qty": quantity

                }
                let skustring = data.sku.replace("STK01", "");

                await Products.updateOne({ "code": skustring }, { $set: updatePObj }, { upsert: false });

                let result = { 'error': 0, 'response': 'Return updated' }
                return res.status(200).json(result);
            }

        } else {
            let result = { 'error': 1, 'response': 'No data found' }
            return res.status(200).json(result);
        }
    } catch (err) {
        let result = { 'error': 1, 'response': err.toString() }
        return res.status(500).json(result);
    }


};

exports.IndiaOffshelfDownload = async (req, res) => {
 
    
    try {
        const shelfNumber = req.query.shelfNumber;
        const data = await Indiaoffshelf.find({ shelfNumber : shelfNumber } );
        // console.log(data)
        // return false;

        let distinctProductSkus = 0;
        let distinctOrderCodes = new Set();
        let totalQuantity = 0;
        
        const mdata = data;

        const item_data = [];
        const batchSize = 12;

        const promises = [];

        // console.log(mdata.length)
        distinctProductSkus = mdata.length;

        const uniqueSku = await Indiaoffshelf.distinct('sku', {shelfNumber : shelfNumber});
        const skuCount = uniqueSku.length;

        let orderData = await Promise.all(mdata.map(async (item) => {
            distinctOrderCodes.add(item.shelfNumber);
            totalQuantity += parseInt(item.quantity);
        
            let sku = item.sku.replace("STK01", "");
            // const productData = await Products.find({ code: sku }, { "imgUrl.src": 1, code: 1 });
        
            // let imageSrc = productData[0]?.imgUrl[0]?.src !== 'null' ? productData[0].imgUrl[0].src : '';
            // let product_sku = productData[0]?.product_sku || '0';
        
            let batchItemData = {
                'Shelf Number': item.shelfNumber,
                'Shelf Location': item.bin?item.bin:item.shelflocation,
                'Order Serial': item.orderSerial,
                'Product Barcode': item.sku,
                // 'Image': `${process.env.S3_BUCKET_FILE_URL}/${imageSrc}`,
                'Quantity': item.quantity,
                'Order Status': item.op_status==1?'Scanned':'Not Scanned',
                // opm_sort: item.opm_sort,
                // opm_create_date: item.createdDate,
                // opm_package_update: item.opm_package_update,
                // shelflocation: item.shelflocation,
                
            };
        
            item_data.push(batchItemData);
        }));

        // console.log(item_data)

        // return false;
        // await Promise.all(promises);

        // let countDistinctOrdersCode = distinctProductSkus;

        // results.data = item_data;
        // results.qty = totalQuantity;
        // results.order_qty = countDistinctOrdersCode;
        // results.sku_qty = skuCount;

        ///////////////////////////////////////
        
        // let fileContent = req.files.file.data;

        let d = new Date();
        let supplierId = req.query.id;
        // let supplierId = '6613cc084184e227e4815e4e';
        const s3dir = "indiaoffshelf/" + supplierId + d.getFullYear().toString() + "/" + (d.getMonth() + 1).toString() + "/";
        // console.log(s3dir)
        let filename = makeid(6) + '_' + supplierId + '.xlsx';
        let fullPath = s3dir + filename;
        // console.log(fullPath);
        // return false;

        const excelBuffer = generateExcelFile(item_data);
        // console.log(excelBuffer)

        // return false;
        var status = await uploadExcel(excelBuffer, s3dir + filename).then(async () => {
            var url = process.env.S3_BUCKET_FILE_URL
            url =  url + '/' + fullPath 
            // console.log(url)
            let result = { 'error': 0, 'message': url };
            return res.status(200).json(result);
        });


        /*let uploadres = await uploadSupplierCsv(fileContent, fullPath, supplierId, 101, req.files.file.name);
        if (uploadres == 'success') {
            // console.log("inside success")
            return res.send({ 'error': 0, 'Response': 'File uploaded Successfully.' });
        } else {
            return res.send({ 'error': 1, 'Response': 'Something went wrong.' });
        }*/


        // let result = { 'error': 0, 'message': 'error' };
        // return res.status(200).json(result);
    } catch (error) {
        let result = { 'error': 1, 'message': error };
        return res.status(200).json(result);
    }

};


exports.UploadRefundCsv = async (req, res) => {
    try {
        var fileContent = req.files.file.data;
        let csv_data = await csv().fromString(fileContent.toString());

        let successCount = 0;
        let errorCount = 0;

        for (const item of csv_data) {
            try {
                let obj = {
                    rStatus: 'RD',
                    oStatus: "OC"
                };

                // Convert RefundDate properly
                const dateStr = item.RefundDate;
                //const formattedRefundDate = moment.tz(dateStr, "DD-MM-YYYY HH:mm", "Asia/Kolkata").toISOString();
                const formattedRefundDate = new Date(dateStr);

                // Find existing order
                const existingOrder = await Order.findOne({ mkpOrderId: item.mkpOrderId });

                if (existingOrder) {
                    const updatedOrder = await Order.findOneAndUpdate(
                        { mkpOrderId: item.mkpOrderId },
                        { $set: obj },
                        { new: true }
                    );

                    const winward = await WInward.findOne({ mkpOrderId: item.mkpOrderId });

                    if (winward) {
                        let winwardUpdateObj = {};
                        if (!winward.dispatch_date) {
                            winwardUpdateObj = {
                                order_status: 11,
                                refund_date: formattedRefundDate,
                                cancel_before_dispatch: formattedRefundDate,
                                refund_reason: item.refund_reason
                                ,
                            };
                        } else {
                            winwardUpdateObj = {
                                order_status: 9,
                                refund_date: formattedRefundDate,
                                refund_reason: item.refund_reason,
                            };
                        }

                        await WInward.findOneAndUpdate(
                            { mkpOrderId: item.mkpOrderId },
                            { $set: winwardUpdateObj }
                        );

                        // Update WMS order if `winward` exists
                        if (winward && winward.cff_orderno) {
                            await Wmsorder.findOneAndUpdate(
                                { orders_code: winward.cff_orderno },
                                { $set: { orders_status: 11, refund_date: formattedRefundDate } }
                            );
                        }
                    } 
                    successCount++;
                } else {
                    console.log(`No existing order found for OrderId: ${item.mkpOrderId}`);
                    errorCount++;
                }
            } catch (err) {
                console.error("Error processing item:", err);
                errorCount++;
            }
        }

        // Send response after processing all records
        res.status(200).json({ error: 0, message: 'Refund status updated successfully', success: successCount, failed: errorCount });

    } catch (error) {
        console.error("Upload error:", error);
        res.status(500).json({ error: 1, message: 'Internal server error', details: error.message });
    }
};


exports.GetShelfLocation = async (req, res) => {
    let searchLocation = req.body.searchLocation;
 
    var query = {
        shelf: { $regex: new RegExp(searchLocation, 'i') } // 'i' for case-insensitive
    };

    // console.log(query)
    let data = [];
    const shelflocation = await Shelflocations.find(query, {shelf:1});
    if(shelflocation.length>0){
        
        let obj = [];

        shelflocation.forEach((item) => {
            obj = {
                id: item._id,
                name: item.shelf
            }
            data.push(obj)
        })
        
        
        let result = { 'error': 0, 'message': data };
        return res.status(200).json(result);
    }else{
        let result = { 'error': 1, 'message': 'No data found' };
        return res.status(200).json(result);
    }
}


const generateExcelFile = (data) => {
    const worksheet = xlsx.utils.json_to_sheet(data);
    const workbook = xlsx.utils.book_new();
    xlsx.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
  
    // Write the workbook to a buffer
    const buffer = xlsx.write(workbook, { bookType: 'xlsx', type: 'buffer' });
    return buffer;
  };

async function uploadSupplierCsv(fileContent, path, Id, csvtype, file_name) {
    let supplierId = Id;
    await uploadExcel(fileContent, path)
    var url = process.env.S3_BUCKET_FILE_URL;
    const csvUpload = await new CsvUpload({
        type: csvtype,
        cond: [{ 'supplier_id': supplierId }],
        spId: mongoose.Types.ObjectId(supplierId),
        url: url + '/' + path,
        date: new Date(),
        localFile: file_name
    });
    try {
        const saveProduct = await csvUpload.save();
        return 'success';
    } catch (err) {
        return 'error';
    }
}
function makeid(length) {
    var result = '';
    var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    var charactersLength = characters.length;
    for (var i = 0; i < length; i++) {
        result += characters.charAt(Math.floor(Math.random() * charactersLength));
    }
    return result;
}
async function uploadExcel(file, key) {
    const params = {
        Bucket: process.env.S3_FILE_BUCKET,
        Key: key,
        Body: file
    };

    s3.upload(params, async function (err, data) {
        if (err) {
            throw err;
        }
        else {

        }
    });
};

exports.OrderOpCodeList = async (req, res) => {
    try {
        const combineCode = req.params.combineCode;
        const orders = await Wmsorder.find(
            { "ordership.combine_code": combineCode },
            { "orders_code": 1, "_id": 0 }
        );
        if (orders.length === 0) {

            return res.status(404).send("No orders found for the given combine_code.");
        }
        const ordersCodeList = orders.map(order => order.orders_code);

        const opCodes = await OrderPickup.find(
            { "map.orders_code": { $in: ordersCodeList } },
            { "op_code": 1, "_id": 0 }
        );
        if (opCodes.length === 0) {

            return res.status(404).send("No op_codes found for the given orders_code.");
        }

        return res.status(200).send(opCodes);
    } catch (error) {   
        return res.status(500).send("An error occurred while fetching op_codes.");
    }
};

exports.ProductChallan = async(req,res) =>{
const barcode = req.params.code
try {
    const product = await Products.findOne({ code: barcode })
    if(!product){
        return res.status(400).json({error: 'Product not found'})
    }
    res.json({
        Code: product.code,   
        name: product.name,
        quantity: product.quantity   
    })
} catch (error) {
    res.status(500).json({ error: 'Server error' });
}
}    


exports.SaveChallan = async (req, res) => {
    try {
      const { challanNumber, name, address, productDetails } = req.body;
      const newChallan = new Challan({
        challanNumber,
        name,
        address,
        productDetails,
      });
      await newChallan.save();
      res.status(201).json({ message: "Challan saved successfully!" });
    } catch (error) {
      console.error("Error saving challan:", error);
      res.status(500).json({ error: "Error saving challan" });
    }
  }

  exports.ProductChallan = async (req, res) => {
    const barcode = req.params.code
    try {
        const product = await Products.findOne({ code: barcode })
        if (!product) {
            return res.status(400).json({ error: 'Product not found' })
        }
        res.json({
            Code: product.code,
            name: product.name,
            quantity: product.quantity
        })
    } catch (error) {
        res.status(500).json({ error: 'Server error' });
    }
}

exports.AddVendor = async (req, res) => {
    try {
        const { name, email, address, city, state, postalCode, gst, bankName, beneficiaryName, accountNumber, phoneNumber, origin } = req.body;

        const newVendor = new Vendor({ name, email, address, city, state, postalCode, gst, bankName, beneficiaryName, accountNumber, phoneNumber, origin, });
        await newVendor.save()
        res.status(201).json({ message: 'Vendor created successfully' });
    } catch (error) {
         console.error("Error creating vendor:", error);
        res.status(400).json({ error: "Error on Creationg Vendor" });
    }
};

exports.getVendors = async (req, res) => {
    try {
        const vendors = await Vendor.find();      
        res.status(200).json({ vendors });
    } catch (error) {
        console.error("Error fetching vendors:", error);
        res.status(500).json({ error: "Error fetching vendors" });
    }
};


exports.AddGateEntry = async (req, res) => {
    const { courier, box, vehical, vehicleName } = req.body;
 
    if (!courier || !box || !vehical || !vehicleName) {
      return res.status(400).json({ message: "All fields are required" });
    }
  
    try {
      const gateEntry = new GateEntry({
        courier,
        box,  
        vehicleName, 
        vehical,
      });
      const savedGateEntry = await gateEntry.save();
      res.status(201).json({ message: "Gate Entry Created Successfully", data: savedGateEntry });
    } catch (err) {
      res.status(500).json({ message: "Error creating gate entry", error: err.message });
    }
  };

  exports.addPurchaseOrder = async (req, res) => {
    try {
      const { vendor, orderId, marketId, hsn, sku, quantity, rate, tax, netAmount } = req.body;
  
      if (!vendor || !orderId || !marketId || !hsn || !sku || !quantity || !rate || !tax || !netAmount) {
        return res.status(400).json({ response: "Please provide all required fields." });
      }
  
      const newOrder = new PurchaseOrder({
        vendor,
        orderId,
        marketId,
        hsn,
        sku,
        quantity,
        rate,
        tax,
        netAmount,
      });
  
      await newOrder.save();
      res.status(200).json({ response: "Purchase order added successfully!" });
    } catch (error) {
      console.error("Error adding purchase order:", error);
      res.status(500).json({ response: "Server error. Please try again later." });
    }
  };

  exports.UnscannedOrders = async (req, res) => {

    let offshelfSearch = req.body.offshelfSearch;
    
    const orderPickupData = await OrderPickup.find({ op_code: offshelfSearch }, {map:1});
    const mapData = orderPickupData[0].map;
    // for(const item of orderPickupData){
    let j = 0;

    let matchFound = false;
    let orderLabelPincode = '';

    let finalData = []
    for (const key of Object.keys(mapData)) {
        let child = mapData[key];
        
        if(child.opm_status==0){

            const wmsData = await Wmsorder.aggregate([
                {
                    $match: {
                        "orders_code": child.orders_code
                    }
                },
                {
                    $unwind: { path: "$product", preserveNullAndEmptyArrays: true }
                },
                {
                    $lookup: {
                        from: "products",
                        localField: "product.product_sku",
                        foreignField: "code",
                        as: "matched_product"
                    }
                },
                {
                    $unwind: { path: "$matched_product", preserveNullAndEmptyArrays: true }
                },
                {
                    $project: {
                        "_id": 0,
                        "product_sku": "$product.product_sku",
                        "orders_code": child.orders_code,
                    }
                }
            ]);

            let product_sku = wmsData[0].product_sku ? wmsData[0].product_sku : '0';

            const trackingData = await WInward.findOne({ cff_orderno: child.orders_code })
            let trackingId = '';
            let courierName = '';
            let i_orderno = '';
            let s_orderno = '';
            if(trackingData){
                trackingId = trackingData.trackingId
                courierName = trackingData.courierName
                i_orderno = trackingData.i_orderno
                s_orderno = trackingData.s_orderno
            }

            let data = {}
            data = {
                op_code: child.op_code,
                orders_code: child.orders_code,
                product_id: child.product_id,
                opm_quantity: child.opm_quantity,
                product_sku: product_sku,
                ws_code: child.ws_code,
                opm_quantity: child.opm_quantity,
                opm_status: child.opm_status,
                courierName:courierName,
                trackingId:trackingId,
                i_orderno:i_orderno,
                s_orderno:s_orderno
            };

            finalData.push(data)
        }

        
    }

    // console.log(finalData)
        let result = { 'error': 0, 'finalData': finalData }
        return res.status(200).json(result);
  }

  exports.getGateEntrys= async (req, res) => {
    try {
        const GateEntrys = await GateEntry.find();          
        res.status(200).json({ GateEntrys });
    } catch (error) {
        console.error("Error fetching gatEntries:", error);
        res.status(500).json({ error: "Error fetching getEntries" });
    }
};

exports.BinLocationUpdate = async(req, res) => {
    // console.log(req.body)

    const binLocation = req.body.binLocation;
    const processby = req.body.processby;

    try{
        const sku = req.body.sku;
        let skustring1 = sku.replace("STK01", "");

        const orderReturn = await OrderReturn.findOne({ "sku" : skustring1 });
        
        if(orderReturn){
            var query = {
                shelf: { $regex: new RegExp(binLocation, 'i') } // 'i' for case-insensitive
            };
    
            // const quantity = req.body.quantity;
            const saleableQuantity = req.body.saleableQuantity;
    
            if(req.body.saleableQuantity>0){
                
                const products = await Products.findOne({ code : skustring1 }, { stock:1 })
    
                let in_qty = 0;
                let blk_qty = 0;
                let updateObj = {}
                if(products.stock.in_qty){
                    in_qty = products.stock.in_qty
                }
    
                if(products.stock.blk_qty){
                    blk_qty = products.stock.blk_qty
                }
                
                let qtyUpdate = [];
                if(processby==0){
                    updateObj = {
                        'stock.in_qty':parseInt(in_qty)+parseInt(saleableQuantity)
                    }
                }
    
                if(processby==3){
                    updateObj = {
                        'stock.blk_qty':parseInt(blk_qty)+parseInt(saleableQuantity)
                    }
                }
    
                if(processby==1 || processby==4){
                    updateObj = {
                        "stock.in_qty": parseInt(in_qty)+parseInt(saleableQuantity)
                    }
                }
    
                // console.log(skustring1)
                await Products.updateOne({ "code": skustring1 }, { $set: updateObj }, { upsert: false });
    
            }
    
            // return false;
            const shelflocations = await Shelflocations.findOne(query)
            if(shelflocations){
            
            let qty = parseInt(shelflocations.quantity)+parseInt(req.body.saleableQuantity);

            const updateObj = {
                code: skustring1,
                quantity: qty,
                qcaction: req.body.qcaction,
                saleableQty: req.body.saleableQuantity,
                nonSaleableQty: req.body.nonSaleableQuantity,
                damageQty: req.body.damageQuantity,
                remark: req.body.remark,
                updatedAt:new Date()
                }
                // console.log(updateObj)
                const shelflocation = await Shelflocations.updateOne(query, {$set: updateObj})

                const insertObj = new TempShelflocations({
                    code: skustring1,
                    quantity: qty,
                    qcaction: req.body.qcaction,
                    saleableQty: req.body.saleableQuantity,
                    nonSaleableQty: req.body.nonSaleableQuantity,
                    damageQty: req.body.damageQuantity,
                    remark: req.body.remark,
                    shelf : req.body.binLocation,
                    systemRemark:'shelflocations updated'
                    });
        
                await insertObj.save();
    
                return res.status(200).json({ response: "Shelflocation updated successfully!" });
    
            }else{
                const shelflocations1 = await Shelflocations.findOne({}, {sort:1}).sort({_id:-1}).limit(1);
    
            //   console.log(shelflocations1)
            //   return false;
    
                const insertObj = new Shelflocations({
                code: skustring1,
                quantity: req.body.saleableQuantity,
                qcaction: req.body.qcaction,
                saleableQty: req.body.saleableQuantity,
                nonSaleableQty: req.body.nonSaleableQuantity,
                damageQty: req.body.damageQuantity,
                remark: req.body.remark,
                shelf : req.body.binLocation,
                sort:shelflocations1.sort
                });
    
                await insertObj.save();

                const tempObj = new TempShelflocations({
                    code: skustring1,
                    quantity: req.body.saleableQuantity,
                    qcaction: req.body.qcaction,
                    saleableQty: req.body.saleableQuantity,
                    nonSaleableQty: req.body.nonSaleableQuantity,
                    damageQty: req.body.damageQuantity,
                    remark: req.body.remark,
                    shelf : req.body.binLocation,
                    systemRemark:'shelflocations inserted'
                    });
        
                await tempObj.save();
    
                return res.status(200).json({ response: "Shelflocation added successfully!" });
    
            }
        }else{
            return res.status(200).json({ error:1, response: "No data found" });
        }

    }catch(error){
        console.error("Error fetching gatEntries:", error);
        return res.status(500).json({ error: "Something went wrong" });
    }
      
}

exports.GetQtyShelflocation = async (req, res) => {

    const sku = req.body.sku;
    let skustring1 = sku.replace("STK01", "");


    const orderReturn = await OrderReturn.findOne({ "sku" : skustring1 });
	// console.log(orderReturn);
    if(orderReturn){
        const orders = await Order.findOne({ $or: [ { mkpOrderId: orderReturn.marketplace_order_id }, {orderSerial: orderReturn.marketplace_order_id } ] })
        //const orders = await Order.findOne({ mkpOrderId : orderReturn.marketplace_order_id })
        // console.log(orders);
        
        let chinaProcessBy = '';
        if(orders.chinaProcess==0){
            chinaProcessBy = 'India'
        }else if(orders.chinaProcess==1){
            chinaProcessBy = 'China'
        }else if(orders.chinaProcess==3){
            chinaProcessBy = 'Bulk'
        }else if(orders.chinaProcess==4){
            chinaProcessBy = 'China1'
        }

        let saleableQty = 0;
        if(orderReturn.saleableQty){
            saleableQty = orderReturn.saleableQty
        }

        let nonSaleableQty = 0;
        if(orderReturn.nonSaleableQty){
            nonSaleableQty = orderReturn.nonSaleableQty
        }

        let damageQty = 0;
        if(orderReturn.damageQty){
            damageQty = orderReturn.damageQty
        }

        
        let returnObj = {
            'quantity' : orderReturn.quantity,
            'processby': orders.chinaProcess,
            'inventoryBucket': chinaProcessBy,
            'saleableQty' : saleableQty,
            'nonSaleableQty' : nonSaleableQty,
            'damageQty' : damageQty
        }

        let result = { 'error': 0, 'message': returnObj };
        return res.status(200).json(result); 
    }else{
        let result = { 'error': 1, 'message': 'No data found' };
        return res.status(200).json(result);
    }
}

exports.WinwardList = async (req, res) => {

    const page = parseInt(req.query.page)
    const limit = parseInt(req.query.limit)
    const startIndex = (page - 1) * limit
    const endIndex = page * limit
    const results = {}
    let query = {};

    if (req.query.text) {
        query.mkpOrderId = req.query.text;
    }

    query = {
        refund_date: { $ne : null }
    }

    const orderCount = await WInward.countDocuments(query).exec();
    results.count = orderCount;
    results.startIndex = startIndex;
    if (endIndex < orderCount) {
        results.next = {
            page: page + 1,
            limit: limit
        }
    }
    if (startIndex > 0) {
        results.previous = {
            page: page - 1,
            limit: limit
        }
    }

    try {
        let WInwardData = await WInward.find(query).sort({ created_date: -1 }).limit(limit).skip(startIndex);
        

        if (WInwardData.length > 0) {
            let orders = WInwardData.map(async (item) => {
                
                return {
                    "_id": item._id,
                    "mkpOrderId": item.mkpOrderId,
                    "s_orderno": item.s_orderno,
                    "refund_date": item.refund_date,
                    "orderDate": item.orderDate,
                };
            });

            results.result = await Promise.all(orders);

            res.send(results);
        } else {
            res.json({ message: "No warehouse found" });
        }
    } catch (error) {
        console.error("Error fetching WinwardDataData:", error);
        res.status(500).json({ error: "Internal Server Error" });
    }

};

exports.UploadSafeTClaimCsv = async (req, res) => {
    var fileContent = req.files.file.data
    
    let csv_data = await csv().fromString(fileContent.toString());
    let sku_list = [];
    var d = new Date();
    // console.log(csv_data)

    // return false
    // const merchantId = req.body.merchantId;
    // const s3dir = "import_export/" + d.getFullYear().toString() + "/" + (d.getMonth() + 1).toString() + "/";
    // var filename = 'exportStock_' + makeid(6) + '_' + merchantId + '.csv';

    // const limitedCsvData = csv_data.slice(0, 10);
    await Promise.all(csv_data.map(async (item) => {
      try {
        
        // console.log(item.mkpOrderId)

        // const orders = await Order.findOneAndUpdate({mkpOrderId: item.mkpOrderId}, {$set: obj}, {orderSerial:1}, { new: true })
        const existingOrder = await WInward.findOne({ mkpOrderId: item.mkpOrderId });
        if (!existingOrder) {
            const notinward = new NotWInward({
                mkpOrderId: item.mkpOrderId,
                safetyClaimAmt:item.safetyClaimAmt,
                safetyClaimApprovedAmt:item.safetyClaimApprovedAmt,
                safety_claim_date:item.safetyClaimDate,
                received_safety_claim_date:item.receivedSafetyClaimDate,
                declined_safety_claim_date:item.declinedSafetyClaimDate
              });
              await notinward.save();

        } else {
            
            let winwardUpdateObj = {
                    safetyClaimAmt:item.safetyClaimAmt,
                    safetyClaimApprovedAmt:item.safetyClaimApprovedAmt,
                    safety_claim_date:item.safetyClaimDate,
                    received_safety_claim_date:item.receivedSafetyClaimDate,
                    declined_safety_claim_date:item.declinedSafetyClaimDate
                }
            // console.log(item.mkpOrderId)
            const winward = await WInward.findOneAndUpdate({mkpOrderId: item.mkpOrderId}, {$set: winwardUpdateObj})
            
        }
        
        let result = { 'error': 0, 'message': 'Safe-T Claim updated successfully' };
        return res.status(200).json(result);
        

      }catch(err){
        let result = { 'error': 1, 'message': err };
        return { 'error': 1, 'message': err };
        // return res.status(200).json(result);
      }
    }));
}

exports.SafeTClaimList = async (req, res) => {

    const page = parseInt(req.query.page)
    const limit = parseInt(req.query.limit)
    const startIndex = (page - 1) * limit
    const endIndex = page * limit
    const results = {}
    let query = {};

    if (req.query.text) {
        query.mkpOrderId = req.query.text;
    }

    query = {
        safety_claim_date: { $ne : null }
    }

    // console.log(query)

    const orderCount = await WInward.countDocuments(query).exec();
    results.count = orderCount;
    results.startIndex = startIndex;
    if (endIndex < orderCount) {
        results.next = {
            page: page + 1,
            limit: limit
        }
    }
    if (startIndex > 0) {
        results.previous = {
            page: page - 1,
            limit: limit
        }
    }

    try {
        let WInwardData = await WInward.find(query).sort({ created_date: -1 }).limit(limit).skip(startIndex);
        

        if (WInwardData.length > 0) {
            let orders = WInwardData.map(async (item) => {
                
                // let winwardUpdateObj = {
                //     safetyClaimAmt:item.safetyClaimAmt,
                //     safetyClaimApprovedAmt:item.safetyClaimApprovedAmt,
                //     safety_claim_date:item.safetyClaimDate,
                //     received_safety_claim_date:item.receivedSafetyClaimDate,
                //     declined_safety_claim_date:item.declinedSafetyClaimDate
                // }

                return {
                    "_id": item._id,
                    "mkpOrderId": item.mkpOrderId,
                    "safetyClaimAmt": item.safetyClaimAmt,
                    "safetyClaimApprovedAmt": item.safetyClaimApprovedAmt,
                    "safety_claim_date": item.safety_claim_date,
                    "received_safety_claim_date": item.received_safety_claim_date,
                    "declined_safety_claim_date": item.declined_safety_claim_date,
                    "orderDate": item.orderDate,
                };
            });

            results.result = await Promise.all(orders);

            res.send(results);
        } else {
            res.json({ message: "No warehouse found" });
        }
    } catch (error) {
        console.error("Error fetching WinwardDataData:", error);
        res.status(500).json({ error: "Internal Server Error" });
    }

};

exports.NotWinwardList = async(req, res) => {
    const page = parseInt(req.query.page)
    const limit = parseInt(req.query.limit)
    const startIndex = (page - 1) * limit
    const endIndex = page * limit
    const results = {}
    let query = {};

    if (req.query.text) {
        query.mkpOrderId = req.query.text;
    }

    // console.log(query)

    const orderCount = await NotWInward.countDocuments(query).exec();
    results.count = orderCount;
    results.startIndex = startIndex;
    if (endIndex < orderCount) {
        results.next = {
            page: page + 1,
            limit: limit
        }
    }
    if (startIndex > 0) {
        results.previous = {
            page: page - 1,
            limit: limit
        }
    }

    try {
        let WInwardData = await NotWInward.find(query).sort({ created_date: -1 }).limit(limit).skip(startIndex);
        

        if (WInwardData.length > 0) {
            let orders = WInwardData.map(async (item) => {

                $status_arr = {
                    0 : 'Initialize',
                    1 : 'Dispatch from Warehouse',
                    2 : 'In Transite',
                    3 : 'Deliever',
                    4 : 'RTO',
                    5 : 'Return',
                    6 : 'QC',
                    7 : 'In Stock',
                    8 : 'Damage',
                    9 : 'Refund',
                }

                // console.log($status_arr)
                // console.log($status_arr[0])

                // console.log(item.order_status);
                // console.log(typeof item.order_status);

                let order_status = '-'
                if(item.order_status){
                    order_status = $status_arr[item.order_status]
                }
                
                return {
                    "_id": item._id,
                    "inv_number": item.inv_number,
                    "mkpOrderId": item.mkpOrderId,
                    "cff_orderno": item.cff_orderno,
                    "i_orderno": item.i_orderno,
                    "s_orderno": item.s_orderno,
                    "spID": item.spID,
                    "description": item.description,
                    "qty": item.qty,
                    "unitPrice": item.unitPrice,
                    "totalPrice": item.totalPrice,
                    "rmbPrice": item.rmbPrice,
                    "sku": item.sku,
                    "returnReason": item.returnReason,
                    "remark": item.remark,
                    "qc": item.qc,
                    "claim": item.claim,
                    "type": item.type,
                    "account_name": item.account_name,
                    "rto_awb": item.rto_awb,
                    "return_awb": item.return_awb,
                    "order_status": order_status,
                    "refund_date": item.refund_date,
                    "created_date": item.created_date,
                    "return_date": item.return_date,
                    "invoiceDate": item.invoiceDate,
                    
                };
            });

            results.result = await Promise.all(orders);

            res.send(results);
        } else {
            res.json({ message: "No warehouse found" });
        }
    } catch (error) {
        console.error("Error fetching WinwardDataData:", error);
        res.status(500).json({ error: "Internal Server Error" });
    }
};

exports.IncomingStockUpdate = async(req, res) => {
    // console.log(req.body)

    const binLocation = req.body.binLocation;
    const processby = req.body.inventoryBucket;
    
    try{
        const sku = req.body.sku;
        let skustring1 = sku.replace("STK01", "");

        const orderReturn = await OrderReturn.findOne({ "sku" : skustring1 });
        
        // if(orderReturn){
            var query = {
                shelf: { $regex: new RegExp(binLocation, 'i') } // 'i' for case-insensitive
            };
    
            // const quantity = req.body.quantity;
            const saleableQuantity = req.body.saleableQuantity;
    
            if(req.body.saleableQuantity>0){
                
                const products = await Products.findOne({ code : skustring1 }, { stock:1 })
    
                let in_qty = 0;
                let blk_qty = 0;
                let updateObj = {}
                if(products.stock.in_qty){
                    in_qty = products.stock.in_qty
                }
    
                if(products.stock.blk_qty){
                    blk_qty = products.stock.blk_qty
                }
                
                let qtyUpdate = [];
                if(processby==0){
                    updateObj = {
                        'stock.in_qty':parseInt(in_qty)+parseInt(saleableQuantity)
                    }
                }
    
                if(processby==3){
                    updateObj = {
                        'stock.blk_qty':parseInt(blk_qty)+parseInt(saleableQuantity)
                    }
                }
    
                // console.log(skustring1)
                await Products.updateOne({ "code": skustring1 }, { $set: updateObj }, { upsert: false });
    
            }
            
            // return false;
            const shelflocations = await Shelflocations.findOne(query)
            if(shelflocations){
    
            const updateObj = {
                code: skustring1,
                quantity: req.body.quantity,
                qcaction: req.body.qcaction,
                saleableQty: req.body.saleableQuantity,
                nonSaleableQty: req.body.nonSaleableQuantity,
                damageQty: req.body.damageQuantity,
                remark: req.body.remark,
                updatedAt:new Date()
                }
                // console.log(updateObj)
                const shelflocation = await Shelflocations.updateOne(query, {$set: updateObj})
    
                return res.status(200).json({ response: "Shelflocation updated successfully!" });
    
            }else{
                const shelflocations1 = await Shelflocations.findOne({}, {sort:1}).sort({_id:-1}).limit(1);
                
            //   console.log(shelflocations1)
            //   return false;
    
                const insertObj = new TempShelflocations({
                code: skustring1,
                quantity: req.body.quantity,
                qcaction: req.body.qcaction,
                saleableQty: req.body.saleableQuantity,
                nonSaleableQty: req.body.nonSaleableQuantity,
                damageQty: req.body.damageQuantity,
                remark: req.body.remark,
                shelf : req.body.binLocation,
                sort:shelflocations1.sort
                });
    
                await insertObj.save();
    
                return res.status(200).json({ response: "Shelflocation added successfully!" });
    
            }
        // }else{
        //     return res.status(200).json({ error:1, response: "No data found" });
        // }

    }catch(error){
        console.error("Error fetching gatEntries:", error);
        return res.status(500).json({ error: "Something went wrong" });
    }
      
}

exports.UnallocatedDownload = async (req, res) => {
 
    try {
        const shelfNumber = req.query.shelfNumber;
        const data = await Indiaoffshelf.find({ shelfNumber : shelfNumber, shelflocation:"" } );
        // console.log(data)

        let distinctProductSkus = 0;
        let distinctOrderCodes = new Set();
        let totalQuantity = 0;
        
        const mdata = data;

        const item_data = [];
        const batchSize = 12;

        const promises = [];

        // console.log(mdata.length)
        distinctProductSkus = mdata.length;

        const uniqueSku = await Indiaoffshelf.distinct('sku', {shelfNumber : shelfNumber});
        const skuCount = uniqueSku.length;

        let orderData = await Promise.all(mdata.map(async (item) => {
            distinctOrderCodes.add(item.shelfNumber);
            totalQuantity += parseInt(item.quantity);
        
            let sku = item.sku.replace("STK01", "");
            
            let batchItemData = {
                'Shelf Number': item.shelfNumber,
                'Shelf Location': item.shelflocation,
                'Order Serial': item.orderSerial,
                'Product Barcode': item.sku,
                'Quantity': item.quantity,
                'Order Status': item.op_status==1?'Scanned':'Not Scanned',
                
            };
        
            item_data.push(batchItemData);
        }));

        let d = new Date();
        let supplierId = req.query.id;
        // let supplierId = '6613cc084184e227e4815e4e';
        const s3dir = "indiaoffshelf/" + supplierId + d.getFullYear().toString() + "/" + (d.getMonth() + 1).toString() + "/";
        // console.log(s3dir)
        let filename = makeid(6) + '_' + supplierId + '.xlsx';
        let fullPath = s3dir + filename;
        // console.log(fullPath);
        // return false;

        const excelBuffer = generateExcelFile(item_data);
        // console.log(excelBuffer)

        // return false;
        var status = await uploadExcel(excelBuffer, s3dir + filename).then(async () => {
            var url = process.env.S3_BUCKET_FILE_URL
            url =  url + '/' + fullPath 
            // console.log(url)
            let result = { 'error': 0, 'message': url };
            return res.status(200).json(result);
        });


    } catch (error) {
        let result = { 'error': 1, 'message': error };
        return res.status(200).json(result);
    }

};

exports.UploadProduct = async (req, res) => {
    try {
        var data = req.body.addProductRequestInfo;
		let orderDetails = [];
		let order_shipping = []; 

        // console.log(data)

        data.forEach(async function (order) {

            // console.log(typeof order.istore_product_id)
            // console.log(order.istore_product_id)
            const productExist = await Products.find({ code : order.istore_product_id });
            if(productExist.length>0){
                // console.log('exist')
                return;
            }else{

                // console.log(order.istore_product_id)
                // console.log(order.image_paths)
                var titlePD = "";
                var handle = "";

                // return false;
                if(order.pd_name=='' || order.pd_name==null){
                    // console.log(order.istore_product_id)

                    titlePD = "";
                    // var dataHandle = titlePD.trim();
                    handle = "";

                }else{
                    titlePD = order.pd_name;
                    var dataHandle = titlePD.trim();
                    handle = dataHandle.toLocaleLowerCase().replace(/[^\w-]+/g, "-");

                }
                    

                    let mainImage = [];
                    if(order.image_paths=='' || order.image_paths==null){

                    }else{

                        // console.log(order);
                        
                        var productImage = order.image_paths.split(',');
                        if (productImage && productImage.length > 0) {
                            let position = 1;
                            productImage.forEach(function (pimage) {
                                
                                var imgData = { 'url': pimage, 'handle': handle };
                                var imgpath = '';
                                var varient_id = '';
                                upload_image(imgData, function (result) {
                                    imgpath = result;
                                });
                                var imgres1 = { 'position': position++, 'src': imgpath, 'varient_id': '' }
                                mainImage.push(imgres1);
                            });
                        }
                    }
                    
                    // console.log(mainImage)
                    // console.log(11111111)

                    // return false
                    let stock = {
                        "cn_qty": 0,
                        "in_qty": 0,
                        "blk_qty": 0,
                    };

                    let shippingObj = {
                        method: 'freeShipping',
                    };

                    let prices = {
                        pd_base_price:order.product_base_price,
                        ppm_price_2:order.ppm_price_2,
                        STK_price: order.stk_shopperr_price
                    }

                    let skus = [];
                    skus.push(order.istore_product_id);

                    let factoryPrice = order.stk_shopperr_price;

                    const sp = chinaPriceAlgoSFC(factoryPrice, order.product_weight);

                    // console.log(parseInt(factoryPrice).toFixed(2))
                    // console.log(222222222222222)
                    try{
                        const data = new Products({
                            hsn:'',
                            pd_status:1,
                            skus:skus,
                            d2cStatus:0,
                            priceUpdate:0,
                            supplier_id:'5ff1fb6cb5a4c4a27a0580dd',
                            sid:mongoose.Types.ObjectId('5ff1fb6cb5a4c4a27a0580dd'),
                            name:order.pd_name,
                            handle:'',
                            price: parseInt(factoryPrice).toFixed(2),
                            mrp: sp.mrp,
                            sp: sp.price,
                            cogs: sp.cogs,
                            quantity: order.po_quantity,
                            weight: order.product_weight,
                            description: order.pd_description,
                            code: order.istore_product_id,
                            size: '',
                            category:'',
                            cat_id:order.category_id,
                            length:order.product_length,
                            width:order.product_width,
                            height:order.product_height,
                            g_id:'',
                            gst:'',
                            is_display:0,
                            stock:stock,
                            prices:prices,
                            shippingCharge: shippingObj,
                            uploaded_on: Date(),
                            imgUrl: mainImage
    
                        })
    
                        const newProduct = data.save();
                    }catch(err){
                        // console.log(err)
                    }

                // }
                
                // console.log(obj)
            }

        })


    }catch(err){
        
    }

};

exports.UpdateGst = async (req, res) => {
    
    try {
        var data = req.body.addProductRequestInfo;
		let orderDetails = [];
		let order_shipping = []; 

        // console.log(data)

        data.forEach(async function (order) {

            var istore_product_id = order.istore_product_id;
            var hsn_gst = order.hsn_gst?order.hsn_gst:'18.00';
            var hsn = order.hsn?order.hsn:'33049110'


            const productData = await Products.findOne({ code: istore_product_id }, {gst:1, hsn:1})
            if(productData){
                
                let updateObj = {
                    istore_product_id:istore_product_id,
                    gst:hsn_gst
                }
                // console.log(productData.hsn)
                // if(productData.hsn===null){
                //     // console.log(1111)
                //     updateObj.hsn = hsn
                // }

                // console.log(updateObj)
                // console.log(istore_product_id)

                // await Products.updateOne({ _id: mongoose.Types.ObjectId(productData._id) }, { $set: updateObj }, { upsert: false });

                // await Products.updateOne({  _id: mongoose.Types.ObjectId(productData._id) }, { $set: updateObj }, { upsert: false }).then(() => {
                //     console.log('done-'+istore_product_id+'--'+hsn_gst)
                // });
            }


        })


    }catch(err){
        
    }
}

exports.StockManagementList = async (req, res) => {

    const spID = req.query.spID;
    const storeDomain = req.query.store
    const page = parseInt(req.query.page)
    const limit = parseInt(req.query.limit)
    const startIndex = (page - 1) * limit
    const endIndex = page * limit
    const results = {}
    var query = {};
    

    if (req.query.text) {
        // query.inv_number = req.query.text; 

        query = {
            $or: [
                { code: req.query.text },
                // {shelf: { $regex: new RegExp(req.query.text, 'i') }}
                {shelf: req.query.text.toUpperCase()}
                // { i_orderno: req.query.text },
                // { s_orderno: req.query.text },
                // { sku: req.query.text }
            ]
        };
    }

    if (req.query.orderdateFrom) {
    
        query.createdAt = {
            $gte: new Date(req.query.orderdateFrom+'T00:00:00.000Z'),
            $lt: new Date(req.query.orderdateTo+'T23:59:59Z')
        }
            
    }

    // if (req.query.orderdateTo) {
    
    //     query.createdAt = {
    //         $gte: new Date(req.query.orderdateTo+'T00:00:00.000Z'),
    //         $lt: new Date(req.query.orderdateTo+'T23:59:59Z')
    //     }
            
    // }


    // console.log(query)

    // query.spID = spID;

    //{ spID: '6613cc084184e227e4815e4e', $or: [ { inv_number: "BL202409160482" }, { cff_orderno: "BL202409160482" }, {i_orderno:"BL202409160482"} ]}

    const orderCount = await Shelflocations.countDocuments(query).exec();
    // console.log(orderCount)
    results.count = orderCount;
    results.startIndex = startIndex;
    if (endIndex < orderCount) {
        results.next = {
            page: page + 1,
            limit: limit
        }
    }
    if (startIndex > 0) {
        results.previous = {
            page: page - 1,
            limit: limit
        }
    }

    try {
        // results.results = await TempShelflocations.find(query)
        //     .sort({ createdAt: -1 })
        //     .limit(limit)
        //     .skip(startIndex)
        //     .exec();

        const resultData = await Shelflocations.find(query)
            .sort({ createdAt: -1 })
            .limit(limit)
            .skip(startIndex)
            .exec();
        
        if(resultData.length>0){
            let final = await Promise.all(resultData.map(async (item) => {

                const dateStr = item.createdAt;
                const formattedDate = moment.tz(dateStr, "DD-MM-YYYY HH:mm", "Asia/Kolkata").toISOString();

                // console.log(formattedDate);

                const formattedInKolkata = moment(formattedDate)
                .tz("Asia/Kolkata")  // Convert to Asia/Kolkata time zone
                .format('ddd, DD MMM YYYY HH:mm:ss [GMT] z');  // Format as per the required format
            
                // console.log(formattedInKolkata);
                
                // console.log(item)
                return {
                    shelf:item.shelf,
                    saleableQty:item.saleableQty,
                    nonSaleableQty:item.nonSaleableQty,
                    damageQty:item.damageQty,
                    code:item.code,
                    date:formattedInKolkata,
                    quantity:item.quantity,
                    prevQuantity:item.beforeQty?item.beforeQty:0,
                    

                }

            }))
           
            results.results = final
        }

        res.send(results)
    } catch (e) {
        res.status(500).json({ message: e.message })
    }

};

exports.TempHistory = async (req, res) => {
    // console.log(req.query.code)

    const results = {}

    try{
        const resultData = await TempShelflocations.find({code:req.query.code}).sort({ createdAt: -1 });
        //createdAt
        // console.log(resultData)

        if(resultData.length>0){
            let final = await Promise.all(resultData.map(async (item) => {

                const dateStr = item.createdAt;
                const formattedDate = moment.tz(dateStr, "DD-MM-YYYY HH:mm", "Asia/Kolkata").toISOString();

                // console.log(formattedDate);

                const formattedInKolkata = moment(formattedDate)
                .tz("Asia/Kolkata")  // Convert to Asia/Kolkata time zone
                .format('ddd, DD MMM YYYY HH:mm:ss [GMT] z');  // Format as per the required format
            
                // console.log(formattedInKolkata);
                
                // console.log(item)
                return {
                    shelf:item.shelf,
                    saleableQty:item.saleableQty,
                    nonSaleableQty:item.nonSaleableQty,
                    damageQty:item.damageQty,
                    code:item.code,
                    date:formattedInKolkata,
                }

            }))
           
            results.results = final
        }


        res.send(results)
    }catch(err){
        res.status(500).json({ message: err.message })
    }
    

};

exports.StockManagementExport = async (req, res) => {

    const spID = req.query.spID;
    const storeDomain = req.query.store
    
    const results = {}
    var query = {};
    const item_data = [];
    
    if (req.query.text) {
        // query.inv_number = req.query.text; 

        query = {
            $or: [
                { code: req.query.text },
                {shelf: req.query.text.toUpperCase()}
            ]
        };
    }

    if (req.query.orderdateFrom) {
    
        query.createdAt = {
            $gte: new Date(req.query.orderdateFrom+'T00:00:00.000Z'),
            $lt: new Date(req.query.orderdateTo+'T23:59:59Z')
        }
            
    }

    // if (req.query.orderdateTo) {
    
    //     query.createdAt = {
    //         $gte: new Date(req.query.orderdateTo+'T00:00:00.000Z'),
    //         $lt: new Date(req.query.orderdateTo+'T23:59:59Z')
    //     }
            
    // }

    const orderCount = await Shelflocations.countDocuments(query).exec();
    // console.log(orderCount)
    
    try {

        const resultData = await Shelflocations.find(query)
            .sort({ createdAt: -1 })
            .exec();
        
        if(resultData.length>0){
            let final = await Promise.all(resultData.map(async (item) => {

                const dateStr = item.createdAt;
                const formattedDate = moment.tz(dateStr, "DD-MM-YYYY HH:mm", "Asia/Kolkata").toISOString();

                // console.log(formattedDate);

                const formattedInKolkata = moment(formattedDate)
                .tz("Asia/Kolkata")  // Convert to Asia/Kolkata time zone
                .format('ddd, DD MMM YYYY HH:mm:ss [GMT] z');  // Format as per the required format
            
                // console.log(formattedInKolkata);

                let obj = {
                    shelf:item.shelf,
                    quantity:item.quantity,
                    saleableQty:item.saleableQty,
                    nonSaleableQty:item.nonSaleableQty,
                    damageQty:item.damageQty,
                    code:item.code,
                    date:formattedInKolkata,
                    remark:item.remark,
                }

                item_data.push(obj)
                
                // console.log(item)
                return {
                    shelf:item.shelf,
                    saleableQty:item.saleableQty,
                    nonSaleableQty:item.nonSaleableQty,
                    damageQty:item.damageQty,
                    code:item.code,
                    date:formattedInKolkata,
                }
                
            }))
            // item_data.push(final)
            results.results = final
        }

        // console.log(item_data)
        
        let d = new Date();
        let supplierId = req.query.spID;
        // let supplierId = '6613cc084184e227e4815e4e';
        const s3dir = "indiaoffshelf/" + supplierId + d.getFullYear().toString() + "/" + (d.getMonth() + 1).toString() + "/";
        // console.log(s3dir)
        let filename = makeid(6) + '_' + supplierId + '.xlsx';
        let fullPath = s3dir + filename;
        // console.log(fullPath);
        // return false;

        const excelBuffer = generateExcelFile(item_data);
        // console.log(excelBuffer)

        // return false;
        var status = await uploadExcel(excelBuffer, s3dir + filename).then(async () => {
            var url = process.env.S3_BUCKET_FILE_URL
            url =  url + '/' + fullPath 
            // console.log(url)
            let result = { 'error': 0, 'message': url };
            return res.status(200).json(result);
        });
        

        // res.send(results)
    } catch (e) {
        res.status(500).json({ message: e.message })
    }

};

//Read Xlsx
exports.OrderReturnAwbUpdate = async (req, res) => {

    let fileContent = req.files.file.data;
    // console.log(req.files)

    // let csv_data = await  xlsx.readFile(fileContent.toString());
    let workbook = await xlsx.read(fileContent, { type: 'buffer' });

    // console.log(workbook.SheetNames);
    // return false;

    const sheetName = workbook.SheetNames[0];  // First sheet
    const sheet = workbook.Sheets[sheetName];

    // Convert the sheet data to JSON
    const jsonData = xlsx.utils.sheet_to_json(sheet);

    // Print the parsed data
    // console.log(jsonData);

    jsonData.forEach(async(item) => {
        // console.log(item.TrackingID)
        
        let obj = {
            awb : item.TrackingID
        }

        // const updatedOrder1 = await OrderReturn.findOne(
        //     { marketplace_order_id : item.OrderingOrderID },
            
        // );

        // console.log(updatedOrder1)

        const updatedOrder = await OrderReturn.findOneAndUpdate(
            { marketplace_order_id : item.OrderingOrderID },
            { $set: obj },
            { new: true }
        );
        console.log(item.OrderingOrderID)
        // return false
    })
    
};

exports.ProductDelete = async (req, res) => {

    let fileContent = req.files.file.data;
    // console.log(req.files)

    // let csv_data = await  xlsx.readFile(fileContent.toString());
    let workbook = await xlsx.read(fileContent, { type: 'buffer' });

    // console.log(workbook.SheetNames);

    const sheetName = workbook.SheetNames[0];  // First sheet
    const sheet = workbook.Sheets[sheetName];

    // Convert the sheet data to JSON
    const jsonData = xlsx.utils.sheet_to_json(sheet);

    // Print the parsed data
    // console.log(jsonData);

    jsonData.forEach(async(item) => {
        // console.log(item.SKU)
        
        // let obj = {
        //     awb : item.SKU
        // }

        // const updatedOrder1 = await Products.findOne(
        //     { code : item.SKU },
            
        // );

        // console.log(updatedOrder1)

        const updatedOrder = await Products.findOneAndDelete(
            { code : item.SKU },
            
        );
        // console.log(item.SKU)
        // return false
    })
    
};

exports.DateTest = async (req, res) => {
    // console.log(req.body.date)

    //Test
    
    const dateStr = '2024-12-01 01:10:03';
    const formattedDate = moment.tz(dateStr, "YYYY-MM-DD HH:mm", "Asia/Kolkata").toISOString();


    // console.log(formattedDate);


    const formattedInKolkata = moment(formattedDate)
    .tz("Asia/Kolkata")  // Convert to Asia/Kolkata time zone
    .format('ddd, DD MMM YYYY HH:mm:ss [GMT] z');  // Format as per the required format
    
    // console.log(formattedInKolkata);

    // const test = new Test({
    //     'orders_code' : 'abcd',
    //     testDate: formattedDate
    // })

    // await test.save();
    
    let startDate, endDate;
    startDate ='2024-12-01' + 'T00:00:00Z';
    endDate = '2024-12-07' + 'T23:59:59Z';

    const dateStr1 = '2024-12-08';
    const dateStr2 = '2024-12-14';

    // Convert the date to the start of the day (00:00:00) in Asia/Kolkata time zone
    const startOfDayKolkata = moment.tz(`${dateStr1} 00:00:00`, "YYYY-MM-DD HH:mm:ss", "Asia/Kolkata");

    // Convert the date to the end of the day (23:59:59) in Asia/Kolkata time zone
    const endOfDayKolkata = moment.tz(`${dateStr2} 23:59:59`, "YYYY-MM-DD HH:mm:ss", "Asia/Kolkata");

    // Convert both start and end times to UTC
    const startOfDayUTC = startOfDayKolkata.utc().toDate();
    const endOfDayUTC = endOfDayKolkata.utc().toDate();

    // const testdata = await Test.find({ testDate: { $gte: startOfDayUTC, $lte: endOfDayUTC } })

    // console.log(startOfDayUTC)


    const order = await Order.countDocuments({
        // orderSerial: "10024COC100101040000",
        orderDate: { $gte: startOfDayUTC, $lte: endOfDayUTC }
    }).exec()

    // console.log(order)

    //2024-12-01 01:10:03

    /*console.log(new Date())
    // console.log(ISODate())

    const t = new Date()

    const f = new Intl.DateTimeFormat('en-us', {
        dateStyle:"short",
        timeStyle:"full"
    })

    console.log(f.format())

    const today = new Date('2024-12-01 01:10:03')
    console.log(today.toLocaleDateString +'-'+today.toLocaleTimeString())
    console.log(today.toLocaleString())

    let date = new Date().toISOString();
    let isoDate = new Date(date);
    console.log(isoDate)*/

    // const dateStr = '30-11-2024  12:39';
    

};

exports.checkOrderInvoice = async (req, res) => {
    var data = req.body.addProductRequestInfo;

    let final_data = [];
    const promises = data.map(async (order) => {
        

        // const orderData = await Order.find({ orderSerial : order.orders_serial })

        const orderData = await Order.aggregate([
            {
              $match: {
                pStatus: { $in: ['PD', 'PP', 'PR'] },
                // orderDate: { $gte: startOfDayUTC, $lte: endOfDayUTC },
                // merchantId: { $nin: ['6371e830aa051e6d673cd97f', '653aa21a40a92c499f3a5a26', '62f238091e5826109e17b557', '668fd0f9c2269f9c393ee96e'] },
                // source: 1,
                orderSerial:order.orders_serial,
                "order_shipping": { $exists: true, $ne: [] }
              },
            },
            {
              $unwind: '$orderDetails', // Unwind the orderDetails array
            },
            {
              $lookup: {
                from: 'users',
                let: { merchantId: { $toObjectId: "$merchantId" } }, // Convert merchantId to ObjectId
                pipeline: [
                  {
                    $match: {
                      $expr: {
                        $eq: ["$_id", "$$merchantId"]
                      }
                    }
                  }
                ],
                as: 'customerInfo'
              }
            },
            {
              $lookup: {
                from: 'products',
                localField: 'orderDetails.sku',
                foreignField: 'skus',
                as: 'productInfo',
              },
            },
            {
              $sort: { orderDate: 1 },
            },
        ]);
        
        if(orderData.length>0){
            // console.log('found')
            // console.log(order.orders_serial)

            orderData.forEach(async (item) => {
                
                // const test = new Test({
                //     'orderSerial' : order.orders_serial,
                //     pStatus: item.pStatus,
                //     merchantId:item.merchantId,
                //     orderDate:item.orderDate
                // })
            
                // await test.save();
                
                const obj = {
                    'orderSerial' : order.orders_serial,
                    pStatus: item.pStatus,
                    merchantId:item.merchantId,
                    orderDate:item.orderDate
                }
    
                // final_data.push(obj)
            })

           
        }else{
            // console.log(order.orders_serial)

            const obj = {
                'orderSerial' : order.orders_serial,
                
            }

            final_data.push(obj)

            // const test = new Test({
            //     'orderSerial' : order.orders_serial,
            //     // testDate: formattedDate
            // })
        
            // await test.save();

            // const data = [
            //     { name: 'John Doe', age: 30, city: 'New York' },
            //     { name: 'Jane Smith', age: 25, city: 'Los Angeles' },
            //     { name: 'Sam Brown', age: 35, city: 'Chicago' }
            //   ];

            
        }

    });

    await Promise.all(promises);

    // console.log(final_data)
    // return false;
    
    const csv = parse(final_data);

    // Specify the folder and file name
    const folderPath = path.join(__dirname, 'csv_folder');
    const fileName = 'output.csv';
    // const filePath = path.join(folderPath, fileName);
    const filePath = 'public/labels/'+fileName;

    // Ensure the folder exists, if not create it
    if (!fs.existsSync(folderPath)) {
        fs.mkdirSync(folderPath);
    }
    
    // Write the CSV data to the file
    fs.writeFile(filePath, csv, (err) => {
        if (err) {
            console.error('Error writing file:', err);
        } else {
            console.log('CSV file saved successfully at:', filePath);
        }
    });
    
}

exports.checkOrderSerial = async (req, res) => {
    var fileContent = req.files.file.data
    
    let csv_data = await csv().fromString(fileContent.toString());
    let sku_list = [];
    var d = new Date();
    // console.log(csv_data)

    // return false
    // const merchantId = req.body.merchantId;
    // const s3dir = "import_export/" + d.getFullYear().toString() + "/" + (d.getMonth() + 1).toString() + "/";
    // var filename = 'exportStock_' + makeid(6) + '_' + merchantId + '.csv';

    // const limitedCsvData = csv_data.slice(0, 10);
    await Promise.all(csv_data.map(async (item) => {
      try {
        
        const dateStr = item.RefundDate;
        const formatteReturndDate = moment.tz(dateStr, "DD-MM-YYYY HH:mm", "Asia/Kolkata").toISOString();

        const existingOrder = await Order.findOne({ orderSerial: item.orders_serial });
        if (!existingOrder) {
            console.log('No existing order found with the specified OrderId - ' + item.orders_serial);
        } else {
            
            
        
        }
        
        let result = { 'error': 0, 'message': 'Refund status updated successfully' };
        return res.status(200).json(result);
        

      }catch(err){
        let result = { 'error': 1, 'message': err };
        return { 'error': 1, 'message': err };
        // return res.status(200).json(result);
      }
    }));
}

exports.pdfCreate = async (req, res) => {
    const html = `
    <!DOCTYPE html><head><title>Pdf</title></head><body>
        <div style="position: relative; margin-left: 0px; width: 9.7cm;border: 2px solid black; overflow: hidden; height: 13.84cm;top: -0.2cm;">
        <div style="position: relative; width: 8.3cm; border-width: medium medium 2px; border-style: none none solid; border-color: -moz-use-text-color -moz-use-text-color black; -moz-border-top-colors: none; -moz-border-right-colors: none; -moz-border-bottom-colors: none; -moz-border-left-colors: none; border-image: none; left: 0cm; height: 2.1cm;">
                <div style="line-height:2px;margin-top: 6px;font-size:12px;">
                    If undelivered,please return to it
                </div>
                <div style="line-height:13px;font-weight:bold;margin-top: 5px;font-size:10px;">
                    GST: 06AAHCC8685P1ZR
                </div>
                <div style="line-height:12px;font-size:12px; margin-top:2px;">
                    <b>Kosliya LLP</b><br>
                    B.No-1 Ground Floor NR Road Nathupur Above Canara Bank Sector 24 Gurgaon Haryana 122002-122015<br>
                    Phone No: 9711878424
                </div>
            </div>
            <div style="position: absolute; width: 8.3cm; padding-left: 0cm; border-width: medium medium 2px; border-style: none none solid; border-color: -moz-use-text-color -moz-use-text-color black; -moz-border-top-colors: none; -moz-border-right-colors: none; -moz-border-bottom-colors: none; -moz-border-left-colors: none; border-image: none; top: 2.3cm; left: 0cm; font-weight: bold; overflow-wrap: break-word; font-size: 12px; height: 3.1cm;">
                To:
                Asmita Saha
                <br>Flat no. E8/104, Peerless Nagar, 29F.B.T. Road,Sodepur29F.B.T. Road , Panihati
                <br>
                India
                <br>Tel: 8420823369<br>
                122015 - GGN / UED
            </div>
            <div style="position: absolute; height: 3.4cm; width: 8.2cm; padding-left: 5px; border-width: medium medium 2px; border-style: none none solid; border-color: -moz-use-text-color -moz-use-text-color black; -moz-border-top-colors: none; -moz-border-right-colors: none; -moz-border-bottom-colors: none; -moz-border-left-colors: none; border-image: none; left: 0cm; font-weight: bold; overflow-wrap: break-word; font-size: 14px; top: 5.6cm;">
                <div style="font-size: 16px;">
                        PREPAID ORDER(Amount : 500 INR)
                </div>
                AWB No:81202259202<br>
                Weight(kgs):0.039<br>
                Dimensions(cms):1X1X1<br>
                Order Id:AA0012121212132269<br>
                Order Date:2024-12-20<br>
                Pieces:1<br><br>
            </div>
            <div style="position: absolute;top:0.1cm; width: 1.4cm; border-width: medium medium 2px 2px; border-style: none none solid solid; border-color: -moz-use-text-color -moz-use-text-color black black; -moz-border-top-colors: none; -moz-border-right-colors: none; -moz-border-bottom-colors: none; -moz-border-left-colors: none; border-image: none; left: 8.3cm; font-size: 13px; line-height: 14px; overflow: hidden; height: 11.38cm;">
                        <p style="margin-left:44px;margin-top:65px;margin-right:-61px;margin-bottom:-50px;transform: rotate(90deg);height:10px;width:10px;">
                        AA0012121212132269 <img height="33" alt="barcode" width="253" src="data:image/png;base64, ">
                        </p>
            </div><div style="position: absolute; width: 9.7cm; border-width: medium medium 2px; border-style: none none solid; border-color: -moz-use-text-color -moz-use-text-color black; -moz-border-top-colors: none; -moz-border-right-colors: none; -moz-border-bottom-colors: none; -moz-border-left-colors: none; border-image: none; left: 0cm; top: 9.1cm; height: 2.4cm;">
                <div style="position:absolute;height:1.9cm;width:7.5cm;top:0.2cm;left:0.4cm;text-align:center;">
                    <span style="display:inline-block;height:60px;width:253px;margin-left:15px;">
                        <img style="height:1.2cm" alt="barcode" width="253" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOAAAACRCAYAAADaU7SFAAAAHnRFWHRTb2Z0d2FyZQBid2lwLWpzLm1ldGFmbG9vci5jb21Tnbi0AAAFQ0lEQVR4nO3TMY7CQAAEQf//0xCRWAL32CKrkwgOtDttUB3HcbxOr8/f+f/z+9/O1fNX99X9dffqeZ+eX8/V57vb+/Q56u/z7+/3qu/uPXc/X5/7670AbvcCCODSDWDsBrDtALh1Axi7AWw7AG7dAMZuANsOgFs3gLEbwLYD4NYNYOwGsO0AuHUDGLsBbDsAbt0Axm4A2w6AWzeAsRvAtgPg1g1g7Aaw7QC4dQMYuwFsOwBu3QDGbgDbDoBbN4CxG8C2A+DWDWDsBrDtALh1Axi7AWw7AG7dAMZuANsOgFs3gLEbwLYD4NYNYOwGsO0AuHUDGLsBbDsAbt0Axm4A2w6AWzeAsRvAtgPg1g1g7Aaw7QC4dQMYuwFsOwBu3QDGbgDbDoBbN4CxG8C2A+DWDWDsBrDtALh1Axi7AWw7AG7dAMZuANsOgFs3gLEbwLYD4NYNYOwGsO0AuHUDGLsBbDsAbt0Axm4A2w6AWzeAsRvAtgPg1g1g7Aaw7QC4dQMYuwFsOwBu3QDGbgDbDoBbN4CxG8C2A+DWDWDsBrDtALh1Axi7AWw7AG7dAMZuANsOgFs3gLEbwLYD4NYNYOwGsO0AuHUDGLsBbDsAbt0Axm4A2w6AWzeAsRvAtgPg1g1g7Aaw7QC4dQMYuwFsOwBu3QDGbgDbDoBbN4CxG8C2A+DWDWDsBrDtALh1Axi7AWw7AG7dAMZuANsOgFs3gLEbwLYD4NYNYOwGsO0AuHUDGLsBbDsAbt0Axm4A2w6AWzeAsRvAtgPg1g1g7Aaw7QC4dQMYuwFsOwBu3QDGbgDbDoBbN4CxG8C2A+DWDWDsBrDtALh1Axi7AWw7AG7dAMZuANsOgFs3gLEbwLYD4NYNYOwGsO0AuHUDGLsBbDsAbt0Axm4A2w6AWzeAsRvAtgPg1g1g7Aaw7QC4dQMYuwFsOwBu3QDGbgDbDoBbN4CxG8C2A+DWDWDsBrDtALh1Axi7AWw7AG7dAMZuANsOgFs3gLEbwLYD4NYNYOwGsO0AuHUDGLsBbDsAbt0Axm4A2w6AWzeAsRvAtgPg1g1g7Aaw7QC4dQMYuwFsOwBu3QDGbgDbDoBbN4CxG8C2A+DWDWDsBrDtALh1Axi7AWw7AG7dAMZuANsOgFs3gLEbwLYD4NYNYOwGsO0AuHUDGLsBbDsAbt0Axm4A2w6AWzeAsRvAtgPg1g1g7Aaw7QC4dQMYuwFsOwBu3QDGbgDbDoBbN4CxG8C2A+DWDWDsBrDtALh1Axi7AWw7AG7dAMZuANsOgFs3gLEbwLYD4NYNYOwGsO0AuHUDGLsBbDsAbt0Axm4A2w6AWzeAsRvAtgPg1g1g7Aaw7QC4dQMYuwFsOwBu3QDGbgDbDoBbN4CxG8C2A+DWDWDsBrDtALh1Axi7AWw7AG7dAMZuANsOgFs3gLEbwLYD4NYNYOwGsO0AuHUDGLsBbDsAbt0Axm4A2w6AWzeAsRvAtgPg1g1g7Aaw7QC4dQMYuwFsOwBu3QDGbgDbDoBbN4CxG8C2A+DWDWDsBrDtALh1Axi7AWw7AG7dAMZuANsOgFs3gLEbwLYD4NYNYOwGsO0AuHUDGLsBbDsAbt0Axm4A2w6AWzeAsRvAtgPg1g1g7Aaw7QC4dQMYuwFsOwBu3QDGbgDbDoBbN4CxG8C2A+DWDWDsBrDtALh1Axi7AWw7AG7dAMZuANsOgFs3gLEbwLYD4NYNYOwGsO0AuHUDGLsBbDsAbt0Axm4A2w6AWzeAsRvAtgPg1g1g7Aaw7QC4dQMYuwFsOwBu3QDGbgDbDoBb98++N0haO7n8OxxYAAAAAElFTkSuQmCC"> <br>81202259202
                    </span>
                    <div style="font-size:13px;clear:left;font-weight:bold">
                    </div>
                </div>
                <div style="position:absolute;height:0.6cm;top:1.7cm;right:1.9cm;text-align:center;font-size:18px;">
                    Blue-Dart
                </div>
                <div style="position:absolute;height:4.1cm;width:1.4cm;top:-2cm;left:8.3cm;text-align:center;font-size:12px;line-height:12px;border-left:2px solid black;">
                </div>
            </div>
            <div style="position: absolute; height: 2.7cm; width: 9.7cm; left: 0cm; font-size: 12px; overflow: hidden; top: 11.55cm;">
                <table style="width:9.7cm ; border-spacing: 0px; padding: 0px;"  >
                    <tbody><tr>
                        <td style="width:2.5cm;border-bottom:2px solid black;border-right:2px solid black;text-align:center;font-size:10px;font-weight:bold;">Description
                        </td>
                        <td style="width:0.5cm;border-bottom:2px solid black;border-right:2px solid black;text-align:center;font-size:10px;font-weight:bold;">Qty
                        </td>

                        <td style="width:2cm;border-bottom:2px solid black;border-right:2px solid black;text-align:center;font-size:10px;font-weight:bold;">SKU
                        </td>

                    </tr>
                    <tr>
                        <td style="text-align:left;padding-left:5px;border-bottom:2px solid black;border-right:2px solid black;font-size:9px;font-family:droidsansfallback;">
                        Adorable Cat Hat Party Costume Accessory Winter Pet Hat for Cats Puppy Party Pink S
                        </td>
                        <td style="border-bottom:2px solid black;border-right:2px solid black;font-size:9px;text-align:center;">1
                        </td>

                        <td style="border-bottom:2px solid black;border-right:2px solid black;font-size:9px;text-align:center;">64067421
                        </td>
                    </tr>
                </tbody></table>
            </div>
        <div style="position: absolute; width: 8.3cm; height: 2cm;">
        </div>
        </div></body></html>


        `;



        // console.log(html)
        // return false;

        // const options = {
        //     format: 'A4',
        //     orientation: 'portrait',
        //     border: '10mm',
        // };

        // var options = {
        //     format: "A4",
        //     orientation: "portrait",
        //     //border: "10mm",
        //     "height": "552",
        //     "width": "395",
            
        // };

        // const document = {
        // html: html,
        // data: {
        //     name: 'John Doe',
        // },
        // path: 'public/labels/output.pdf', // Path to save the generated PDF
        // };

        // pdfCreator
        // .create(document, options)
        // .then((res) => {
        //     console.log('PDF created successfully:', res);
        // })
        // .catch((err) => {
        //     console.error('Error creating PDF:', err);
        // });

}

function upload_image(handle, callback) {
    var d = new Date();//
    const imageDir = "images/" + d.getFullYear().toString() + "/" + (d.getMonth() + 1).toString() + "/" + handle.handle + "/";
    var s3dir = `${imageDir}`;
    var filename = Date.now().toString() + makeid(6) + '.png';
    var options = {
        uri: handle.url,
        encoding: null
    };
    request(options, async function (error, response, body) {
        if (error || response.statusCode !== 200) {
  
  
        } else {
            var status = uploadFile(body, s3dir + filename);
        }
    });
    callback(s3dir + filename);
  }

async function uploadFile(file, key) {
    buf = Buffer.from(file.replace(/^data:image\/\w+;base64,/, ""), 'base64')
    console.log('buf')
    console.log(key)
    // Setting up S3 upload parameters
    const params = {
        Bucket: process.env.S3_FILE_BUCKET,
        Key: key, // File name you want to save as in S3
        Body: buf,
        ContentEncoding: 'base64',
        ContentType: 'image/jpeg'
    }
    console.log
    // Uploading files to the bucket
    s3.upload(params, (err, data) => {
      // s3.putObject(params, function(err, params){
  
        if (err) {
            console.log('err: ', err);
            console.log('Error uploading data: ', params); 
        }
        else {
            console.log('NO ERROR WHILE UPLOADING IMAGE');
        }
    })
}

function chinaPriceAlgoSFC (factoryPrice, product_weight) {
	var STK_Shopperr_price 	  = factoryPrice;
	var product_weight 		    = (product_weight/1000)*1.81;
	var ppPrice 			        = STK_Shopperr_price*12*1.22;
	var getDuty 				      = (ppPrice*38/100);
	var getLandedCost 			  = getDuty+ppPrice;
	var getFrieghtCost 		    = (795*product_weight*1.18);
	var chaCost 				      = 0;   
	var processingCost 		    = 12; 
	var lastMileCost 			    = 85;
	var getTotalCOCGS 			  = getLandedCost+getFrieghtCost+chaCost+processingCost+lastMileCost;
	var profitAdd15Percent 	  = (getTotalCOCGS*15/100)+getTotalCOCGS;
	var gstImpact 				    = ((profitAdd15Percent-getTotalCOCGS)*18/100);
	var gst_price 				    = profitAdd15Percent+gstImpact;
	
	var FourPercentAddInPrice = (gst_price*4)/100;
	var finalShopperrPrice 	  = gst_price+FourPercentAddInPrice;
	var product_msrp 			    = finalShopperrPrice*2.5;
	
	var GSTPrice              = finalShopperrPrice.toFixed(2);
  var productPricemrp       = product_msrp.toFixed(2);
  var totalCOCGS            = getTotalCOCGS.toFixed(2);
  var data                  = { 'price': GSTPrice, 'cogs': totalCOCGS, 'mrp': productPricemrp }
  return data;
}

// exports.updateInQty = async (req, res) => {
//     var fileContent = req.files.file.data
    
//     let csv_data = await csv().fromString(fileContent.toString());
//     let sku_list = [];
//     var d = new Date();
//     // console.log(csv_data)

//     // return false
//     const limitedCsvData = csv_data.slice(0, 15000);
//     await Promise.all(limitedCsvData.map(async (item) => {
//       try {
        
//         // console.log(item.sku+'--'+item.qty)

//         // const orders = await Order.findOneAndUpdate({mkpOrderId: item.mkpOrderId}, {$set: obj}, {orderSerial:1}, { new: true })
//         const existingOrder = await Products.findOne({ "code": item.sku }, { stock:1 });
//         // console.log(existingOrder)
//         if(existingOrder){
//             let updateObj = {
//                 "stock.in_qty" : item.qty
//             }

//             // console.log(item.sku+'--'+item.qty)
//             // console.log(updateObj)

//             await Products.updateOne({ "code": item.sku }, { $set: updateObj }, { upsert: false }).then(() => {
//                 console.log('done-'+item.sku+'--'+item.qty)
//             });

//             return false;

//         }
        
//         let result = { 'error': 0, 'message': 'Safe-T Claim updated successfully' };
//         return res.status(200).json(result);
        

//       }catch(err){
//         let result = { 'error': 1, 'message': err };
//         return { 'error': 1, 'message': err };
//         // return res.status(200).json(result);
//       }
//     }));
// }
