const SubCatagory = require("../models/SubCatagory");
const SubSubCatagory = require('../models/SubSubCatagory')
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const ejs = require("ejs");
const path = require("path");

exports.postNew = async function (req, res) {
    console.log("nnnnnn", req.body)
    const { catagoryid, catagory, subcatagory, imageSubCatagory } = req.body;

    if (
        !subcatagory ||
        !imageSubCatagory ||
        !catagoryid ||
        !catagory
    ) {
        return res.status(422).json({
            message: "All feilds are required",
        });
    }
    try {
        const subcatagorie = new SubCatagory({ catagory: catagory, subcatagory: subcatagory, imageSubCatagory: imageSubCatagory, catagoryid: catagoryid });
        const subcatagories = await subcatagorie.save();
        res.status(200).json({ message: "success", subcatagories });
    } catch (error) {
        console.log("is match 1st error===>>>", error)
        res.status(404).json({ success: false, message: error.message });
    }
};



exports.AddSubCat = async function (req, res) {
    console.log("nnnnnn", req.body)
    const { subcatagory, imageSubCatagory, catagory } = req.body;

    if (
        !subcatagory ||
        !imageSubCatagory ||
        !catagory
    ) {
        return res.status(422).json({
            message: "All feilds are required",
        });
    }
    try {
        const catagorie = new SubCatagory({ subcatagory: subcatagory, imageSubCatagory: imageSubCatagory });
        const catagories = await catagorie.updateOne({ _id: catagory });
        res.status(200).json({ message: "success", catagories });
    } catch (error) {
        console.log("is match 1st error===>>>", error)
        res.status(404).json({ success: false, message: error.message });
    }
};


async function updateAllAccessories(subcatagory, id) {
    await SubSubCatagory.updateMany({ subcatagoryid: id }, { subcatagory })
}


exports.UpdateSubCatagory = async function (req, res) {
    console.log("nnnnnn", req.body)
    let id = req.params.id
    const { subcatagory, imageSubCatagory, catagory } = req.body;
    let body = req.body;
    if (
        !subcatagory ||
        !imageSubCatagory ||
        !catagory
    ) {
        return res.status(422).json({
            message: "All feilds are required",
        });
    }


    try {
        const catagories = await SubCatagory.updateOne({ _id: id }, body);
        await updateAllAccessories(subcatagory, id);
        res.status(200).json({ message: "success", catagories });
    } catch (error) {
        console.log("is match 1st error===>>>", error)
        res.status(404).json({ success: false, message: error.message });
    }
};

exports.GetAllSubCatagory = async function (req, res) {
    console.log("abc=====", req.params.id);
    let searchQuery = req.params.id;
    try {
        const subcatagories = await SubCatagory.find();
        res.status(200).json({ message: "Success", subcatagories });
    } catch (error) {
        console.log("is match 1st error===>>>", error)
        res.status(404).json({ success: false, message: error.message });
    }
};



exports.GetAllSubCatagorybySearch = async (req, res) => {
    try {
        const subcatagories = await SubCatagory.find({ subcatagory: new RegExp('^' + req.params.data, 'i') });
        res.status(200).json({ message: "success", subcatagories });
    } catch (error) {
        console.log("Error while fetching all Type from Database", error);
        res.status(500).json({ sucess: false, message: error });
    }
};

exports.getSingle = async function (req, res) {
    console.log("abc=====", req.params.model);
    let model = req.params.model;
    try {
        const subcatagories = await SubCatagory.findOne({ _id: model });
        res.status(200).json({ message: "Success", subcatagories });
    } catch (error) {
        console.log("is match 1st error===>>>", error)
        res.status(404).json({ success: false, message: error.message });
    }
};


exports.GetAllSubCatagoryBrand = async function (req, res) {
    console.log("abc=====", req.params.brandid);
    let brandid = req.params.brandid;
    try {
        const subcatagories = await SubCatagory.find({ catagoryid: brandid });
        res.status(200).json({ message: "Success", subcatagories });
    } catch (error) {
        console.log("is match 1st error===>>>", error)
        res.status(404).json({ success: false, message: error.message });
    }
};
exports.GetAllSubCatagoryBrandName = async function (req, res) {
    const { brandName } = req.params;
    try {
        const subcatagories = await SubCatagory.find({ catagory: brandName });
        res.status(200).json({ message: "Success", subcatagories });
    } catch (error) {
        console.log("is match 1st error===>>>", error)
        res.status(404).json({ success: false, message: error.message });
    }
};


exports.GetSingle = async function (req, res) {
    console.log("abc=====", req.params.id);
    let searchQuery = req.params.id;
    try {
        const subcatagories = await SubCatagory.find({ item: { $regex: new RegExp(searchQuery, 'i') } });
        res.status(200).json({ message: "Success", subcatagories });
    } catch (error) {
        console.log("is match 1st error===>>>", error)
        res.status(404).json({ success: false, message: error.message });
    }
};


exports.getDataByID = async function (req, res) {
    let ID = req.params.id;
    try {
        const subcatagories = await SubCatagory.findOne({ _id: ID });
        res.status(200).json({ message: "Success", subcatagories });
    } catch (error) {
        console.log("is match 1st error===>>>", error)
        res.status(404).json({ success: false, message: error.message });
    }
};


exports.updateSubcatagorySequence = async function (req, res) {
    try {
        const { subcatagoryId, targetSubcatagoryId } = req.body;
        // Fetch products
        const [sourceProduct, targetProduct] = await Promise.all([
            SubCatagory.findById(subcatagoryId),
            SubCatagory.findById(targetSubcatagoryId)
        ]);
        if (!sourceProduct || !targetProduct) {
            return res.status(404).json({ success: false, message: 'Product not found' });
        }
        if (sourceProduct === targetProduct) {
            return res.status(423).json({ success: false, message: 'Same Products cannot be replaced' });
        }
        // Swap the data fields of source and target products
        const updatedSourceProduct = await SubCatagory.findByIdAndUpdate(subcatagoryId, {
            catagory: targetProduct.catagory,
            subcatagory: targetProduct.subcatagory,
            imageSubCatagory: targetProduct.imageSubCatagory
        }, { new: true });
        const updatedTargetProduct = await SubCatagory.findByIdAndUpdate(targetSubcatagoryId, {
            catagory: sourceProduct.catagory,
            subcatagory: sourceProduct.subcatagory,
            imageSubCatagory: sourceProduct.imageSubCatagory
        }, { new: true });
        res.status(200).json({ success: true, message: 'Product sequence updated successfully' });
    } catch (error) {
        console.error('Error updating product sequence:', error);
        res.status(500).json({ success: false, message: 'Internal server error' });
    }
}

exports.DeleteSingl = async function (req, res) {
    let ID = req.params.id;
    try {
        SubCatagory.deleteOne({ _id: ID }, (err, response) => {
            if (response === null) {
                res.json({ message: "User Not Found" })
            } else {
                console.log("user found")
                res.status(200).json({ response, message: "SuccessDelete" })
            }
        });
    } catch (error) {
        console.log("is match 1st error===>>>")
        res.status(404).json({ success: false, message: error.message });
    }
};


exports.DeleteSinglProduct = async function (req, res) {
    let ID = req.params.id;
    try {
        SubCatagory.deleteOne({ _id: ID }, (err, response) => {
            if (response === null) {
                res.json({ message: "User Not Found" })
            } else {
                console.log("user found")
                res.status(200).json({ response, message: "SuccessDelete" })
            }
        });
    } catch (error) {
        console.log("is match 1st error===>>>")
        res.status(404).json({ success: false, message: error.message });
    }
};