const mongoose = require("mongoose");
const request = require('request-promise');
const Order = mongoose.model("Orders");
const User = mongoose.model("User");
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 ReturnStockage = mongoose.model("ReturnStockage");
const Wmsorder = mongoose.model("Wmsorder");
const Indiaoffshelf = mongoose.model("Indiaoffshelfs")
const Pincode = mongoose.model("Pincode")
const Baging = mongoose.model("Baging")
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 axios = require('axios');

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

const xlsx = require('xlsx');

const csv = require('csvtojson');

const ID = 'AKIAZQ3DPSAOW34EMAWP';
const SECRET = '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';
const BUCKET_NAME = 'test-bucket';
const s3 = new AWS.S3({
    accessKeyId: ID,
    secretAccessKey: SECRET,
    apiVersion: 'latest',
});



exports.getReturnScannedDataByDateRange = async (req, res) => {
  try {
    let d = new Date();
    const s3dir = `import_export/${d.getFullYear()}/${d.getMonth() + 1}/`;
    const filename = `${makeid(6)}_.csv`;
    const fullPath = s3dir + filename;

    // Build date range query
    let query = {};
	if (req.body.fromDate && req.body.toDate) {
	  const from = new Date(req.body.fromDate + 'T00:00:00.000Z');
	  const to = new Date(req.body.toDate + 'T23:59:59.999Z');

	  query.date_added = {
		$gte: from,
		$lte: to
	  };
	}


    //console.log("MongoDB Query:", query);

    const scannedData = await ReturnStockage.find(query).lean();
    
    if (!scannedData || scannedData.length === 0) {
      return res.status(404).json({ message: "No records found for given date range" });
    }
	//console.log("MongoDB Query:", scannedData);
    // TEMP: return data as JSON to test
    return res.status(200).json({ data: scannedData });

  } catch (e) {
    console.error("Error in getReturnScannedDataByDateRange:", e);
    return res.status(500).json({ message: e.message });
  }
};


const generateCSVFile = (data) => {
    const worksheet = xlsx.utils.json_to_sheet(data);
    const csv = xlsx.utils.sheet_to_csv(worksheet);
    return csv;
};

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 {

        }
    });
};
