const Orders = require("../models/Order");
const Email = require("../controllers/email");
const User = require("../models/User");
const pKey = require('../stripeKey');
const Order = require("../models/Order");
const stripe = require('stripe')(pKey);

exports.neworder = async function (req, res) {
    console.log("nnnnnn", req.body);
    const { clientid, role, product, totalprice  , name } = req.body;
    let orderr = req.body;
    if (
        !clientid ||
        !role ||
        !product ||
        !totalprice ||
        !name
    ) {
        return res.status(422).json({
            message: "All feilds are required",
        });
    }
    try {
        const order = new Orders(orderr);
        let user = await User.findOne({ _id: clientid });
        
        await Email.NewOrder(user, res);
        const orders = await order.save();
        res.status(200).json({ message: "success", orders });
    } catch (error) {
        console.log("is match 1st error===>>>", error)
        res.status(404).json({ success: false, message: error.message });
    }
};

exports.CreateOrder = async function(req,res){
    try {
        const newOrder = await Order.create({...req.body,siteOrder:"trade"}); // Only trade site is going to get these orders;
        await Email.MailToAdminForCreatingOrder(newOrder);
        res.status(201).json({success:true, message:'Successfully created new order',order:newOrder});
    } catch (error) {
        console.log("error creating new order===>>>", error)
        res.status(500).json({ success: false, message: error.message });
    }
}



exports.updateStripeStatusOrder = (async (req, res, next) => {
    console.log("first=====", req);
    try {
        const siteorders = await Orders.updateOne({ _id: req.ID }, { paymentSessionID: req.sessionID, });
        return siteorders;
    }
    catch (error) {
        console.log("bbbbb", error.code)
        res.send({ success: false, message: error.code, status: error.code });
    }
});


exports.postNewOrder = (async (req, res, next) => {
    // console.log("first=====", req.body.data);
    let productInfo = req.body.data; 
    try {
        // Fetch the last order from the database to get the latest order number
        const lastOrder = await Orders.findOne().sort({ orderNumber: -1 });
        let orderid = 1; // Default order ID if no orders exist yet

        if (lastOrder) {
            // If there's a last order, increment the order ID by 1
            orderid = lastOrder.orderNumber + 1;
        }

        // Create a new order with the incremented order ID
        const siteorder = new Orders({ productInfo: productInfo, userid: productInfo[0].userid, customerName: "default", customerEmail: "default", deliverycharges: req.body.deliverycharges,  orderNumber: orderid });
        const siteorders = await siteorder.save();
        return siteorders;
    }
    catch (error) {
        console.log("Error:", error);
        res.status(500).send({ success: false, message: "Internal Server Error", status: 500 });
    }
});


exports.updateStatusPay = (async (req, res, next) => {
    try { 
        let data = await Orders.find({ _id: req.params.id })
        // console.log("data==", data)
        let sessionID = data[0].paymentSessionID;
        stripe.checkout.sessions.retrieve(sessionID, async (err, session) => {
            if (err) {
                console.error("err");
                return res.status(500).json({ error: 'An error occurred while retrieving session details from Stripe.' });
            }
            if (session.payment_status === "paid") {
                let name = session.customer_details.name;   
                let email = session.customer_details.email;
                let phone = session.customer_details.phone;
                let postalcode = session.customer_details.address.postal_code;
                let address = session.customer_details.address.line1;
                const siteorders = await Orders.updateOne({ _id: req.params.id }, { paymentStatus: "paid", customerName: name, customerEmail: email, customerPhone: phone, postalCode: postalcode, customerAddress: address });
                console.log("sending emails")
                await Email.MailToAdmin(session, data[0] , res);
                await Email.NewOrder(session , data[0] , res); 
                res.status(200).json({ message: "Success", siteorders });
            } else {    
                console.log('Payment Status not paid:');
                res.status(404).json({ success: false, message: "No Paid" });
            }
        });

    }
    catch (error) {
        console.log("Error", error)
        res.send({ success: false, message: error.code, status: error.code });
    }
});



exports.getall = async function (req, res) {
    try { 
        const orders = await Orders.find({}); 
        
        res.status(200).json({ message: "Getting", orders });
    } catch (error) {
        console.log("is match 1st error===>>>", error);
        res.status(404).json({ success: false, message: error.message });
    }
};






exports.getallPaid = async function (req, res) {
    try {
        const orders = await Orders.find({ paymentStatus: "paid" });

        res.status(200).json({ message: "Getting", orders });
    } catch (error) {
        console.log("is match 1st error===>>>", error);
        res.status(404).json({ success: false, message: error.message });
    }
};

exports.statusChange = async function (req, res) {
    try {
        console.log("Abc-====", req.body)
        console.log("Abc-====", req.params.orderNumber)
        const orders = await Orders.update({orderNumber: req.params.orderNumber } , { $set: { readyStatus: req.body.readyStatus } });

        res.status(200).json({ message: "Getting", orders });
    } catch (error) {
        console.log("is match 1st error===>>>", error);
        res.status(404).json({ success: false, message: error.message });
    }
};




exports.trackOrderStatus = async function (req, res) {
    console.log("abc====", req.params.orderNumber)
    try {
        const orders = await Orders.findOne({ orderNumber : req.params.orderNumber});

        res.status(200).json({ message: "Getting", orders });
    } catch (error) {
        console.log("is match 1st error===>>>", error);
        res.status(404).json({ success: false, message: error.message });
    }
};




exports.CancelSelingByUser = async function (req, res) {
    let ID = req.params.id;
    try {
        console.log("Searching for product ID:", ID);
        const order = await Orders.findOne({ "product": { $elemMatch: { "data._id": ID } } }); // Find the order containing the product with the provided ID
        if (!order) {
            console.log("Product not found in any order");
            return res.status(404).json({ message: "Product not found in any order" });
        }
        const productIndex = order.product.findIndex(product => product.data._id === ID);
        if (productIndex === -1) {
            console.log("Product not found in the order");
            return res.status(404).json({ message: "Product not found in the order" });
        }
        console.log("Abc4", order.product[productIndex].data.price)
        let totalprice = order.totalprice - order.product[productIndex].data.price;
        console.log("Abc3", totalprice)
        const removedProduct = order.product.splice(productIndex, 1);
        order.totalprice = totalprice;
        order.product.splice(productIndex, 1);
        await order.save();
        let user = await User.findOne({ _id: order.clientid });

        await Email.removedProduct(removedProduct, user, res)
        // console.log("Product removed successfully from order:", removedProduct)
        res.status(200).json({ message: "Success", order });

    } catch (error) {
        console.log("Error occurred:", error.message);
        res.status(500).json({ success: false, message: error.message });
    }
};




exports.Delete = async function(req,res){
    const id=req.params.id;
    try {
        if(!id){
            return res.status(400).json({ success: false, message: 'Id id not found'});
        }
        await Orders.findByIdAndDelete(id);
        return res.status(200).json({ success: true, message: 'Deleted Order'});
    } catch (error) {
        console.log("Error occurred:", error.message);
        res.status(500).json({ success: false, message: error.message });
    }
}

exports.GetOrderByID = async(req,res)=>{
    const id=req.params.id;
    try {
        if(!id){
            return res.status(400).json({ success: false, message: 'Id id not found'});
        }
        const order = await Orders.findOne({_id:id});
        return res.status(200).json({ success: true, message: 'Order found',order});
    } catch (error) {
        console.log("Error occurred:", error.message);
        res.status(500).json({ success: false, message: error.message });
    }
}



