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

const setapprovalstatus = async (req, res) => {
  try {
    const { id } = req.params;
    const {status, approved_by}  = req.body;
    console.log('params:', id);
    console.log('body:', status);
    const result = await pool.query('SELECT setapprovalstatus($1,$2,$3) AS status',[id,status,approved_by]);
    const updateapproval = result.rows[0].status; 
    if(updateapproval == 3)
    {
        res.json({
        message: "El usuario no tiene permisos para aprobar.",
        new_product: updateapproval
    });
    }else{
    res.json({
        message: "Se actualizo correctamente el estatus de aprobación",
        new_product: updateapproval
    });

    }
        
  }
  catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Error al actualizar el estatus de aprobacion' });
  }

};

const setpaymentstatus = async (req, res) => {
  try {
    const { id } = req.params;
    const {status}  = req.body;
    console.log('params:', id);
    console.log('body:', status);
    const result = await pool.query('SELECT setpaymentstatusv2($1,$2) AS status',[id,status]);
    
    const updatepayment = result.rows[0].status; 
    if(updatepayment == -3){
        res.json({
        message: "El gasto no esta aprobado o fue rechazado",
        paymentstatus: updatepayment
    });}
    else {
              res.json({
        message: "Se actualizo correctamente el estatus del pago",
        paymentstatus: updatepayment
      });
    }
  }
  catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Error al actualizar el estatus del pago' });
  }

};

const pendingAppPayments = async (req, res) => {
try{
const result = await pool.query('SELECT pendingapppayments() AS pendingapp',);
const pendingapprov = result.rows[0].pendingapp;

console.log(result.rows[0].pendingApp);
        res.json({
        message: "Pagos pendientes de aprobación",
        data: pendingapprov
    });

}catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Error al obtener pagos pendientes por aprobar' });
  }
};

const countDelayPayments = async (req, res) => {
try{
const result = await pool.query('SELECT countdelaypayments() AS delaypayments',);
const delayPay = result.rows[0].delaypayments; 
        res.json({
        message: "Pagos con retraso",
        data: delayPay
    });

}catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Error al obtener pagos con retraso' });
  }
};
const totalSpent = async (req, res) => {
try{
const result = await pool.query('SELECT totalspent() AS spent',);
const totalSpent = result.rows[0].spent; 
        res.json({
        message: "Total gastado",
        data: totalSpent
    });

}catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Error al obtener total gastado' });
  }
};

  module.exports = { setapprovalstatus,setpaymentstatus,pendingAppPayments,countDelayPayments,totalSpent };