<?php



class PosProductoRepository extends EntityRepository
{



    private $table = 'pos_productos';

    private $images = null;

    private $options_image = array(

        'allowedExtensions' => array('jpg', 'jpeg', 'png'),

        'maxFileSizeAllowed' => 1000000,

        'pathToSave' => PATH_IMG_PRODUCTS

    );



    public $flashmessenger = null;





    public function __construct()
    {

        if (!$this->flashmessenger instanceof FlashMessenger) {

            $this->flashmessenger = new FlashMessenger();
        }
    }



    public function _getTranslation($text)
    {

        return $this->flashmessenger->_getTranslation($text);
    }

    public function setImage($file)
    {

        $this->images['main'] = $file;
    }



    public function saveImage($idProduct)
    {

        $file = new UploadFile();

        $file->setAllowedExtensions($this->options_image['allowedExtensions']);

        $file->setMaxFileSizeAllowed($this->options_image['maxFileSizeAllowed']);

        $file->setTempFolder($this->options_image['pathToSave']);



        $rsUpload = $file->uploadFile($this->images['main'], null, 'main_' . $idProduct);

        if (!$rsUpload) {

            $this->flashmessenger->addMessage(array('info' => $file->getMessageError()));
        }
    }



    public function save(array $data, $table = null)
    {

        $login = new Login();

        $data['creado_por'] = $login->getId();

        $data['creado_fecha'] = date('Y-m-d H:i:s');

        unset($data['modificaciones']);



        if (trim($data['descuento']) == '') {
            $data['descuento'] = 0;
        }

        if (trim($data['punitarioventa']) == '') {
            $data['punitarioventa'] = 0;
        }



        if (is_array($data['proveedores']) && count($data['proveedores']) > 0) {

            $sucursal = implode(',', $data['proveedores']);

            $data['proveedores'] = trim($sucursal, ',');
        }

        if ($this->images !== null) {

            $data['con_imagen'] = 1; //UG La imagen del producto fue agregada

        }

        foreach ($data as $key => $value) {

            if (trim($value) == '' || trim($value) === null) {

                unset($data[$key]);
            }
        }



        $this->startTransaction();

        $result =  parent::save($data, $this->table);



        if ($result) {

            $idProduct = $this->getInsertId();

            $this->setLastInsertId($idProduct); //Para utilizarlo en el Controller action insert  

            $this->commit();

            if ($this->images !== null) {

                $this->saveImage($this->getInsertId());
            }

            return true;
        }
    }



    public function update($id, $data, $table = null)
    {

        unset($data['creado_fecha'], $data['creado_por'], $data['modificaciones']);

        if(isset($data['admin_product_id'])){
            unset($data['admin_product_id']);
        }


        if (trim($data['descuento']) == '') {
            $data['descuento'] = 0;
        }

        if (trim($data['punitarioventa']) == '') {
            $data['punitarioventa'] = 0;
        }



        if (is_array($data['proveedores']) && count($data['proveedores']) > 0) {

            $sucursal = implode(',', $data['proveedores']);

            $data['proveedores'] = trim($sucursal, ',');
        }

        if ($this->images !== null) {

            $data['con_imagen'] = 1; //UG La imagen del producto fue agregada

        }



        foreach ($data as $key => $value) {

            if ($value == '' || $value === null) {

                $data[$key] = array('key' => $key, 'value' => '_NULL');
            }
        }

        if ($this->images !== null) {

            $this->saveImage($id);
        }



        return parent::pos_update($id, $data, $this->table);
    }



    public function getById($id, $table = null, $selectAux = null)
    {

        $selectAux = " IFNULL(costo,0)as costo,"

            . "IFNULL(punitarioventa,0)as punitarioventa,"

            . "fxGetImpuestosTasa(impuestos)as impuestosTasa,"

            . "fxGetUnidadMedidaDescripcion(unidad_de_medida) as umName,"

            . " fxGetCategoriaDescripcion(categoria)as categoriaName ";

        return parent::getById($id, $this->table, $selectAux);
    }



