const pool = require('../db/connection');
const transporter = require('../services/mailService'); // importa el transporter

const getContracts = async (req, res) => {
  try {
    // Leer query params con valores por defecto
    const page = parseInt(req.query.page) || 1;   // Página actual
    const limit = parseInt(req.query.limit) || 1000; // Cantidad por página
    const offset = (page - 1) * limit;           // Desde dónde empezar

    // Llamamos a la función con LIMIT y OFFSET
    const result = await pool.query(
      `SELECT * FROM getcontracts() LIMIT $1 OFFSET $2`,
      [limit, offset]
    );

    // Obtener total para calcular páginas
    const totalResult = await pool.query('SELECT COUNT(*) FROM contracts');
    const total = parseInt(totalResult.rows[0].count);
    const totalPages = Math.ceil(total / limit);

    const contracts = result.rows.map(con => ({
      id_contract: con.id_contract,
      name_employee: con.name_employee,
      position_employee: con.position_employee,
      area_employee: con.area_employee,
      contract_start: con.contratc_start,
      contract_end: con.contratc_end,
      uniforms: con.uniforms,
      daily_pay: con.daily_pay,
      status_contract: con.status_contract,
    }));

    res.json({
      page,
      limit,
      total,
      totalPages,
      data: contracts
    });

  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Error al obtener los contratos' });
  }
};
//CONTRATOS CERCA DE TERMINAR, 1 MES O MENOS DE TIEMPO
const neartoend = async (req, res) => {
  try {
        const result = await pool.query(
      'SELECT * FROM contratcsneartoend() as contractsneartoend',
    );
    const neartoend = result.rows[0].contractsneartoend;

    res.json({
      message: 'Contratos cerca de terminar',
      data: neartoend
    });

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


//listado de posiciones
const getpositions = async (req, res) => {
  try {
        const result = await pool.query(
      'SELECT * FROM getpositions()',
    );
     const positions = result.rows.map(pos => ({
      id_position: pos.id_position,
      name_position: pos.name_position,
      spanish_name: pos.spanish_name
    }));

    res.json({
        data:positions
    });

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

const getareas = async (req, res) => {
  try {
        const result = await pool.query(
      'SELECT * FROM getareas()',
    );
     const areas = result.rows.map(ar => ({
      id_area: ar.id_area,
      name_area: ar.name_area,
    }));

    res.json({
        data:areas
    });

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

const newContract = async (req, res) => {
  try {
      const {
            rfc_emp,
            id_position_emp,
            id_area_emp,
            start_contract,
            end_contract,
            new_daily_pay,
            boss_rfc,
          	boss_name,
            uniforms} = req.body;
      let message = "";

      const result = await pool.query('SELECT newcontract($1,$2,$3,$4,$5,$6,$7,$8,$9::jsonb) AS status', 
            [rfc_emp,id_position_emp,id_area_emp,start_contract,end_contract,new_daily_pay,boss_rfc,boss_name,JSON.stringify(uniforms)]);
      const newcontract = result.rows[0].status;        
            if(newcontract == 1)
              message = "Contrato generado correctamente";
            else
              message = "No se pudo agregar el contrato"
            res.json({
              message,
              idNewContract: newcontract
            });
    } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'No se pudo generar el nuevo contrato' });
  }
}
const updateContract = async (req, res) => {
  try {
      const {
            rfc_emp,
            id_position_emp,
            id_area_emp,
            start_contract,
            end_contract,
            status_contract,
            new_daily_pay,
            boss_rfc,
            boss_name,
            reason,
            uniforms} = req.body;
            const { id } = req.params;
      let message = "";

      const result = await pool.query('SELECT updatecontract($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12::jsonb) AS status', 
            [id,rfc_emp,id_position_emp,id_area_emp,start_contract,end_contract,status_contract,new_daily_pay,boss_rfc,boss_name,reason,JSON.stringify(uniforms)]);
      const newcontract = result.rows[0].status;        
            if(newcontract == 1)
              message = "Contrato actualizado correctamente";
            else
              message = "No se pudo actualizar el contrato"
            res.json({
              message,
              idNewContract: newcontract
            });
    } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'No se pudo generar el nuevo contrato' });
  }
};

const getContract = async (req, res) => {
  try {
    
    const { id } = req.params;
    console.log(id);
    
    const result = await pool.query(
      `SELECT * FROM getcontracts() WHERE id_contract = $1 LIMIT 1  `,
      [id]
    );
    const contracts = result.rows.map(con => ({
      id_contract: con.id_contract,
      name_employee: con.name_employee,
      position_employee: con.position_employee,
      area_employee: con.area_employee,
      contract_start: con.contratc_start,
      contract_end: con.contratc_end,
      uniforms: con.uniforms,
      daily_pay: con.daily_pay,
      status_contract: con.status_contract
    }));

    res.json({

      data: contracts
    });

  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Error al obtener los contratos' , error});
  }
};

const getbosses = async (req, res) => {
  try {
    
    const result = await pool.query(
      `SELECT * FROM getbosses()`
    );
    const bosses = result.rows.map(con => ({
      rfc_boss: con.rfc_boss,
      name_boss: con.name_boss,
    }));

    res.json({

      data: bosses
    });

  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'No se pudieron obtener los jefes' , error});
  }
};

const disabledcontracts = async (req, res) => {
  try {
        const result = await pool.query(
      'SELECT * FROM disabledcontracts() as total',
    );
    const disabled = result.rows[0].contractsneartoend;

    res.json({
        message: "contratos expirados",
        data:disabled
    });

  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Error al obtener las areas' });
  }
};
const reportEmployeeContract = async (req, res) => {
  try {
        const result = await pool.query(
      'SELECT * FROM reportemployeecontract()',
    );
     const report = result.rows.map(rep => ({
      name_employee: rep.name_employee,
      rfc_employee: rep.rfc_employee,
      nss_employee: rep.nss_employee,
      name_position: rep.name_position,
      spanish_name: rep.spanish_name,
      name_area: rep.name_area,
      addres_employee: rep.name_area, 
      phone_employee: rep.phone_employee,
      email_employee: rep.email_employee ,
      birthday: rep.birthday,
      curp: rep.curp , 
      name_study: rep.name_study,
      id_contract: rep.id_contract , 
      contratc_start:rep.contract_start, 
      contratc_end: rep.contract_end, 
      name_status: rep.name_status , 
      daily_pay:rep.daily_pay , 
      rfc_boss: rep.rfc_boss , 
      name_boss: rep.name_boss , 
      reasonfordismissal: rep.reasonfordismissal ,
      name_contact: rep.name_contact, 
      tel_contact: rep.tel_contact ,
      name_relationship: rep.name_relationship
      
    }));

    res.json({
        data:report
    });

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

module.exports = { 
  getContract,
  getContracts,
  neartoend,
  getpositions,
  getareas,
  newContract,
  updateContract,
  disabledcontracts,
  getbosses,
  reportEmployeeContract
};