const config = require('config.json');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const db = require('helpers/db');
const { Op, QueryTypes } = require('sequelize');
const e = require('express');
const moment = require('moment');


module.exports = {
    getAll,
    getFilter,
    getOne, 
    getName,
    getOption,
    getCount,
    create,
    update,
    delete: _delete,
    replace,
    getLatestDocumentNo,
    getByDocumentNo,
    getDocumentTerritory,
    getDocumentTerritoryEmployee,
};

// ============================= || FUNCTION || ============================= //

async function getAll() {
    const callplans = await db.ASA_CallPlan.findAll({
        order: [
            ['modified', 'DESC']
        ],
    });

    const success = true;
    const message = "Loaded Successfully!";

    return  { callplans: callplans, success, message };
}

async function getOne(id) {
    const callplan = await getCallPlan(id); 

    const success = true;
    const message = "Loaded Successfully!";

    return  { callplan: callplan, success, message };
}

// ?
async function getName(id) {
    const callplan = await db.ASA_CallPlan.findAll({
        attributes: ['document_no'],
        where: { 
            id: id 
        },
    });

    const success = true;
    const message = "Loaded Successfully!";

    return  { callplan: callplan, success, message };
}

async function getOption() {
    const callplans = await db.ASA_CallPlan.findAll({
        attributes: ['id', 'document_no', 'territory'],
        where: { 
            enabled: true 
        },
    });

    const success = true;
    const message = "Loaded Successfully!";

    return  { callplans: callplans, success, message };
}

async function getByDocumentNo(document) {
    const callplans = await db.ASA_CallPlan.findAll({
        where: {
            document_no : document
        }
    });

    const success = true;
    const message = "Loaded Successfully!";
    return  { callplans : callplans , success, message}
}

async function getFilter(params) {
    console.log('params : ', params)
    let { start_date, end_date, territory, document } = params;
    const whereCondition = {};


    if (territory && start_date && end_date) {
        whereCondition.territory = territory;
        whereCondition.from_date = {
            [Op.gte]: start_date, // >= tanggal 1 bulan sebelumnya
        },
        whereCondition.to_Date = {
            [Op.lte]: end_date, // <= tanggal terakhir bulan berikutnya
        }
    }

    // Tambahkan kondisi untuk document jika ada
    if (document && document.trim() !== '') {
        whereCondition.document = document;
    }

    // Log untuk memastikan kondisi where sudah benar
    console.log('whereCondition : ', whereCondition);

    try {
        const callplans = await db.ASA_CallPlan.findAll({
            where: whereCondition,
            order: [['modified', 'DESC']],
        });

        return { callplans, success: true, message: "Loaded Successfully!" };
    } catch (error) {
        console.error('Error fetching data:', error);
        return { success: false, message: "Failed to load data" };
    }
}


async function getDocumentTerritory(territory) {
     // Ambil tanggal 1 dari bulan sebelumnya
    const startDate = moment().subtract(1, 'month').startOf('month').toDate();
    
    // Ambil tanggal terakhir dari bulan berikutnya
    const endDate = moment().add(1, 'month').endOf('month').toDate();
    const callplans = await db.ASA_CallPlan.findAll({
        where: {
            territory: territory,
            from_date: {
                [Op.gte]: startDate, // >= tanggal 1 bulan sebelumnya
            },
            to_date: {
                [Op.lte]: endDate, // <= tanggal terakhir bulan berikutnya
            }
        },
        order: [
            ['modified', 'DESC']
        ], 
    });

    const success = true;
    const message = "Loaded Successfully!";
    return  { callplans : callplans , success, message}
}

async function getDocumentTerritoryEmployee(params) {
    const callplans = await db.ASA_CallPlan.findAll({
         where: { 
            territory: params.values.territory,
            // employee_name: params.values.employee_name,
            company: params.values.company
        },
        order: [
            ['modified', 'DESC']
        ],
        
    });

    const success = true;
    const message = "Loaded Successfully!";

    return  { callplans: callplans, success, message };
}

async function getCount() {
    var callplanCount = await db.ASA_CallPlan.count({ 
        where: { 
            enabled: true 
        },
       
    })

    const success = true;
    const message = "Loaded Successfully!";

    // return
    return { count: callplanCount, success, message};
}

async function create(params) {
    // validate
    if (await db.ASA_CallPlan.findOne({ where: { document_no: params.document_no } })){
        throw 'Document No "' + params.document_no + '" is already taken. Try again!';
    }

    // save
    await db.ASA_CallPlan.create(params);

    // default format return
    // const callplans = await db.ASA_CallPlan.findAll({
    //     order: [
    //         ['modified', 'DESC']
    //     ],
    // });
    
    const success = true;
    const message = "Your data has been saved!";

    // return
    return  { success, message }
}

async function update(id, params) {
    const callplan = await getCallPlan(id);

    // validate
    const callplanChanged = params.callplan && callplan.document_no !== params.document_no;
    if (callplanChanged && await db.ASA_CallPlan.findOne({ where: { callplan: params.callplan } })) {
        throw 'Call Plan or Document No "' + params.callplan + '" is already taken. Try again!';
    }
    // copy params to user and save
    Object.assign(callplan, params);
    await callplan.save();

    // default format return
    // const callplans = await db.ASA_CallPlan.findAll({
    //     order: [
    //         ['modified', 'DESC']
    //     ],
    // });

    const success = true;
    const message = "Your data has been updated!";

    // return
    return  { success, message }
}

async function getLatestDocumentNo(parameter) {
    const callplan = await db.ASA_CallPlan.findOne({ 
        where: { territory: parameter },
        order: [['id', 'DESC']],
    }); 
      return {callplan: callplan}
}

async function _delete(id) {
    const callplan = await getCallPlan(id);
    await callplan.destroy();

    // const callplans = await db.ASA_CallPlan.findAll({
    //     order: [
    //         ['modified', 'DESC']
    //     ],
    // });

    const success = true;
    const message = "Your data has been deleted!";

    return  { success, message }
}

async function replace(params) {
    // save Call Plan List
    await db.ASA_CallPlan.upsert(params);

    // default format return
    // const callplans = await db.ASA_CallPlan.findAll({
    //     order: [
    //         ['modified', 'DESC']
    //     ],
    // });
    
    const success = true;
    const message = "Your data has been updated!";

    // return
    return  { success, message }
}

// ============================= || HELPER FUNCTION || ============================= //
async function getCallPlan(id) {
    const callplan = await db.ASA_CallPlan.findByPk(id);
    if (!callplan) throw 'Call Plan not found, please kindly check!';
    return callplan;
}