    public function getByCode($code)
    {

        $query = "SELECT * FROM $this->table WHERE codigo = '$code' LIMIT 1";

        $result = $this->query($query);



        if ($result->num_rows > 0) {

            $result = $this->resultToArray($result);

            return $result[0];
        }

        return null;
    }



    public function getRealInfoById($id)
    {

        $query = "SELECT id,descripcion,

                            fxGetCategoriaDescripcion(categoria)as categoria,

                            fxGetMarcaDescripcion(marca)as marca,

                            fxGetPresentacionDescripcion(presentacion)as presentacion,

                            punitariocompra,punitarioventa

                   FROM $this->table

                   WHERE id = '$id'";



        $result = $this->query($query);



        if ($result->num_rows > 0) {

            $result = $this->resultToArray($result);

            return $result[0];
        }



        return null;
    }



    public function delete($id, $table = null)
    {

        return parent::delete($id, $this->table);
    }



    public function exist($idProducto)
    {

        $query = "SELECT descripcion

                    FROM $this->table 

                    WHERE id = '$idProducto'

                    LIMIT 1 ";

        $result = $this->query($query);



        if ($result->num_rows > 0) {

            $result =  $this->resultToArray($result);

            return $result[0];
        }

        return null;
    }



    public function existeCodigo($codigo, $idProducto = null)
    {

        $codigo = strtolower(trim($codigo));

        if ($codigo == '') {
            return null;
        } else {
            $codigo = " codigo = '$codigo' ";
        }

        if ($idProducto != null && trim($idProducto) != '') {
            $idProducto = " AND id != '$idProducto' ";
        }



        $query = "SELECT codigo,

                         descripcion,

                         fxGetCategoriaDescripcion(categoria) as categoria,

                         fxGetMarcaDescripcion(marca) as marca

                    FROM $this->table 

                    WHERE $codigo $idProducto

                    LIMIT 1 ";

        $result = $this->query($query);



        if ($result->num_rows > 0) {

            $result =  $this->resultToArray($result);

            return $result[0];
        }

        return null;
    }



    public function isUsedInRecord($id, array $buscarEn = null, $andWhere = null)
    {

        return parent::isUsedInRecord($id, array('ventasdetalles' => 'idProducto'));
    }



    public function getPreciosVentaById($id)
    {

        $query = "SELECT punitarioventa as `precio_menudeo` FROM productos WHERE id = '$id' LIMIT 1";

        $result = $this->query($query);



        if ($result) {

            $result = $result->fetch_object();

            $array[$result->precio_menudeo] = "Precio menudeo - $" . $result->precio_menudeo;

            $array[$result->precio_mayoreo] = "Precio mayoreo - $" . $result->precio_mayoreo;



            return $array;
        }



        return null;
    }



    public function getListaProductos($tipo = null, $status = 1)
    {

        if ($tipo != null) {

            $tipo = " AND p.type = '$tipo'";
        }



        $status = " AND p.status = '$status' ";

        // fxGetStatusName(p.status,'status','Product') as statusName,        

        $query = "SELECT p.*,

                    c.descripcion as categoria,

                    m.descripcion as marca,

                    um.descripcion as unidad_de_medida,
                    i.impuesto as impuesto_name,



                    fxGetStatusName(p.status,'Product') as statusName, 

                    co.hex_color as color

                    FROM $this->table p 

                    LEFT JOIN  pos_categorias c ON p.categoria = c.id 

                    LEFT JOIN  pos_marcas m ON p.marca = m.id

                    LEFT JOIN  pos_unidades_de_medida um ON p.unidad_de_medida = um.id

                    LEFT JOIN  pos_impuestos i ON p.impuestos = i.id

                    LEFT JOIN  pos_productos_colors co ON p.color = co.id

                    WHERE 1=1

                    $status

                    $tipo   ORDER BY p.descripcion ";



        //var_dump($query);exit;

        $result = $this->query($query);



        if ($result) {

            return $this->resultToArray($result);
        }

        return null;
    }



