const Subscribe = require('../models/subscription')

class subscriptionController {
    static async subscribe(req, res) {
        try {
            if (req.body) {
                var { apps_data, user_id, email, subscription_type, offer_code, start_date } = req.body;
                var subs_data = await Subscribe.findOne({ user_id: user_id }).exec()
                if (!subs_data) {
                    let subscribe_data = new Subscribe({
                        apps_data: apps_data,
                        user_id: user_id,
                        email: email,
                        subscription_type: subscription_type,
                        offer_code: offer_code,
                        start_date: start_date
                    });
                    await subscribe_data.save();
                    res.send({ "Success": "Data has been stored successfully!!", "email": email });
                    // -----------------------Mail Function End --------------------
                } else {
                    // console.log(`in SubscriptionController's line no. 23 - existing User`);
                    subs_data.subscription_type = subscription_type;
                    subs_data.offer_code = offer_code;
                    subs_data.email = email;
                    subs_data.start_date = start_date;
                    await subs_data.save();
                    res.send({ "Success": "Data has been updated successfully!!", "email": email });
                    // -----------------------Mail Function End --------------------
                }
            } else {
                res.send({ "Error": "Data haven't received." });
            }
        } catch (error) {
            res.send({ "Error": "Data haven't received.", "Error": error });
        }
    }
}

module.exports = subscriptionController