const pool = require('../db/connection');

const newMonthlyExpense = async (req, res) => {
    try{
        const {
            descriptionex,
            recurrence_id,
            payment_type,
            currency_id,
            suppliers_id,
            area,
            expense_category,
            day_expense,
            tax_id,
            new_subtotal,
        } = req.body;
        const subtotal = new_subtotal && !isNaN(parseFloat(new_subtotal))? parseFloat(new_subtotal): 0;
        const result = await pool.query('SELECT newmonthlyexpensev2($1,$2,$3,$4,$5,$6,$7,$8,$9,$10) AS status',[
            descriptionex,recurrence_id,payment_type,currency_id,suppliers_id,
            area,expense_category,day_expense,tax_id,parseFloat(subtotal)]);

        const newMonthly = result.rows[0].status; 
            res.json({
              message: "Gasto mensual agregado correctamente",
              status: newMonthly
            });

    }catch(error)
    {
    console.error(error);
    res.status(500).json({ message: 'No se puede agregar el gasto mensual',error });
    }
};
const setPaymentStatusMonthly = async (req, res) => {
    try{
    
    const {id} = req.params;
    const {
            status_payment,
            tax_id,
            subtotal,
        } = req.body;
    const total    = subtotal    && subtotal    !== '' ? subtotal   : null;
    if(total ==null)
    {
    const result = await pool.query('SELECT setpaymentstatusmonthlyv2($1,$2) as status',[id,status_payment]);
    const statuspayment = result.rows[0].status;
    res.json({
    message:'Se actualizo el estatus del pago correctamente',
    status_monthly: statuspayment
        });
    }else{
     const result = await pool.query('SELECT setpaymentstatusmonthlyv2($1,$2,$3,$4) as status',[id,status_payment,tax_id,parseFloat(total)]);
     const statuspayment = result.rows[0].status;
     res.json({
     message:'Se actualizo estatus y pago correctamente',
     status_monthly: statuspayment
        });

    }
    }catch(error){
    console.error(error);
    res.status(500).json({ message: 'No se pudo actualizar el pago' });
    }
};

const refreshMonthlyExpenses = async(req,res) =>{
    try{
    const result = await pool.query('SELECT refresh_monthly_expenses() as status');
    const refresh = result.rows[0].status; 
    res.json({
    message:"se realizo actualizacion de gastos mensuales",
    status_monthly: refresh
        });
    }catch(error){
    console.error(error);
    res.status(500).json({ message: 'No se pudo actualizar' });
    }
    
};

const updateMonthlyExpense = async (req, res) => {
    try{
        const {
            descriptionex,
            recurrence_id,
            payment_type,
            currency_id,
            suppliers_id,
            area,
            expense_category,
            day_expense,
            tax_id,
            new_subtotal,
        } = req.body;
        const {id} = req.params;
        const subtotal = new_subtotal && !isNaN(parseFloat(new_subtotal))? parseFloat(new_subtotal): 0;
        const result = await pool.query('SELECT updatemonthlyexpensev2($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11) AS status',
            [id,descriptionex,recurrence_id,payment_type,currency_id,suppliers_id,
            area,expense_category,day_expense,tax_id,parseFloat(subtotal)]);

        const update = result.rows[0].status; 
            res.json({
              message: "Gasto mensual actualizado correctamente",
              status: update
            });

    }catch(error)
    {
    console.error(error);
    res.status(500).json({ message: 'No se puede actualizar el gasto mensual' });
    }
};
const getOneMonthly = async (req, res) => {
    try{
       const {id} = req.params;
         const result = await pool.query('SELECT * FROM getONEmonthlypayment($1)',[id]);

    const monthlypayment = result.rows.map(mp => ({
      expense_id: mp.expense_id,
      descriptionex: mp.descriptionex,
      recurrence_id: mp.recurrence_id,
      payment_type: mp.payment_type,
      currency_idea: mp.currency_id,
      suppliers_id: mp.suppliers_id,
      area: mp.area,
      expense_category: mp.expense_category,
      day_expense: mp.day_expense,
      tax_id: mp.tax_id,
      new_subtotal: mp.new_subtotal
    }));



    res.json({
        data:monthlypayment
    });

    }
    catch(error)
    {
    console.error(error);
    res.status(500).json({ message: 'Error al obtener el pago mensual' });
    }

};
const needtorefresh = async (req, res) => {
    try{
       const {id} = req.params;
       const {notrefresh} = req.body;
       let mensaje;
        const result = await pool.query('SELECT needToRefresh($1,$2)',[id,notrefresh]);
        const rows = result.rowCount;
        if (notrefresh == true)
            mensaje = 'El gasto mensual se estara actualizando.';
        else
            mensaje = 'El gasto mensual NO se estara actualizando'
    res.json({
        data:rows,
        message: mensaje
    });

    }
    catch(error)
    {
    console.error(error);
    res.status(500).json({ message: 'No se pudo completar la accion' });
    }

};



module.exports = {newMonthlyExpense,setPaymentStatusMonthly,refreshMonthlyExpenses,updateMonthlyExpense,getOneMonthly,needtorefresh};