    public function getListSelectProductos()
    {

        $query = "SELECT *,TRIM(descripcion)as descripcion

                    FROM $this->table 

                    WHERE 1=1 

                    AND status = '1' 

                    ORDER BY descripcion";

        $result = $this->query($query);



        if ($result) {

            $array = array();

            while ($row = $result->fetch_object()) {

                $array[$row->id] = $row->descripcion;
            }



            return $array;
        }



        return null;
    }

    public function getListSelectProductosAndPrice()
    {

        $query = "SELECT *,TRIM(descripcion)as descripcion

                    FROM $this->table 

                    WHERE 1=1 

                    AND status = '1' 

                    ORDER BY descripcion";

        $result = $this->query($query);



        if ($result) {

            $array = array();

            while ($row = $result->fetch_object()) {

                $array[$row->id] = $row->descripcion .'- $'. $row->punitarioventa;
            }



            return $array;
        }



        return null;
    }


    public function getProductosLike($item)
    {

        $query = "SELECT *,

                    fxGetCategoriaDescripcion(categoria)as categoria,

                    fxGetMarcaDescripcion(marca)as marca

                    FROM $this->table WHERE codigo like '%$item%' OR descripcion like '%$item%' AND status = 1 ORDER BY descripcion";

        $result = $this->query($query);



        if ($result) {

            return $this->resultToArray($result);
        }



        return null;
    }

    public function getListVentaProductos($tipo = null)
    {

        $query = "SELECT p.*,

                    c.descripcion as categoria,

                    m.descripcion as marca 

                    FROM $this->table p "

            . "WHERE 1=1 "

            . " LEFT JOIN  pos_categorias c ON p.categoria = c.id 

                    LEFT JOIN  pos_marcas m ON p.marca = m.id"

            . "AND(type = '1' OR type = '2') "

            . "ORDER BY descripcion";

        $result = $this->query($query);



        if ($result) {

            return $this->resultToArray($result);
        }
    }



    public function updatePrecios($data)
    {

        unset($data['enviar']);

        unset($data['id']);

        unset($data['action']);

        foreach ($data as $key => $value) {

            foreach ($value as $id => $campos) {

                $query = "UPDATE productos SET ";

                foreach ($campos as $key => $valor) {

                    $query .= $key . " = '$valor',";
                }

                $query = trim($query, ",");

                $query .= " WHERE id = $id";

                $this->query($query);
            }
        }
    }



    public function getLastIdProduct()
    {

        $query = "SELECT id FROM $this->table ORDER BY id DESC LIMIT 1";



        $result = $this->query($query);



        if ($result->num_rows > 0) {

            $result = $result->fetch_object();

            return $result->id;
        } else {

            return 0;
        }
    }



    public function getListSelectColors()
    {

        $select = "SELECT * FROM  pos_productos_colors ";

        $result = $this->query($select);



        if ($result) {

            $array = array();

            while ($row = $result->fetch_assoc()) {

                $array[$row['id']] = $row['hex_color'];
            }



            return $array;
        }

        return null;
    }

    public function crearTablaDetallesForUser()
    {

        $login = new Login();

        $query = "DROP TABLE IF EXISTS products_details_" . $login->getId();

        $this->query($query);



        $query = "CREATE TABLE IF NOT EXISTS products_details_" . $login->getId() . " 

                 (  `id` int(11) NOT NULL AUTO_INCREMENT,

                    `id_detail` int(11) NULL,

                    `id_product` int(11) NULL,

                    `id_slice` int(11) NOT NULL,

                    `quantity` double NOT NULL,                   

                    PRIMARY KEY (`id`)

                 )ENGINE=InnoDB DEFAULT CHARSET=utf8;";



        $result = $this->query($query);
    }



    public function insertDetalle($data)
    {

        $storeInDetailsTemp = new ProductDetailsTempRepository();



        return $storeInDetailsTemp->save($data);
    }



