var express = require("express");
var router = express.Router({ mergeParams: true });
var Order=require("../models/order");

router.get("/all/:user_id", function (req, res) {
    Order.find({User: req.user._id}).sort({createdAt:-1}).populate("Product_qty.product").exec( function (err, orders) {
        if (err){console.log(err); return res.redirect("/");} 
            res.render("order/orders", { orders });
    });
});

router.get("/all", function (req, res) {
    Order.find({}).sort({createdAt:-1}).populate("Product_qty.product").exec( function (err, orders) {
        if (err){console.log(err); return res.redirect("/");} 
            res.render("admin/order/orders", { orders });
    });
});

//get order by id
router.get("/:order_id", function (req, res) {
    Order.findOne({_id: req.params.order_id}, function (err, order) {
        res.json({message:"success", order});
    });
});

//update status
router.put("/change_status/:order_id", function (req, res) {
    Order.findByIdAndUpdate({_id: req.params.order_id},{status: req.body.status}, {new: true}, function (err, order) {
        if(req.body.status!="Canceled" && req.user.role!="admin") return res.json({message:"fail", order});
        res.json({message:"success", order});
    })
});


module.exports = router;