var express = require("express");
var router = express.Router({ mergeParams: true });
var Category = require("../models/category");
var Sub_item = require("../models/sub_item");


router.post("/new_category", function (req, res) {
    console.log(req.body);
    Category.findOne({ name: req.body.name }, function (err, cat) {
        if (err || cat) {
            console.log(err);
            return res.redirect("/admin");
        }
        Category.create({ name: req.body.name }, function (err, cat) {
            if (err) {
                console.log(err);
                return res.json({ message: "fail" });
            }
            if (req.body.render) { return res.redirect("/admin"); }
            res.json({ message: "success", cat });
        });
    });
});

router.post("/new_subItem", function (req, res) {
    var catName = req.body.catName;
    var subItemName = req.body.subItemName;
    Category.findOne({ name: catName }, function (err, cat) {

        if (err || !cat) {
            console.log(err);
            return res.json({ message: "fail", desc: "cat: " + cat })
        }

        Sub_item.create({ name: subItemName }, function (err, sub_item) {
            if (err) {
                console.log(err);
                return res.json({ message: "fail" });
            }
            cat.Sub_items.push(sub_item);
            cat.save(function () {
                res.json({ message: "success", sub_item })
            });
        })

    })
});







module.exports = router;