    public function getProductDetails()
    {

        $login = new Login();

        $query = "SELECT v.*,

                    v.id as idDetailTemp,

                    p.flavor,

                    p.category,

                    p.size,

                    fxGetCategoriaDescripcion(p.category)as categoryName

                  FROM products_details_" . $login->getId() . " v LEFT JOIN slices p

                  ON v.id_slice = p.id

                  ORDER BY v.id";

        $result = $this->query($query);



        if ($result) {

            $result = $this->resultToArray($result);

            return $result;
        }



        return null;
    }

    public function getProductDetailsSaved($id)
    {

        $query = "SELECT c.*,

                    p.code as code

                    FROM product_details c LEFT JOIN slices p ON c.id_slice = p.id

                    WHERE c.id_product = '$id'";

        $result = $this->query($query);



        if ($result) {

            $result = $this->resultToArray($result);

            return $result;
        }



        return null;
    }

    public function getListaSelectImpuestos()
    {

        $select = "SELECT * FROM taxes ";

        $result = $this->query($select);



        if ($result) {

            $array = array();

            while ($row = $result->fetch_assoc()) {

                $array[$row['id']] = $row['description'] . " - " . $row['rate'] . " %";
            }

            return $array;
        }

        return null;
    }

    public function getSliceById($id)
    {

        $repoSlice = new SliceRepository();

        return $data = $repoSlice->getById($id);
    }

    public function getProductForMenu()
    {

        $query = "SELECT p.* "

            . "FROM productos p "

            . "WHERE mostrar_en_menu = '1' "

            . "ORDER BY p.nombre_para_menu ASC";



        $result = $this->query($query);



        if ($result->num_rows > 0) {

            return $this->resultToArray($result);
        }
    }

    public function truncateIfIsEditInfo()
    {

        $repository = new ProductDetailsTempRepository();

        $repository->truncateIfIsEditInfo();
    }



    public function getListStatus()
    {

        $query = "SELECT * FROM pos_codigo_status WHERE tipo = 'Product'";

        $result = $this->query($query);



        if ($result->num_rows > 0) {

            $array = array();

            foreach ($result as $status) {

                $array[$status['codigo']] = $status['descripcion'];
            }

            return $array;
        }

        return null;
    }



    public function proveedoresStringToArray($sucursales)
    {

        $arraySucursales = array();

        $sucursales = explode(',', $sucursales);

        foreach ($sucursales as $key => $sucursal) {

            $arraySucursales[$sucursal] = $sucursal;
        }

        return $arraySucursales;
    }



    public function getDataTaxesById($id)
    {

        $query = "SELECT * FROM pos_impuestos WHERE id = '$id'";

        $result = $this->query($query);



        if ($result->num_rows > 0) {

            return $this->resultToArray($result)[0];
        }



        return null;
    }

    public function getUUID()
    {

        $query = 'SELECT SUBSTRING(UUID(), 1, 10) as uuid ';
        $result = $this->query($query);

        if ($result->num_rows > 0) {

            return $this->resultToArray($result);
        }
        return null;
    }
    public function saveChangeProduct($dataProduct, $dataStore)
    {
        // echo "<pre>  ";
        // var_dump($dataProduct);
        // echo "</pre>";
        // echo "<pre>  ";
        // var_dump($dataStore);
        // echo "</pre>"; exit;

        $_login = new Login();
        $user_id = $_login->getRole();

        // Convertir las tiendas a una cadena delimitada por comas
        $storeIds = array_column($dataStore, 'value');
        $storeIdsString = implode(',', $storeIds);

        // Crear el UUID para este conjunto de cambios
        $cp_uuid = implode($this->getUUID()[0]);

        // Preparar las consultas de inserción
        $query = "INSERT INTO pos_cambios_productos (cp_uuid, p_uuid, p_categoria, p_codigo, p_preview, p_new, cp_store,creado_por,creado_fecha, cp_status,cp_categoria) VALUES ";
        $values = [];

        foreach ($dataProduct as $productId => $changes) {
            foreach ($changes as $field => $changeDetails) {
                $p_uuid = $changeDetails[$field]['p_uuid'];
                $codigo = $changeDetails[$field]['Codigo'];
                $original = $changeDetails[$field]['Original'];
                $new = $changeDetails[$field]['New'];
                $categoria = $changeDetails[$field]['Descripcion']; // Puedes ajustar esto si la descripción no es la categoría

                $values[] = "('$cp_uuid', '$p_uuid', '$categoria', '$codigo', '$original', '$new', '$storeIdsString',$user_id,NOW(), '1','$field')";
            }
        }

        // Unir todos los valores de las consultas
        $query .= implode(", ", $values);
        //var_dump($query);exit;
        // Ejecutar la consulta
        $result = $this->query($query);

        if ($result) {
            return true;
        }

        return null;
    }


