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

const getEmployees = 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) || 500; // 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 getemployees() LIMIT $1 OFFSET $2`,
      [limit, offset]
    );

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

    const employees = result.rows.map(emp => ({
      employee_rfc: emp.employee_rfc,
      name_employee: emp.name_employee,
      nss_employe: emp.nss_employe,
      position_employee: emp.position_employee,
      area_employee: emp.area_employee,
      phone_employee: emp.phone_employee,
      end_contract: emp.end_contract,
      daily_pay: emp.daily_pay,
      uniforms: emp.uniforms,
      status: emp.status,
      birthday: emp.birthday,
      curp: emp.curp
    }));

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

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

//TOTAL DE EMPLEADOS CON CONTRATO ACTIVO
const getTotalActiveEmployees = async (req, res) => {
  try {

    const result = await pool.query(
      'SELECT * FROM activeemployeesnumber() as activenumber',
    );
    const activeEmployees = result.rows[0].activenumber;

    res.json({
      message: 'Total de empleados activos',
      data: activeEmployees
    });

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

//OBTENER UN SOLO EMPLEADO
const getEmployee = async (req, res) => {
  try {
    const { rfcEmployee} = req.body;
    const result = await pool.query(
      'SELECT * FROM getoneemployee($1)',
      [rfcEmployee]
    );

    const employee = result.rows.map(emp => ({
      name_emp: emp.name_emp,
      rfc_emp: emp.rfc_emp,
      nss_emp: emp.nss_emp,
      id_position_emp: emp.id_position_emp,
      id_area_emp: emp.id_area_emp,
      addres_emp:emp.addres_emp,
      phone_emp: emp.phone_emp,
      email_emp: emp.email_emp,
      daily_pay: emp.daily_pay,
      uniforms: emp.uniforms,
      birthday: emp.birthday,
      curp: emp.curp
    }));
    
   if (result.rows.length > 0) {
       res.json({
        message: 'Empleado existio previamente',
        data: employee 
      });
    }
    else
    {
       res.json({
        message: 'El pleneado no existe.',
        data: 0 // Devuelve la primera fila (o todas si quieres)
      });
    }

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

const newEmployee = async(req,res)=>{
  try{
    const { 
      name_emp,
      rfc_emp,
      nss_emp,
      addres_emp,
      phone_emp,
      email_emp,
      birthday_emp,
      curp_emp,
      study_emp ,
      emergency_name ,
      emergency_tel,
	    relationship_id
    } = req.body;
    const result = await pool.query('SELECT newemployee($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12) AS STATUS',
      [name_emp,rfc_emp,nss_emp,addres_emp,phone_emp,email_emp,birthday_emp,curp_emp, study_emp, emergency_name, emergency_tel,relationship_id]
    );
    const status = result.rows[0].status;
    if(status == 1)
      message = "Empleado añadido correctamente";
    else
      message = "Empleado no se pudo agregar"
            res.json({
              message,
              status: status
            });
  }catch(error){
    console.error(error);
    res.status(500).json({ error });
  }

}
const updateEmployee = async(req,res)=>{
  try{
    const { 
      name_emp,
      rfc_emp,
      nss_emp,
      addres_emp,
      phone_emp,
      email_emp,
      birthday_emp,
      curp_emp,
      study_emp ,
      emergency_name ,
      emergency_tel,
	    relationship_id
    } = req.body;
    const result = await pool.query('SELECT updateemployee($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12) AS STATUS',
      [name_emp,rfc_emp,nss_emp,addres_emp,phone_emp,email_emp,birthday_emp,curp_emp, study_emp,
      emergency_name, emergency_tel, relationship_id]
     );
    const status = result.rows[0].status;
    if(status == 1)
      message = "Empleado actualizado correctamente";
    else
      message = "No se pudo agregar el empleado"
            res.json({
              message,
              status: status
            });
  }catch(error){
    console.error(error);
    res.status(500).json({ error });
  }

}
const getattendance = async (req, res) => {
  try {
    const result = await pool.query(
      'SELECT * FROM getattendance()',
    );

    const attendance = result.rows.map(emp => ({
      aid_attendance: emp.aid_attendance,
      aname_emp: emp.aname_emp,
      alast_name: emp.alast_name,
      aID_tran: emp.aID_tran,
      arol: emp.arol,
      adate_atten:emp.adate_atten,
      atime_atten: emp.atime_atten,
      alaboral_day: emp.alaboral_day,
      adata_origin: emp.adata_origin,
      aname_device: emp.aname_device,
      aserie_device: emp.aserie_device,
      aperforation: emp.aperforation,
      aubication: emp.aubication,
      aobservations: emp.aobservations
    }));
    
       res.json({
        message: 'attendance',
        data: attendance 
      });

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

const getGradeOfStudy = async (req, res) => {
  try {
    const result = await pool.query(
      'SELECT * FROM degreeofstudy',
    );

    const study = result.rows.map(emp => ({
      id_study: emp.id_study,
      name_study: emp.name_study
    }));
    
       res.json({
        message: 'grados de estudio',
        data: study 
      });

     } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Error al obtener los grados de estudio' });
  }
};
const getRelationshipEmployee = async (req, res) => {
  try {
    const result = await pool.query(
      'SELECT * FROM relationship_employee',
    );

    const relationship = result.rows.map(emp => ({
      id_relationship: emp.id_relationship,
      name_relationship: emp.name_relationship
    }));
    
       res.json({
        message: 'Parentesco',
        data: relationship 
      });

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

module.exports = 
{ getEmployees,
  getTotalActiveEmployees,
  getEmployee,
  newEmployee,
  updateEmployee,
  getattendance,
  getGradeOfStudy,
  getRelationshipEmployee
};