<?php

/**

 * Description of Ajax

 *

 * @author carlos

 */

class ProductAjax extends ProductRepository
{



    public $flashmessenger = null;



    public function __construct()
    {

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

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



    public function getResponse($request, $options)
    {

        return $this->$request($options);
    }



    public function _getTranslation($text)
    {

        $translator = new Translator();

        return $translator->_getTranslation($text);
    }



    public function getTranslation($options)
    {

        $msj = $options['msj'];



        return array(

            'response' => true,

            'translation' => $this->_getTranslation($msj)

        );
    }



    public function getDataToEdit($options)
    {

        $supplieRepo = new ProductRepository();

        $data = $supplieRepo->getById($options['id']);

        $data['action'] = 'edit';



        return array(

            'response' => true,

            'productData' => $data

        );
    }



    public function deleteProduct($options)
    {

        $colegioRepo = new ProductRepository();



        if ($colegioRepo->delete($options['id'])) {

            $this->flashmessenger->addMessage(array('success' => 'Producto se elimino exitosamente.'));
        }



        return array(

            'response' => true

        );
    }



    public function getListaProducts($options)
    {

        $repository = new ProductRepository();

        $item = $options['item'];



        $items = $repository->getProductsLike($item);



        if ($items) {

            $array = array();

            foreach ($items as $item) {

                $array[] = array(

                    'value' => $item['id'],

                    'label' => $item['description'] . " (" . $item['code'] . ")"

                );
            }
        }

        return array(

            'response' => true,

            'productos' => $array

        );
    }



    //UG esta parte de codigo va a POS_PRODUCTO 20.05.24
    public function saveCambiosProductos($options)
    {

        if (!is_array($options) || empty($options)) {
            $this->flashmessenger->addMessage(array('danger' => 'No existen datos en el array.'));

            echo "<pre> Error: opciones no válidas. </pre>";
            return array(

                'response' => false,

                'msg' => $this->flashmessenger->getRawMessage()

            );
        }

        // echo "<pre> categoryList ";
        // var_dump($options);
        // echo "</pre>";
        // Asegúrate de que $options contenga los datos POST
        $cambios = isset($options['cambios']) ? json_decode($options['cambios'], true) : [];
        $store = isset($options['store']) ? json_decode($options['store'], true) : [];

        // Crear array para cambios
        $arrayCambios = [];
        foreach ($cambios as $key => $value) {
            // Obtener la parte antes del guion bajo
            $id = explode('_', $key)[0];

            // Si el id no existe en el array, inicializarlo
            if (!isset($arrayCambios[$id])) {
                $arrayCambios[$id] = [];
            }

            // Obtener la columna (parte después del guion bajo)
            $columna = explode('_', $key)[1];

            // Agregar los datos de la columna al array del id correspondiente
            $arrayCambios[$id][$columna] = $value;
        }

        // Crear array para store
        $arrayStores = [];
        foreach ($store as $storeItem) {
            $arrayStores[] = [
                'value' => $storeItem['value'],
                'text' => $storeItem['text']
            ];
        }

        $repository = new PosProductoRepository();

        $result = $repository->saveChangeProduct($arrayCambios, $arrayStores);
        $this->flashmessenger->addMessage(array('success' => 'Transaccion generada correctamente.'));

        // echo "<pre>  ";
        // var_dump($arrayCambios);
        // echo "</pre>";
        // echo "<pre>  ";
        // var_dump($result);
        // echo "</pre>";
        return array(

            'response' => true,

            'productos' => $result,

            'msg' =>  $this->flashmessenger->getRawMessage()

        );
    }
    public function getListCambiosProductosByTransaction($options)
    {
        $item = $options['cp_uuid'];
        $productRepository = new  PosProductoRepository();
        $storeRepository = new StoreRepository();
        $result = $productRepository->getListaProductosCambios($item);
        $listDetalles = "";


        foreach ($result as $detalle) {

            $storeName = $storeRepository->getListSelectStores($detalle['cp_store']);

            $stores = "";
            $count = 0;
            foreach ($storeName as $name) {

                if ($count < count($storeName)) {
                    $stores .= $name  . " | ";
                } else {
                    $stores .= $name;
                }
                $count++;
            }

            $listDetalles .= "<tr>  
    
        <td class='text-center'>" . $detalle['cp_categoria'] . "</td>

        <td class='text-center'>" . $detalle['p_codigo'] . "</td> 

        <td class='text-center'>" . $stores . "</td>

        <td class='text-center'>" . $detalle['nombre_para_pos'] . "</td> 

        <td class='text-center'>" . number_format($detalle['p_preview'], 2) . "</td>
        <td class='text-center'>" . number_format($detalle['p_new'], 2) . "</td>


        </tr>";
        }

        return array(
            'response' => true,
            'DataDetails' => $listDetalles

        );
    }

    //UG en esta funcion preparamos el update masivo en la tabla destino (de la sucursal)

    public function sendTransaction($options)
    {
        $cp_uuid = $options['cp_uuid'];
        $posProductRepository = new PosProductoRepository();
        $data = $posProductRepository->getCambiosProductosById($cp_uuid);
        $result = $posProductRepository->saveTransactionProduct($data);

        if ($result['success']) {
            // Actualizar el registro de la transacción
            $result_updateT = $posProductRepository->updateTransaction($cp_uuid, 2);
            $this->flashmessenger->addMessage(array('success' => 'Datos enviados correctamente.'));

            if ($result_updateT) {
                return [
                    'response' => true,
                    'msg' => $this->flashmessenger->getRawMessage()
                ];
            } else {
                return [
                    'response' => false,
                    'msg' => 'Failed to update transaction.'
                ];
            }
        } else {

            // Manejar el error retornado por saveTransactionProduct
            return [
                'response' => false,
                'msg' => 'Error: ' . $result['error']
            ];
        }
    }


    // public function sendTransaction($options)
    // {
    //     $cp_uuid = $options['cp_uuid'];

    //     //Obtener toda la informacion de la transaccion

    //     $posProductRepository = new PosProductoRepository();

    //     $data = $posProductRepository->getCambiosProductosById($cp_uuid);

    //     $result = $posProductRepository->saveTransactionProduct($data);

    //     if ($result) {

    //         //UG update registro de transaccion, porque los cambios en la/las sucursal ya se realizaron 
    //         $result_updateT = $posProductRepository->updateTransaction($cp_uuid, 2);
    //         $this->flashmessenger->addMessage(array('danger' => 'Datos enviados correctamente.'));

    //         if ($result_updateT) {
    //             return array(

    //                 'response' => true,

    //                 'msg' => $this->flashmessenger->getRawMessage()

    //             );
    //         }
    //         return array(
    //             'response' => true,

    //             'msg' => $this->flashmessenger->getRawMessage()
    //         );
    //     }
    // }

    public function uploadTransaction($options)
    {
        $cp_uuid = $options['cp_uuid'];
        //Obtener toda la informacion de la transaccion

        $posProductRepository = new PosProductoRepository();

        $data = $posProductRepository->getCambiosProductosById($cp_uuid);
        $result = $posProductRepository->uploadTransactions($data);
        if ($result) {
            //UG update registro de transaccion, porque los cambios en la/las sucursal ya se realizaron 
            $result_updateT = $posProductRepository->updateTransaction($cp_uuid, 3);

            $this->flashmessenger->addMessage(array('danger' => 'Datos sincronizados correctamente.'));

            return array(

                'response' => true,

                'msg' => $this->flashmessenger->getRawMessage()

            );
        }
    }
    //UG esta parte de codigo va a POS_PRODUCTO 14.07.24
    public function saveChangeProduct($options)
    {

        if (!is_array($options) || empty($options)) {
            $this->flashmessenger->addMessage(array('danger' => 'No existen datos en el array.'));

            echo "<pre> Error: opciones no válidas. </pre>";
            return array(

                'response' => false,

                'msg' => $this->flashmessenger->getRawMessage()

            );
        }

        // Asegúrate de que $options contenga los datos POST
        $p_uuidA = isset($options['p_uuidA']) ? $options['p_uuidA'] : [];
        $store = isset($options['store']) ? json_decode($options['store'], true) : [];


        // Crear array para store
        $arrayStores = [];
        foreach ($store as $storeItem) {
            $arrayStores[] = [
                'value' => $storeItem['value'],
                'text' => $storeItem['text']
            ];
        }

        $repository = new PosProductoRepository();

        $result = $repository->saveProductTransaction($p_uuidA, $arrayStores);
        $this->flashmessenger->addMessage(array('success' => 'Transaccion generada correctamente.'));

        // echo "<pre>  ";
        // var_dump($arrayCambios);
        // echo "</pre>";

        if (!$result) {
            return array(

                'response' => true,

                'productos' => $result,

                'msg' =>  $this->flashmessenger->getRawMessage()

            );
        }
        return array(

            'response' => false,

            'productos' => $result,

            'msg' =>  $result

        );
    }
    public function GetDetailsQuery($options)
    {
        $item = $options['log_uuid'];
        $productRepository = new  PosProductoRepository();
    
        $result = $productRepository->get_DetailsQuery($item);

        $listDetallesQuery = "";


        foreach ($result as $detalle) {         

            $listDetallesQuery .= "<tr>  
    
                <td class='text-center'>" . $detalle['type_log'] . "</td>

                <td class='text-center'>" . $detalle['query_log'] . "</td> 
            </tr>";
        }

        return array(
            'response' => true,
            'listDetallesQuery' => $listDetallesQuery

        );
    }
    public function ExecQuery($options)
    {
        $item = $options['log_uuid'];

        $productRepository = new  PosProductoRepository();

        $query = $productRepository->get_DetailsQuery($item);
        
    
        $result = $productRepository->Exec_Query($item,$query[0]['query_log']);

        if(isset($result['success'])) {
            if($result['success'] === "true"){
                return array(
                    'response' => true,
                    'msg' => $result
        
                );
            }else{
                return array(
                    'response' => false,
                    'msg' => $result
        
                );
            }
        }

        
    }

    public function ExecQueryBulk($options)
    {
        $log_uuids = $options['log_uuids']; // Este es el array con todos los log_uuid seleccionados
       
        $productRepository = new PosProductoRepository();

        $results = [];

        foreach ($log_uuids as $item) {
            $query = $productRepository->get_DetailsQuery($item);
            $result = $productRepository->Exec_Query($item, $query[0]['query_log']);

            if (isset($result['success']) && $result['success'] === "true") {
                $results[] = [
                    'log_uuid' => $item,
                    'status' => 'success'
                ];
            } else {
                $results[] = [
                    'log_uuid' => $item,
                    'status' => 'failed',
                    'error' => $result['error'] ?? 'Unknown error'
                ];
            }
        }

        return [
                'response' => true,
                'msg' => [
                    'results' => $results
                ]
            ];
    }

    public function getInsumosAsignadosAjax($options){
        $repository_product = new ProductRepository();

        $result = $repository_product->getInsumosAsignados($options['p_uuid']);
       
        $listDetallesQuery = "";

        $bandera = "";
        foreach ($result as $detalle) {     

            if ($detalle['regresa_inventario'] == 1) {
                $bandera = "Si";
            } else {
                $bandera = "No";
            }
            $listDetallesQuery .= "<tr id=".$detalle['p_uuid_pos']."  data-id=".$detalle['p_uuid_pos'].">  
                    
                <td class='text-center'><a id=".$detalle['id_insumo']." class='btnDeleteInsumoAsignado' onclick='deleteConsumibleAsignado(this,".$detalle['id_insumo'].")'><i class='fa fa-trash btn btn-sm btn-danger'></i></a></td>
                <td class='text-center'>" . $detalle['code'] . "</td>
                <td class='text-center'>" . $detalle['description'] . "</td>

                <td class='text-center'>" . $detalle['um'] . "</td> 
                <td class='text-center'>" . $detalle['category'] . "</td> 
                <td class='text-center'>" . number_format($detalle['cost']) . "</td> 
                <td class='text-center'>" . $detalle['factor'] . "</td> 
                <td class='text-center'>" . $bandera . "</td> 
                

            </tr>";
        }
        return array(
            'response' => true,
            'listDetallesQuery' => $listDetallesQuery

        );
    }
    public function saveConsumibleAjax($options){
        $repository_product = new ProductRepository();

        $result = $repository_product->saveConsumible($options);
        return array(
            'response' => true,
            'result' => $result

        );
    }
    
    public function deleteConsumibleAjax($options){
        $repository_product = new ProductRepository();

        $result = $repository_product->deleteConsumible($options['id_insumo']);
        return array(
            'response' => true,
            'result' => $result

        );
    }
    
}