    public function getListaProductosCambios($tipo = null, $status = 1)
    {

        $filter = "";
        //                    fxGetStatusName(p.status,'status','Product') as statusName,        
        if ($tipo != null) {
            $filter = " AND cp.cp_uuid = '$tipo'";
        }





        $status = " AND p.status = '$status' ";

        //                    fxGetStatusName(p.status,'status','Product') as statusName,        

        $query = "SELECT cp.*, p.*,

                    c.descripcion as categoria,

                    m.descripcion as marca,

                    um.descripcion as unidad_de_medida,



                    fxGetStatusName(p.status,'Product') as statusName, 

                    co.hex_color as color

                    FROM pos_cambios_productos cp 
                    
                    JOIN $this->table p on cp.p_uuid = p.p_uuid

                    LEFT JOIN  pos_categorias c ON p.categoria = c.id 

                    LEFT JOIN  pos_marcas m ON p.marca = m.id

                    LEFT JOIN  pos_unidades_de_medida um ON p.unidad_de_medida = um.id

                    LEFT JOIN  pos_impuestos i ON p.impuestos = i.id

                    LEFT JOIN  pos_productos_colors co ON p.color = co.id

                    WHERE 1=1

                    $status

                    $filter   ORDER BY p.descripcion ";



        //var_dump($query);exit;

        $result = $this->query($query);



        if ($result) {

            return $this->resultToArray($result);
        }

        return null;
    }
    public function getListaCambiosGenerados($cp_uuid = null, $status = 1)
    {

        $filter = "";
        //                    fxGetStatusName(p.status,'status','Product') as statusName,        
        if ($cp_uuid != null) {
            $filter = " AND cp.cp_uuid = '$cp_uuid'";
        }

        $query = "SELECT DISTINCT cp.cp_uuid, cp.cp_store,cp.cp_status,                    
                    fxGetUserName(cp.creado_por)as userName,
                    DATE_FORMAT(cp.creado_fecha,'%m/%d/%Y')as formated_date
                    FROM pos_cambios_productos cp                                 
                    WHERE 1 = 1 $filter
                   ORDER BY cp.creado_fecha desc ";

        //var_dump($query);exit;

        $result = $this->query($query);



        if ($result) {

            return $this->resultToArray($result);
        }

        return null;
    }
    public function getCambiosProductosById($cp_uuid)
    {
        $filter = "";
        if ($cp_uuid != null) {
            $filter = " AND cp.cp_uuid = '$cp_uuid'";
        }

        $query = "SELECT *
                    FROM pos_cambios_productos cp                                 
                    WHERE 1 = 1 $filter
                   ORDER BY cp.creado_fecha desc ";

        $result = $this->query($query);

        if ($result) {

            return $this->resultToArray($result);
        }

        return null;
    }
    //UG funcion para enviar el update del producto a la sucursal que le corresponde

    public function saveTransactionProduct($data)
    {
        $query = "";
        $results = array();

        try {
            foreach ($data as $productId => $changes) {
                $storeRepository = new StoreRepository();
                $dataStore = $storeRepository->getListAllStores($changes['cp_store']); //UG Aqui obtenemos toda la informacion de las sucursales de la transaccion

                foreach ($dataStore as $store) {
                    $query = "UPDATE " . $store . ".productos SET " . $changes['cp_categoria'] . " = '" . $changes['p_new'] . "' WHERE p_uuid = '" . $changes['p_uuid'] . "'";
                    #var_dump($query);exit;
                    $result = $this->query($query);

                    if ($result === false) {
                        throw new Exception("Failed to update product in store: " . $store);
                    }
                    $query = "";
                    $results[] = $result;
                }
            }
            //var_dump($result);exit;
            return ['success' => true, 'results' => $results];
        } catch (Exception $e) {
            return ['success' => false, 'error' => $e->getMessage()];
        }
    }


