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

const getproductsdisplay = async (req, res) => {
    try{
        const result = await pool.query(
       'SELECT * FROM getproductsdisplay()'
    );
    const productsDisplay = result.rows.map(pro => ({
      id_product:pro.id_product,
      image_product: pro.image_product,
      name_product: pro.name_product,
      price_product: pro.price_product,
      units: pro.units
    }));



    res.json({
        data:productsDisplay
    });

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

};

const getproduct = async (req, res) => {
    const { id } = req.params;
    try{
    const result = await pool.query('SELECT * FROM getoneproduct($1)',[parseInt(id)]);
    const product = result.rows.map(pro => ({
      id_product: pro.id_product,
      image_product: pro.image_product,
      name_product: pro.name_product,
      sku_product: pro.sku_product,
      supplier_product: pro.supplier_product,
      price_product: pro.price_unit,
      id_tax: pro.tax_product,
      id_category_pro: pro.category_product,
      product_type: pro.product_type,
      stock: pro.stock,
      id_curreny: pro.currency,
      id_unit: pro.unit
    }));

    res.json({
        data:product
    });

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

};

const getcategoryproducts = async (req, res) => {
    try{
        const result = await pool.query(
       'SELECT * FROM getcategoryproducts()'
    );
    const productCategory = result.rows.map(cat => ({
      id_prod_category: cat.id_prod_category,
      name_prod_category: cat.name_prod_category,
      spanish_name: cat.spanish_name
    }));



    res.json({
        data:productCategory
    });

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

};

const gettypeproduct = async (req, res) => {
    try{
        const result = await pool.query(
       'SELECT * FROM gettypeproduct()'
    );
    const productType = result.rows.map(type => ({
      id_product_type: type.id_product_type,
      name_product_type: type.name_product_type,
      spanish_name: type.spanish_name
    }));



    res.json({
        data:productType
    });

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

};
const getsuppliers = async (req, res) => {
    try{
        const result = await pool.query(
       'SELECT * FROM getsuppliers()'
    );
    const suppliers = result.rows.map(supp => ({
      name_suppliers: supp.name_suppliers,
      rfc_suppliers: supp.rfc_suppliers,
    }));



    res.json({
        data:suppliers
    });

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

};
const newsupplier = async (req, res) => {
    try{
        const {new_name_supp,
            new_rfc_supp,
            new_mail_supp,
            new_phone_supp} = req.body
          const result = await pool.query('SELECT newsupplier($1,$2,$3,$4) AS status', 
            [new_name_supp,new_rfc_supp, new_mail_supp, new_phone_supp]);
      const newsupplier = result.rows[0].status; 
      res.json({
              message: "Proveedor agregado correctamente",
              new_supplier: newsupplier
            });

    }
    catch(error)
    {
    console.error(error);
    res.status(500).json({ message: 'Error al ingresar un nuevo proveedor' });
    }
};

const updateSupplier = async (req, res) => {
    try{
        const {id} = req.params;
        const {
	    name_supp,
	    rfc_supp,
	    mail_supp ,
	    phone_supp} = req.body
          const result = await pool.query('SELECT updateSupplier($1,$2,$3,$4) AS status', 
            [parseInt(id),name_supp,rfc_supp, mail_supp, phone_supp]);
      const updatesupplier = result.rows[0].status; 
      res.json({
              message: "Proveedor actualizado",
              new_supplier: updatesupplier
            });

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

const disabledSupplier = async (req, res) => {
    try{
        const {supplier_id} = req.body
          const result = await pool.query('SELECT disableSuppliers($1) AS status', [supplier_id]);
      const disabled = result.rows[0].status; 
      res.json({
              message: "Proveedor deshabilitado",
              new_supplier: disabled
            });

    }
    catch(error)
    {
    console.error(error);
    res.status(500).json({ message: 'Error al deshabilitar' });
    }
};
const newproduct = async (req, res) => {
    try{
        const {new_name_product,
            new_sku_product,
            product_type,
            new_category,
            suppliers_id,
            unit,
            new_stock,
            newprice_product,
            new_tax,
            currency,
            image_product} = req.body
          const result = await pool.query('SELECT newproduct($1,$2,$3::jsonb,$4,$5,$6,$7,$8,$9,$10,$11) AS status', 
            [new_name_product,new_sku_product,JSON.stringify(product_type),new_category,suppliers_id,unit,new_stock,
            newprice_product,new_tax,currency,image_product]);
      const newproduct = result.rows[0].status; 
      res.json({
              message: "Producto agregado correctamente",
              new_product: newproduct
            });

    }
    catch(error)
    {
    console.error(error);
    res.status(500).json({ message: 'Error al ingresar un nuevo proveedor' });
    }
};
const updateproduct = async (req, res) => {
    try{
    const { id } = req.params;
    const { 
            product_type,
            up_name_product,
            up_sku_product,
            suppliers_id,
            up_price_product,
            up_id_tax,
            id_category,
            new_stock,
            img_product,
            currency,
            unit
        } = req.body

            const result = await pool.query('SELECT updateproduct($1,$2::jsonb,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12) AS status', 
            [parseInt(id),JSON.stringify(product_type),up_name_product,up_sku_product,suppliers_id,
            up_price_product,parseInt(up_id_tax),parseInt(id_category),parseInt(new_stock),img_product,currency,unit]);

             const updateProduct = result.rows[0].status; 
              res.json({
              message: "Se actualizo el producto correctamente",
              new_product: updateProduct
                 });

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


};

const discardProduct = async (req, res) => {
    try{
    const { id } = req.params;
    const { quantity,
            reasons} = req.body

            const result = await pool.query('SELECT discardproductsstock($1,$2,$3) AS status', 
            [parseInt(id),quantity,reasons]);

             const discardProduct = result.rows[0].status; 
              res.json({
              message: "Producto descartado correctamente",
              discard_product: discardProduct
                 });

    }
    catch(error)
    {
    console.error(error);
    res.status(500).json({ message: 'No se pudo hacer el descarte del producto'});
    }


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

            const discartProducts = result.rows.map(dp => ({
            id_discard: dp.id_discard,
            product: dp.product,
            original: dp.original,
            quantity: dp.quantity,
            reasons: dp.reasons,
            date_discard : dp.date_dis,
            total: dp.total
         })); 
              res.json({
              message: "Se obtuvieron los productos descartados",
              product: discartProducts
                 });

    }
    catch(error)
    {
    console.error(error);
    res.status(500).json({ message: 'No se pudo hacer el descarte del producto'});
    }


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

        const reportInventory = result.rows.map(ri => ({
            date_movement: ri.date_movement,
            id_product: ri.id_product,
            name_product: ri.name_product,
            category_en: ri.category_en,
            category_esp:ri.category_esp,
            movement: ri.movement,
            comments_discard: ri.comments_discard,
            housekeeper_name: ri.housekepper_name,
            quantity: ri.quantity,
            average_cost: ri.average_cost,
            before_stock: ri.before_stock,
            stock : ri.stock,
         })); 
              res.json({
              message: "Se obtuvo el reporte de inventario",
              new_product: reportInventory
                 });

    }
        catch(error)
    {
    console.error(error);
    res.status(500).json({ message: 'No se pudo obtener el reporte'});
    }
};
const getstockadjusments = async (req, res) => {
    try{
        const result = await pool.query('SELECT * FROM getstockadjusments()');

        const productAdjusment = result.rows.map(ri => ({
            id_product: ri.id_product,
            name_product: ri.name_product,
            category_en: ri.category_en,
            category_esp: ri.category_esp,
            stock: ri.stock,
         })); 
              res.json({
              message: "Se obtuvo el reporte de inventario",
              productAdjusment: productAdjusment
                 });
    }
        catch(error)
    {
    console.error(error);
    res.status(500).json({ message: 'No se pudo obtener el reporte'});
    }
};

const setstockadjusments = async (req, res) => {
    try{
        const { stockproductadjusment} = req.body
        const result = await pool.query('SELECT * FROM setstockadjusmentsv2($1::jsonb) as stockadjus',[JSON.stringify(stockproductadjusment)]);

        const stockproduct = result.rows[0].stockadjus; 
        res.json({
        message: "Se hicieron los ajustes correspondientes",
        stockproduct: stockproduct});
    }
        catch(error)
    {
    console.error(error);
    res.status(500).json({ message: 'No se pudo realizar el ajuste'});
    }
}
const getHouseKeeper = async (req, res) => {
    try{
        const result = await pool.query('SELECT * FROM gethousekeeper()');
        const houseKeepers = result.rows.map(hk => ({
            rfc_employee: hk.rfc_employee,
            name_emp: hk.name_emp,
         })); 
              res.json({
              message: "Se obtuvieron los datos",
              houseKeeper: houseKeepers});
    }
        catch(error)
    {
    console.error(error);
    res.status(500).json({ message: 'No se pudo obtener los datos'});
    }
}
const newConsumptionStock = async (req, res) => {
    try{
        const {
            product_id,
            quantity_consumption,
            date_consumption,
            rfc_emp} = req.body
        const result = await pool.query('SELECT consumptionstock($1,$2,$3,$4) as STATUS',[product_id,quantity_consumption,date_consumption,rfc_emp]);
        const status = result.rows[0].status;
        if(status == 1)
         message = "El consumo del producto fue realizado con exito";
        else
          message = "No se pudo hacer el consumo"
            res.json({
              message,
              status: status
            });
    }
        catch(error){
    console.error(error);
    res.status(500).json({ message: 'No se pudo obtener los datos'});
    }
}
const getConsumptionStockReport = async (req, res) => {
    try{
        const result = await pool.query('SELECT * FROM getconsumptionreport()');
        const stockConsumptions = result.rows.map(sc => ({
            rfc_employee: sc.rfc_employee,
            name_emp: sc.name_emp,
            date_consumption:sc.date_consumption,
            product_id:sc.product_id,
            product_name:sc.product_name,
            quantity:sc.quantity,
            stocktotal:sc.stocktotal
         })); 
              res.json({
              message: "Se obtuvieron los datos",
              stockConsumption: stockConsumptions});
    }
        catch(error)
    {
    console.error(error);
    res.status(500).json({ message: 'No se pudo obtener los datos'});
    }
};
const getproducts = async (req, res) => {
    try{
        const page = parseInt(req.query.page) || 1;   // Página actual
        const limit = parseInt(req.query.limit) || 10; // Cantidad por página
        const offset = (page - 1) * limit;           // Desde dónde empezar
        const result = await pool.query('SELECT * FROM getproducts() LIMIT $1 OFFSET $2',[limit, offset]);

        const totalResult = await pool.query('SELECT COUNT(*) FROM products');
        const total = parseInt(totalResult.rows[0].count);
        const totalPages = Math.ceil(total / limit);

        const products = result.rows.map(pro => ({
            id_product: pro.id_product,
            name_product:pro.name_product,
            sku_product:pro.sku_product,
            price_product:pro.price_product,
            id_tax:pro.id_tax,
            percentage: pro.percentage,
            id_prod_category: pro.id_prod_category,
            name_prod_category: pro.name_prod_category,
            id_unit: pro.id_unit,
            name_unit: pro.name_unit,
            id_currency: pro.id_currency,
            name_currency: pro.name_currency,
            image_product: pro.image_product,
            id_suppliers: pro.id_suppliers,
            name_suppliers: pro.name_suppliers
         })); 
              res.json({
                page,
                limit,
                 total,
                totalPages,
                 message: "Se obtuvieron los datos",
                 product: products});
    }
        catch(error)
    {
    console.error(error);
    res.status(500).json({ message: 'No se pudo obtener los datos'});
    }
};

module.exports =
{
    getproductsdisplay,
    getproducts,
    getcategoryproducts,
    gettypeproduct,
    getsuppliers,
    getproduct,
    newsupplier,
    newproduct,
    updateproduct,
    discardProduct,
    getdiscardproduct,
    reportInventory,
    getstockadjusments,
    setstockadjusments,
    getHouseKeeper,
    newConsumptionStock,
    getConsumptionStockReport,
    updateSupplier,
    disabledSupplier
}