    // public function saveTransactionProduct($data)
    // {

    //     $query = "";
    //     $result = array();
    //     try {

    //         foreach ($data as $productId => $changes) {
    //             $storeRepository = new StoreRepository();

    //             $dataStore = $storeRepository->getListAllStores($changes['cp_store']); //UG Aqui obtenemos toda la informacion de las sucursales de la transaccion

    //             foreach ($dataStore as $store) {

    //                 $query .= "UPDATE " . $store . ".productos SET " . $changes['cp_categoria'] . " = '" . $changes['p_new'] . "' WHERE p_uuid = '" . $changes['p_uuid'] . "'";
    //                 $result = $this->query($query);
    //             }
    //             //var_dump($query);
    //             $query = "";
    //         }
    //         return $result;
    //     } catch (Exception $e) {
    //         $result = 'Caught exception: '.  $e->getMessage(). "\n";
    //         return $result;
    //     }
    // }



    public function updateTransaction($cp_uuid, $status)
    {
        $query = "UPDATE pos_cambios_productos SET cp_status = '$status' WHERE cp_uuid = '$cp_uuid' ";
        $result = $this->query($query);
        return $result;
    }

    public function uploadTransactions($data)
    {
        $query = "";
        $result = array();
        foreach ($data as $productId => $changes) {

            $query .= "UPDATE pos_productos SET " . $changes['cp_categoria'] . " = '" . $changes['p_new'] . "' WHERE p_uuid = '" . $changes['p_uuid'] . "'";

            $result = $this->query($query);
            $query = "";
        }
        return $result;
    }

    public function saveProductTransaction1($p_uuidProduct, $dataStore)
    {

        $_login = new Login();
        $user_id = $_login->getRole();
        $queryMode = "";
        $QueryString = "";
        try {
            foreach ($dataStore as $id_store) {
                $log_uuid = implode($this->getUUID()[0]);
               
                $storeRepository = new StoreRepository();
                $dataStore = $storeRepository->getListAllStores($id_store['value']); //UG Aqui obtenemos toda la informacion de las sucursales de la transaccion

                foreach ($dataStore as $store) {

                    $query_product = "SELECT * FROM " . $store . ".productos  WHERE p_uuid = '$p_uuidProduct' ";

                    $result_product = $this->query($query_product);

                    if ($result_product) {
                        $queryMode = "UPD";
                    } else $queryMode = "INS";
                }
                $query = "SELECT * FROM $this->table WHERE p_uuid = '$p_uuidProduct' ";

                $result = $this->query($query);
                $arrayActiveProduct = array();
                if ($result->num_rows > 0) {


                    while ($row = $result->fetch_assoc()) {
                        $arrayActiveProduct[] = $row;
                    }
                }

                //  $arrayActiveProduct[0] contiene los datos del producto
                $productData = $arrayActiveProduct[0];

                if ($queryMode == "INS") {
                    // Construcción de la consulta INSERT
                    $columns = array();
                    $values = array();
                    foreach ($productData as $key => $value) {
                       
                        if ($key !== 'modificaciones') {
                            $columns[] = $key;
                            $values[] = is_null($value) ? 'NULL' : "'$value'";
                        }                        
                    }
                    $columns = implode(", ", $columns);
                    $values = implode(", ", $values);

                    $QueryString = "INSERT INTO pbakeryadmin_pos_wisconsin.productos ($columns) VALUES ($values)";
                   
                    // // Ejecutar la consulta INSERT
                    // if ($this->query($insertQuery)) {
                    //     echo "Insert successful";
                    // } else {
                    //     echo "Error: " . $this->error;
                    // }
                } else if ($c == "UPD") {
                    // Construcción de la consulta UPDATE
                    $updateParts = array();
                    foreach ($productData as $key => $value) {
                        if ($key !== 'modificaciones') {
                            $updateParts[] = "$key = " . (is_null($value) ? 'NULL' : "'$value'");
                        }
                    }
                    $updateParts = implode(", ", $updateParts);
                    $QueryString = "UPDATE pbakeryadmin_pos_wisconsin.productos SET $updateParts WHERE p_uuid = '$p_uuidProduct'";
                   
                    // // Ejecutar la consulta UPDATE
                    // if ($this->query($updateQuery)) {
                    //     echo "Update successful";
                    // } else {
                    //     echo "Error: " . $this->error;
                    // }
                }     
                
                $queryUpd = "INSERT INTO pos_productos_logs (log_uuid, p_uuid,id_sucursal,type_log,query_log,creado_por,creado_fecha,log_status) VALUES "
                . " '$p_uuidProduct', '$log_uuid', '{$id_store['value']}', '$queryMode', '$QueryString' ,$user_id,NOW(),'1' ";
                $result = $this->query($queryUpd);

                if ($result) {
                    return true;
                }

            }
        } catch (Exception $e) {
            $result = 'Caught exception: ' .  $e->getMessage() . "\n";
           
            return $result;
        }


    }
    public function saveProductTransaction($p_uuidProduct, $dataStore)
    {
        $_login = new Login();
        $user_id = $_login->getRole();
        $queryMode = "";
        $QueryString = "";

        try {
            foreach ($dataStore as $id_store) {
                $log_uuid = implode($this->getUUID()[0]);

                $storeRepository = new StoreRepository();
                $dataStoreDetails = $storeRepository->getListAllStores($id_store['value']);
                $tabla_name = "";
                foreach ($dataStoreDetails as $store) {
                    $query_product = "SELECT * FROM " . $store . ".productos  WHERE p_uuid = '$p_uuidProduct' ";
                    $result_product = $this->query($query_product);

                    if ($result_product && $result_product->num_rows > 0) {
                        $queryMode = "UPD";
                    } else {
                        $queryMode = "INS";
                    }
                    $tabla_name = $store . ".productos ";
                }

                $query = "SELECT * FROM $this->table WHERE p_uuid = '$p_uuidProduct' ";
                $result = $this->query($query);
                $arrayActiveProduct = [];

                if ($result->num_rows > 0) {
                    while ($row = $result->fetch_assoc()) {
                        $arrayActiveProduct[] = $row;
                    }
                }

                $productData = $arrayActiveProduct[0];

                if ($queryMode == "INS") {
                    $columns = [];
                    $values = [];
                    foreach ($productData as $key => $value) {
                        if ($key !== 'modificaciones' && $key !== 'id') {
                            $columns[] = $key;
                          //  $values[] = is_null($value) ? 'NULL' : "`$value`";
                          $values[] = is_null($value) ? 'NULL' : "'" . addslashes($value) . "'";
                        }
                    }
                    $columnsString = implode(", ", $columns);
                    $valuesString = implode(", ", $values);
                    $QueryString = "INSERT INTO $tabla_name ($columnsString) VALUES ($valuesString)";
                } else if ($queryMode == "UPD") {
                    $updateParts = [];
                    foreach ($productData as $key => $value) {
                        if ($key !== 'modificaciones' && $key !== 'id') {
                            //$select .= "`$key` = '$value',";
                            //$updateParts[] = "$key = " . (is_null($value) ? 'NULL' : "`$value`");
                            $updateParts[] = "`$key` = " . (is_null($value) ? 'NULL' : "'" . addslashes($value) . "'");
                        }
                    }
                    $updateString = implode(", ", $updateParts);
                    $QueryString = "UPDATE $tabla_name SET $updateString WHERE `p_uuid` = '$p_uuidProduct' "  ;// p_uuid = " . '"' .$p_uuidProduct . '"' ;
                }
               // Escapar adecuadamente el QueryString para evitar errores de comillas
                $escapedQueryString = addslashes($QueryString);
                // Inserta en pos_productos_logs
                // $queryLog = "INSERT INTO pos_productos_logs (log_uuid, p_uuid, id_sucursal, type_log, query_log, creado_por, creado_fecha, log_status) VALUES "
                // . "('$log_uuid', '$p_uuidProduct', '{$id_store['value']}', '$queryMode', '{$QueryString}', '$user_id', NOW(), 1)";
                $queryLog = "INSERT INTO pos_productos_logs (log_uuid, p_uuid, id_sucursal, type_log, query_log, creado_por, creado_fecha, log_status) VALUES "
                . "('$log_uuid', '$p_uuidProduct', '{$id_store['value']}', '$queryMode', '$escapedQueryString', '$user_id', NOW(), 1)";

                //var_dump($queryLog);exit;
                $resultLog = $this->query($queryLog);     
                if($resultLog){
                    $query = "UPDATE  $this->table SET change_active = 1 WHERE  p_uuid = '$p_uuidProduct' ";
                    $result_Upd = $this->query($query);
                }          
                if (!$resultLog) {
                    throw new Exception("Error inserting log: ");
                }
            }

            return true;
        } catch (Exception $e) {
            return  'Caught exception: ' . $e->getMessage();
        }
    }
    public function getListaQueryProduct($cp_uuid = null, $status = 1)
    {

        $filter = "";
        //                    fxGetStatusName(p.status,'status','Product') as statusName,        
        if ($cp_uuid != null) {
            $filter = " AND cp.cp_uuid = '$cp_uuid'";
        }

        $query = "SELECT  logs.*,                    
                    fxGetUserName(logs.creado_por)as userName,
                    DATE_FORMAT(logs.creado_fecha,'%m/%d/%Y %h:%i %p')as formated_date,
                    (SELECT descripcion FROM  pos_productos p where p.p_uuid = logs.p_uuid) as producto_descrip
                    FROM pos_productos_logs logs                                 
                    WHERE 1 = 1 $filter
                   ORDER BY logs.log_status desc, logs.creado_fecha desc ";
        
//var_dump($query);exit;
        $result = $this->query($query);



        if ($result) {

            return $this->resultToArray($result);
        }

        return null;
    }
    public function get_DetailsQuery($log_uuid)
    {
        
        $query = "SELECT log.*

                    FROM pos_productos_logs log where log_uuid = '$log_uuid' ";

        $result = $this->query($query);

        if ($result) {

            return $this->resultToArray($result);
        }

        return null;
    }

    public function Exec_Query($log_uuid, $query)
    {
        
        try {

            $result = $this->query($query);
            if ($result === false) {
                throw new Exception("Failed to update product in store: " . $query);
            }          
           

            $QueryIDP = "SELECT * FROM pos_productos_logs WHERE log_uuid = '$log_uuid'";
            $obtenerIDP = $this->query($QueryIDP);
            $obtenerIDP = $this->resultToArray($obtenerIDP);

            $p_uuidV = $obtenerIDP[0]['p_uuid'];
        
            $query_upd_pos_product = "UPDATE pos_productos p SET change_active = NULL WHERE p_uuid = '$p_uuidV'";

            $result_upd_pos_product = $this->query($query_upd_pos_product);

            $query_upd = "UPDATE pos_productos_logs SET log_status = 0 WHERE  log_uuid = '$log_uuid' ";
            
            $result_Upd = $this->query($query_upd);

            return ['success' => true, 'results' => $result];
        } catch (Exception $e) {
            
            return ['success' => false, 'error' => $e->getMessage()];
        }
    }
    public function getListSelectProductosByCategory($category_id)
    {

        $query = "SELECT *,TRIM(descripcion)as descripcion

                    FROM $this->table 

                    WHERE 1=1 

                    AND status = '1' and categoria = '$category_id'

                    ORDER BY descripcion";

        $result = $this->query($query);



        if ($result) {

            $array = array();

            while ($row = $result->fetch_object()) {

                $array[$row->id] = $row->descripcion.'- $'. $row->punitarioventa;;
            }



            return $array;
        }



        return null;
    }
    
}
