<?php

/**
 *          ****************************************************************************
 *          **********************||   PANEL  ||******************
 *          ****************************************************************************
 * 

 *          
 */

//  DEBUG EN PANTALLA   //
error_reporting(E_ALL);
ini_set('display_errors', 1);
set_time_limit(120); 

//  HABILITAMOS EL ACCESO PUBLICO PARA REALIZAR LLAMADAS AJAX DESDE DOMINIOS PUBLICOS   /
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Headers: Origin, Content-Type, Authorization, X-Auth-Token');
header('Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS');
header('Content-type: application/javascript; charset=utf-8');

//   RESCATAMOS TODO EL OUTPUT  //
/**  PARA IMPRIMIRLO EN JSON
 * $output = ob_get_contents(); ob_end_clean();
 */
ob_start();

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'assets/plugins/PHPMailer/src/Exception.php';
require 'assets/plugins/PHPMailer/src/PHPMailer.php';
require 'assets/plugins/PHPMailer/src/SMTP.php';

require 'assets/scripts/utils.php';
//require 'assets/scripts/conn.php';
require 'assets/scripts/c.php';

$json = array();
$guiasPitadas = [];

if ($_POST || $_GET) {
    if ($_POST['meth']) {
        $method =    broom('reg', $_POST['meth']);
    }
    if ($_GET['meth']) {
        $method = broom('reg', $_GET['meth']);
    }

    //          USUARIO INICIA SESION           //
    if ($method == 'login') {

        $username = broom('reg', $_POST["username"]);
        $password = hash('sha512', $_POST['password']);
        $apiuri = $_POST['apiuri'];
        error_log('/////////////////// ' . $password);
        ////            CONSULTAMOS EL USUARIO EN LA BASE DE DATOS A VER SI EXISTE              ////
        $query = " SELECT * "
            . "FROM gt_usuario "
            . "WHERE userUsuario = '" . $username . "'";
        //error_log('/////////////////// '. $password );
        $result = $c->query($query);
        if (!$result) {
            $json['scriptResp'] = "userqueryFail";
            $json['q'] = $query;
            $output = ob_get_contents();
            ob_end_clean();
            $json['output'] = $output;
            echo json_encode($json);
            return;
        }
        $rows = $result->num_rows;
        $row = $result->fetch_array(MYSQLI_ASSOC);

        ////          RETORNAMOS UN JSON AL AJAX PARA ALIMENTAR EL JAVASCRIPT          ////

        if (($rows != 0) && (strcmp($row["userUsuario"], $username) == 0) && ($row['passUsuario'] == $password)) {

            //   VERIFICAMOS SI TIENE IMAGEN CARGADA || CARGAMOS IMAGEN PREDETERMINADA        //
            $isavatar = "assets/img/users/" . $row["idUsuario"] . ".jpg";
            if (file_exists($isavatar)) {
                $row['userImg'] = $apiuri . $isavatar;
            } else {
                $isavatar2 = "assets/img/users/" . $row["idUsuario"] . ".png";
                if (file_exists($isavatar2)) {
                    $row['userImg'] = $apiuri . $isavatar2;
                } else {
                    $row['userImg'] = $apiuri . "assets/img/users/default.jpg";
                }
            }
            $row['panelView'] = file_get_contents('modules/' . $row["panelUsuario"] . '/view.php');
            $row['login'] = "YES";

            $val_update = "UPDATE gt_usuario SET loginUsuario = '" . date('Y-m-d H:i:s') . "' WHERE idUsuario = '" . $row["idUsuario"] . "';";
            $val_result = $c->query($val_update) or die("{'scriptResp' : 'queryFailedd', 'query' : '" . $val_update . "'}");

            $json['userIntel'] = $row;
            $json['scriptResp'] = "match";
            $output = ob_get_contents();
            ob_end_clean();
            $json['output'] = $output;
            echo json_encode($json);
            return;
        } else {


            $sql = "SELECT CODVENDEDOR,NOMVENDEDOR, PASSWORDWEB FROM VENDEDORES WHERE NOMVENDEDOR = '" . $_POST["username"] . "' AND PASSWORDWEB = '" . $_POST["password"] . "'";
            $pa1 = array();
            $op1 = array("scrollable" => SQLSRV_CURSOR_KEYSET);

            $re1 = sqlsrv_query($conexion, $sql, $pa1, $op1);
            if (sqlsrv_num_rows($re1) != 0) {
                while ($fila = sqlsrv_fetch_array($re1)) {
                    $row = [];
                    $row['panelView'] = file_get_contents('modules/home/view.php');
                    $row['login'] = "YES";
                    $row['panelUsuario'] = 'home';
                    $row['userImg'] = $apiuri . "assets/img/users/default.jpg";
                    $row['idUsuario'] = $fila['CODVENDEDOR'];;
                    $row['userUsuario'] = $fila['NOMVENDEDOR'];;
                    $row['nombreUsuario'] = $fila['NOMVENDEDOR'];;
                    $row['rolUsuario'] = 'Usuario';
                }

                $json['userIntel'] = $row;
                $json['scriptResp'] = "match";
                $output = ob_get_contents();
                ob_end_clean();
                $json['output'] = $output;
                echo json_encode($json);
                return;
            }
            /* 
            $wsdlUrl = 'http://10.238.26.69:9298/Service1.asmx?wsdl';
            $client = new SoapClient($wsdlUrl);

            $params = new stdClass();
            $params->userName = $_POST['username'];
            $params->password = $_POST['password'];
            $params->date = date('Y-m-d H:i:s');
            $result = $client->GetVendedoresForLogin($params);
            $objs = json_decode($result->GetVendedoresForLoginResult, true);

            if ($objs['code'] == '200') {

                error_log('/////////////////// ' . print_r($objs, true));
                $row = [];
                $row['panelView'] = file_get_contents('modules/home/view.php');
                $row['login'] = "YES";
                $row['panelUsuario'] = 'home';
                $row['userImg'] = $apiuri . "assets/img/users/default.jpg";
                $row['idUsuario'] = $objs['vendedoresList'][0]['Codvendedor'];
                $row['userUsuario'] = $objs['vendedoresList'][0]['Nomvendedor'];
                $row['nombreUsuario'] = $objs['vendedoresList'][0]['Nomvendedor'];
                $row['rolUsuario'] = $objs['vendedoresList'][0]['Tipousuario'];

                $json['userIntel'] = $row;
                $json['scriptResp'] = "match";
                $output = ob_get_contents();
                ob_end_clean();
                $json['output'] = $output;
                echo json_encode($json);
                return;
            } 
            */
            $json['scriptResp'] = "noMatch";
            $json['passwo'] = $password;
            $json['password'] = $row['passUsuario'];
            $json['q'] = $query;
            $output = ob_get_contents();
            ob_end_clean();
            $json['output'] = $output;
            echo json_encode($json);
            return;
        }
    }

    //          USUARIO INICIA SESION  CON GOOGLE         //
    if ($method == 'googlelogin') {

        $fullname = broom('reg', $_POST["fullname"]);
        $pic = $_POST['pic'];
        $email = $_POST['email'];

        $row = [];
        $row['idUsuario'] = $email;
        $row['rolUsuario'] = 'Administrador';
        $row['userImg'] = $pic;
        $row['nombreUsuario'] = $fullname;
        $row['temaUsuario'] = '1';
        $row['panelUsuario'] = 'home';

        $row['panelView'] = file_get_contents('modules/' . $row["panelUsuario"] . '/view.php');
        $row['login'] = "YES";

        $json['userIntel'] = $row;
        $json['scriptResp'] = "match";
        $output = ob_get_contents();
        ob_end_clean();
        $json['output'] = $output;
        echo json_encode($json);
        return;
    }

    //          GESTIONAR EL PANEL A MOSTRAR            //
    if ($method == 'loadPanel') {
        $panel = $_POST["panel"];
        $user = broom('reg', $_POST["user"]);

        if ($panel == 'undefined') {
            $panelView = file_get_contents('assets/views/login.php');
            $json['scriptResp'] = "loaded";
            $json['panel'] = $panelView;
            $json['panelName'] = 'login';
            $output = ob_get_contents();
            ob_end_clean();
            $json['output'] = $output;
            echo json_encode($json);
            return;
        }

        $panelView = file_get_contents('modules/' . $panel . '/view.php');
        $panelcontrol = file_get_contents('modules/' . $panel . '/controller.php');
        //        $select = "UPDATE gt_usuario SET panelUsuario = '" . $panel . "' WHERE idUsuario = '" . $user . "'";
        //        $result = $c->query($select);

        $json['scriptResp'] = "loaded";
        $json['panel'] = $panelView;
        $json['control'] = $panelcontrol;
        $json['panelName'] = $panel;
        $output = ob_get_contents();
        ob_end_clean();
        $json['output'] = $output;
        echo json_encode($json);
        return;
    }

    //          RETORNAR EL MENU LATERAL AUTORIZADO PARA EL USUARIO            //
    if ($method == 'showSideBar') {
        $user = $_POST["user"];

        if ($user == 'undefined') {
            $json['scriptResp'] = "error";
            $json['output'] = $output;
            echo json_encode($json);
            return;
        }

        $isGoog = explode('@', $user);
        if ($isGoog[1]) {
            $viewSidebar = file_get_contents('assets/views/sidebarAdmin.php');
            $json['scriptResp'] = "loaded";
            $json['sideb'] = $viewSidebar;
            $output = ob_get_contents();
            ob_end_clean();
            $json['output'] = $output;
            echo json_encode($json);
            return;
        }
        /* $select = "SELECT *  FROM gt_usuario  WHERE idUsuario = '" . $user . "'";
        $result = $c->query($select);
        $row = $result->fetch_array(MYSQLI_ASSOC);

        if ($row['rolUsuario'] == 'Administrador') {
            $viewSidebar = file_get_contents('assets/views/sidebarAdmin.php');
        }
        if ($row['rolUsuario'] == 'Nuevo') {
            $viewSidebar = file_get_contents('assets/views/sidebarNot.php');
        } */

        $viewSidebar = file_get_contents('assets/views/sidebarAdmin.php');
        $json['scriptResp'] = "loaded";
        $json['sideb'] = $viewSidebar;
        $output = ob_get_contents();
        ob_end_clean();
        $json['output'] = $output;
        echo json_encode($json);
        return;
    }

    //          GESTIONAR EL PANEL A MOSTRAR            //
    if ($method == 'construct') {

        $getJuice = file_get_contents('assets/scripts/juice.php');
        $video = getBGVideo();

        $json['scriptResp'] = "done";
        $json['view'] = $panelView;
        $json['video'] = $video;
        $json['juice'] = $getJuice;
        $output = ob_get_contents();
        ob_end_clean();
        $json['output'] = $output;
        echo json_encode($json);
        return;
    }

    //          ALIMENTAR LOS INDICADORES            //
    if ($method == 'feedHome') {

        $json['scriptResp'] = "done";
        $output = ob_get_contents();
        ob_end_clean();
        $json['output'] = $output;
        echo json_encode($json);
        return;
    }

    //          ALIMENTAR LOS PORTALES            //
    if ($method == 'feedPortals') {
        $apiuri = $_POST['apiuri'];

        // TOTAL DE PORTALES //
        $query = "  SELECT * FROM gt_portals ";
        $result = $c->query($query);
        $rows = $result->num_rows;

        $htmlPorts = ' 
            
							<div class="col-sm-12 col-md-6 col-lg-3">
                            <div class="card bg-info">
                                <div class="card-body">
                                    <div class="d-flex no-block align-items-center">
                                        <div>
                                            <h6 class="text-white">Sales</h6>
                                            <h2 class="text-white m-0 font-weight-normal">25k</h2>
                                        </div>
                                        <div class="ml-auto">
                                            <span class="text-white display-6"><i class="fa fa-signal fa-2x"></i></span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
        ';
        if ($rows != 0) {
            while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
                if ($row['deletedPortal'] == '0') {
                    if ($row['statusPortal'] == 'true') {
                        $stat = 'checked="checked"';
                        $status = 'Activo';
                    } else {
                        $stat = ' ';
                        $status = 'Inactivo';
                    }
                    $isshortName = '';
                    if (strlen($row['namePortal']) > strlen(substr($row['namePortal'], 0, 15))) {
                        $isshortName = '...';
                    }
                    $isshortAgent = '';
                    if (strlen($row['agentPortal']) > strlen(substr($row['agentPortal'], 0, 15))) {
                        $isshortAgent = '...';
                    }
                    $htmlPorts .= '
                    <div class="col-md-3">
                        <div class="card portalPanelCard anim" data-idPortal="' . $row['idPortal'] . '">
                            <div class="card-body">
                                <div class="card-box tilebox-one">
                                    <i class="icon-layers float-right text-muted"><i class="fa fa-wifi text-info" aria-hidden="true"></i></i>
                                    <h2 class="m-b-20">' . substr($row['namePortal'], 0, 15) . $isshortName . ' </h2>
                                    <span>Leads totales</span><span class="badge badge-primary marg5"> 0 </span> <br>
                                    <span>Visitas totales</span><span class="badge badge-primary marg5"> 0 </span><br>
                                    <span>Encargado: </span><span class="badge badge-primary marg5"> ' . substr($row['agentPortal'], 0, 15) . $isshortAgent . ' </span><br>
                                    
                                </div>
                                
                                <div class="visitor-list marg15">
                                    <div class="media m-0 mt-0 border-bottom">
                                        <img class="avatar brround avatar-md mr-3" alt="avatra-img" src="' . $apiuri . 'assets/img/port/' . $row['imgPortal'] . '">
                                        <div class="media-body">
                                            <label class="custom-switch marg15">
                                                <input disabled="disabled" type="checkbox" ' . $stat . ' name="custom-switch-checkbox" class="custom-switch-input" >
                                                <span class="custom-switch-indicator"></span>
                                                <span class="custom-switch-description text-white">' . $status . '</span>
                                            </label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="p-4 b-t card-footer">
                                <div class="row text-center">
                                    <div class="col-6 border-right text-center">
                                        <div class="text-center">
                                            <a href="#" class="fw-500 editThisPortal">
                                                <i class="fa fa-pencil-square  mr-5"></i>Editar
                                                <div class="offscreen editPortalID">' . $row['idPortal'] . '</div>
                                            </a>
                                        </div>
                                    </div>
                                    <div class="col-6 text-center">
                                        <a href="#" class="fw-500 deleteThisPortal">
                                            <i class="fa fa-times-circle  mr-5"></i>Eliminar
                                            <div class="offscreen deletePortalID">' . $row['idPortal'] . '</div>
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    ';
                    $shoingPortals = 1;
                }
            }
            if ($shoingPortals != 1) {
                $json['isEmpty'] = 'yes';
            }
        } else {
            $json['isEmpty'] = 'yes';
        }


        $json['scriptResp'] = "done";
        $json['html'] = $htmlPorts;
        $output = ob_get_contents();
        ob_end_clean();
        $json['output'] = $output;
        echo json_encode($json);
        return;
    }

    //          CREAR UN NUEVO PORTAL            //
    if ($method == 'newPortal') {

        //** CARGAMOS LA IMAGEN DEL PORTAL
        $path = 'assets/img/port/';
        $directorio = opendir($path);

        /** CALCULAMOS EL NOMBRE CONSECUTIVO DE LA SIGUIENTE IMAGEN ESTE NOMBRE SE LE ASIGNA AL PORTAL EN LA BD*/
        $filename = 1;
        while ($archivo = readdir($directorio)) {
            if (!is_dir($archivo)) {
                $filename++;
            }
        }

        $file = $path . basename($_FILES["imgPortal"]["name"]);
        $filext = pathinfo($file, PATHINFO_EXTENSION);
        $fullFile = $path . $filename . '.' . $filext;

        if (move_uploaded_file($_FILES["imgPortal"]["tmp_name"], $fullFile)) {
            chmod($fullFile, 0666);

            /** FILTRAMOS LOS DATOS PARA EL PORTAL */
            $name = broom('text', $_POST['namePortal']);
            $img = $filename . '.' . $filext;
            $date = date('Y-m-d H:i:s');
            $agent = broom('spa', $_POST['agentPortal']);
            $status = broom('reg', $_POST['statusPortal']);
            $limit = broom('num', $_POST['limitPortal']);
            $url = broom('url', $_POST['urlPortal']);

            // AGREGAR PORTAL //
            $query = " INSERT INTO gt_portals ( namePortal, imgPortal, datePortal, agentPortal, statusPortal, lastUpdatedPortal, limitPortal, urlPortal, deletedPortal) ";
            $query .= "VALUES ('" . $name . "','" . $img . "','" . $date . "','" . $agent . "','" . $status . "','" . $date . "','" . $limit . "','" . $url . "', '0')";
            $result = $c->query($query);
            $portId = $c->insert_id;
            $queryNext = " INSERT INTO gt_portalDetail ( idPortal, titlePortal, bgPortal, formPortal, hasFbPortal, dateDetailPortal, redirPortal) ";
            $queryNext .= "VALUES ('$portId','Ingrese sus datos para continuar','1.jpg','" . addslashes($defaultPortalForm) . "','0','$date', 'https://burtonservers.com')";
            $resultNext = $c->query($queryNext);

            $json['scriptResp'] = "done";
            $json['msg'] = "Image Uploaded // Portal Created";
            $output = ob_get_contents();
            ob_end_clean();
            $json['output'] = $output;
            $json['q'] = $query;
            $json['post'] = json_encode($_POST);
            $json['get'] = json_encode($_GET);
            $json['files'] = json_encode($_FILES);
            $json['name'] = $name;
            $json['namep'] = $_POST['namePortal'];
            $json['namef'] = broom('text', $_POST['namePortal']);
            echo json_encode($json);
            return;
        } else {
            $json['scriptResp'] = "done";
            $json['error'] = 'errorImg';
            $json['post'] = json_encode($_POST);
            $json['files'] = json_encode($_FILES);
            $json['html'] = $htmlPorts;
            $output = ob_get_contents();
            ob_end_clean();
            $json['output'] = $output;
            echo json_encode($json);
            return;
        }
    }

    //          DEVOLVER LOS DATOS DEL PORTAL            //
    if ($method == 'getPortal') {
        $apiuri = $_POST['apiuri'];
        $idportal = broom('num', $_POST['idPortal']);

        // TOTAL DE PORTALES //
        $query = "  SELECT * FROM gt_portals p 
                INNER JOIN gt_portalDetail pd 
                    ON (p.idPortal = pd.idPortal) 
                WHERE p.idPortal = '$idportal' 
                ORDER BY pd.idDetail DESC
                LIMIT 1 ";
        $result = $c->query($query);
        $rows = $result->num_rows;

        if ($rows < 1) {
            $json['scriptResp'] = "error";
            $json['msg'] = 'portal not found';
            $output = ob_get_contents();
            ob_end_clean();
            $json['output'] = $output;
            echo json_encode($json);
            return;
        } else {
            $row = $result->fetch_array(MYSQLI_ASSOC);
            $json['scriptResp'] = "done";
            $json['portalData'] = $row;
            $output = ob_get_contents();
            ob_end_clean();
            $json['output'] = $output;
            echo json_encode($json);
            return;
        }
    }

    //          EDITAR PORTAL LOS PORTALES            //
    if ($method == 'editPortal') {
        $apiUri = $_POST['apiuri'];
        $idportal = broom('num', $_POST['idPortal']);

        if ($_POST['editing'] == 'status') {
            $statusPortal = broom('reg', $_POST['statusPortal']);
            $queryNext = " UPDATE gt_portals SET statusPortal = '$statusPortal' WHERE idPortal = '$idportal' ";
            $resultNext = $c->query($queryNext);

            $json['scriptResp'] = "done";
            $output = ob_get_contents();
            ob_end_clean();
            $json['output'] = $output;
            echo json_encode($json);
            return;
        }

        if ($_POST['editing'] == 'statusFB') {
            $statusHasFb = broom('reg', $_POST['statusHasFb']);
            if ($statusHasFb == 'true') {
                $hasfb = '1';
            } else {
                $hasfb = '0';
            }
            // OBTENER PORTAL //
            $query = "  SELECT * FROM gt_portals p 
                        INNER JOIN gt_portalDetail pd 
                            ON (p.idPortal = pd.idPortal) 
                        WHERE p.idPortal = '$idportal' 
                        ORDER BY pd.idDetail DESC
                        LIMIT 1 ";
            $result = $c->query($query);
            $row = $result->fetch_array(MYSQLI_ASSOC);
            $date = date('Y-m-d H:i:s');

            $queryNext = " INSERT INTO gt_portalDetail ( idPortal, titlePortal, bgPortal, formPortal, hasFbPortal, dateDetailPortal) ";
            $queryNext .= "VALUES ('" . $idportal . "','" . $row['titlePortal'] . "','" . $row['bgPortal'] . "','" . addslashes($row['formPortal']) . "','$hasfb','$date')";
            $resultNext = $c->query($queryNext);

            $json['scriptResp'] = "done";
            $output = ob_get_contents();
            ob_end_clean();
            $json['output'] = $output;
            echo json_encode($json);
            return;
        }

        if ($_POST['editing'] == 'LogoIMG') {

            /** CALCULAMOS EL NOMBRE CONSECUTIVO DE LA SIGUIENTE IMAGEN ESTE NOMBRE SE LE ASIGNA AL PORTAL EN LA BD **/
            $path = 'assets/img/port/';
            $directorio = opendir($path);
            $filename = 1;
            while ($archivo = readdir($directorio)) {
                if (!is_dir($archivo)) {
                    $filename++;
                }
            }

            $file = $path . basename($_FILES["imgPortal"]["name"]);
            $filext = pathinfo($file, PATHINFO_EXTENSION);
            $fullFile = $path . $filename . '.' . $filext;

            if (move_uploaded_file($_FILES["imgPortal"]["tmp_name"], $fullFile)) {
                chmod($fullFile, 0666);

                $img = $filename . '.' . $filext;
                $queryNext = " UPDATE gt_portals SET imgPortal = '$img' WHERE idPortal = '$idportal' ";
                $resultNext = $c->query($queryNext);

                $json['scriptResp'] = "done";
                $json['imgPortal'] = $img;
                $output = ob_get_contents();
                ob_end_clean();
                $json['output'] = $output;
                echo json_encode($json);
                return;
            }
        }

        if ($_POST['editing'] == 'BGIMG') {

            /** CALCULAMOS EL NOMBRE CONSECUTIVO DE LA SIGUIENTE IMAGEN ESTE NOMBRE SE LE ASIGNA AL PORTAL EN LA BD **/
            $path = 'assets/img/portbg/';
            $directorio = opendir($path);
            $filename = 1;
            while ($archivo = readdir($directorio)) {
                if (!is_dir($archivo)) {
                    $filename++;
                }
            }

            $file = $path . basename($_FILES["imgPortal"]["name"]);
            $filext = pathinfo($file, PATHINFO_EXTENSION);
            $fullFile = $path . $filename . '.' . $filext;

            if (move_uploaded_file($_FILES["imgPortal"]["tmp_name"], $fullFile)) {
                chmod($fullFile, 0666);

                $query = "  SELECT * FROM gt_portals p 
                        INNER JOIN gt_portalDetail pd 
                            ON (p.idPortal = pd.idPortal) 
                        WHERE p.idPortal = '$idportal' 
                        ORDER BY pd.idDetail DESC
                        LIMIT 1 ";
                $result = $c->query($query);
                $row = $result->fetch_array(MYSQLI_ASSOC);
                $date = date('Y-m-d H:i:s');
                $img = $filename . '.' . $filext;

                $queryNext = " INSERT INTO gt_portalDetail ( idPortal, titlePortal, bgPortal, formPortal, hasFbPortal, dateDetailPortal) ";
                $queryNext .= "VALUES ('" . $idportal . "','" . $row['titlePortal'] . "','$img','" . addslashes($row['formPortal']) . "','" . $row['hasFbPortal'] . "','$date')";
                $resultNext = $c->query($queryNext);

                $json['scriptResp'] = "done";
                $json['imgPortal'] = $img;
                $output = ob_get_contents();
                ob_end_clean();
                $json['output'] = $output;
                echo json_encode($json);
                return;
            }
        }

        if ($_POST['editing'] == 'Fields') {
            $namePortal = $_POST['namePortal'];
            $agentPortal = $_POST['agentPortal'];
            $urlPortal = $_POST['urlPortal'];
            $titlePortal = broom('text', $_POST['titlePortal']);
            $limitPortal = $_POST['limitPortal'];

            $queryNext = " UPDATE gt_portals SET namePortal = '$namePortal', agentPortal = '$agentPortal', urlPortal = '$urlPortal', limitPortal = '$limitPortal'  WHERE idPortal = '$idportal' ";
            $resultNext = $c->query($queryNext);

            $query = "  SELECT * FROM gt_portals p 
                        INNER JOIN gt_portalDetail pd 
                            ON (p.idPortal = pd.idPortal) 
                        WHERE p.idPortal = '$idportal' 
                        ORDER BY pd.idDetail DESC
                        LIMIT 1 ";
            $result = $c->query($query);
            $row = $result->fetch_array(MYSQLI_ASSOC);
            $date = date('Y-m-d H:i:s');

            $queryNext = " INSERT INTO gt_portalDetail ( idPortal, titlePortal, bgPortal, formPortal, hasFbPortal, dateDetailPortal) ";
            $queryNext .= "VALUES ('" . $idportal . "','$titlePortal','" . $row['bgPortal'] . "','" . addslashes($row['formPortal']) . "','" . $row['hasFbPortal'] . "','$date')";
            $resultNext = $c->query($queryNext);

            $json['scriptResp'] = "done";
            $output = ob_get_contents();
            ob_end_clean();
            $json['output'] = $output;
            echo json_encode($json);
            return;
        }

        if ($_POST['editing'] == 'formPortal') {
            $code = $_POST['formPortal'];

            // OBTENER PORTAL //
            $query = "  SELECT * FROM gt_portals p 
                        INNER JOIN gt_portalDetail pd 
                            ON (p.idPortal = pd.idPortal) 
                        WHERE p.idPortal = '$idportal' 
                        ORDER BY pd.idDetail DESC
                        LIMIT 1 ";
            $result = $c->query($query);
            $row = $result->fetch_array(MYSQLI_ASSOC);
            $date = date('Y-m-d H:i:s');

            $queryNext = " INSERT INTO gt_portalDetail ( idPortal, titlePortal, bgPortal, formPortal, hasFbPortal, dateDetailPortal) ";
            $queryNext .= "VALUES ('" . $idportal . "','" . $row['titlePortal'] . "','" . $row['bgPortal'] . "','" . addslashes($code) . "','" . $row['hasFbPortal'] . "','$date')";
            $resultNext = $c->query($queryNext);

            $json['scriptResp'] = "done";
            $output = ob_get_contents();
            ob_end_clean();
            $json['output'] = $output;
            echo json_encode($json);
            return;
        }
    }

    //          ELIMINAR PORTAL LOS PORTALES            //
    if ($method == 'deletePortal') {
        $apiUri = $_POST['apiuri'];
        $idportal = broom('num', $_POST['idPortal']);
        $queryNext = " UPDATE gt_portals SET deletedPortal = '1' WHERE idPortal = '$idportal' ";
        $resultNext = $c->query($queryNext);

        $json['scriptResp'] = "done";
        $output = ob_get_contents();
        ob_end_clean();
        $json['output'] = $output;
        echo json_encode($json);
        return;
    }

    //         GUARDAR NUEVA VISITA DE PORTAL            //
    if ($method == 'logVisit') {

        $date = date('Y-m-d H:i:s');
        $queryNext = " INSERT INTO gt_visits ( guidVisit, idLead, dateVisit, portalVisit, typeVisit) ";
        $queryNext .= " VALUES ('" . $_POST['gguid'] . "','0','" . $date . "','" . $_POST['portal'] . "','0')";
        $resultNext = $c->query($queryNext);

        $output = ob_get_contents();
        $json['post'] = json_encode($_POST);
        $json['get'] = json_encode($_GET);
        $json['files'] = json_encode($_FILES);
        $json['msg'] = "log visit";
        $json['output'] = $output;
        ob_end_clean();
        echo json_encode($json);
        return;
    }

    //         GUARDAR NUEVA SESION DE PORTAL            //
    if ($method == 'saveNewLead') {

        $date = date('Y-m-d H:i:s');
        $queryNext = " INSERT INTO gt_leads ( guidLead, dateLead, portalLead, nameLead, phoneLead, emailLead) ";
        $queryNext .= " VALUES ('" . $_POST['guid'] . "','" . $date . "','" . $_POST['portal'] . "','" . $_POST['name'] . "','" . $_POST['telephone'] . "','" . $_POST['email'] . "') ";
        $resultNext = $c->query($queryNext);

        if ($resultNext) {

            $row = [];
            $row['idLead'] = $c->insert_id;
            $row['guidLead'] = $_POST['guid'];
            $row['dateLead'] = $date;
            $row['portalLead'] = $_POST['portal'];
            $row['nameLead'] = $_POST['name'];
            $row['phoneLead'] = $_POST['telephone'];
            $row['emailLead'] = $_POST['email'];

            $json['scriptResp'] = "done";
            $json['action'] = "leadSaved";
            $json['leadMeta'] = $row;
            $output = ob_get_contents();
            ob_end_clean();
            $json['output'] = $output;
            echo json_encode($json);
            return;
        } else {
            $json['scriptResp'] = "error";
            $output = ob_get_contents();
            ob_end_clean();
            $json['output'] = $output;
            echo json_encode($json);
            return;
        }
    }

    //          GENCSV           //
    if ($method == 'newCSV') {

        $report = json_decode($_POST['data'], true);

        $path = 'assets/reports/' . $report['title'] . date('Ymd-His') . '.csv';
        $fp = fopen($path, 'w');

        $headers = explode(',', $report['headers']);
        if ($fp) {
            fputcsv($fp, $headers, ';');
            foreach ($report['dataCont'] as $repLine) {
                fputcsv($fp, explode(',', $repLine), ';');
            }
        }
        fclose($fp);

        $json['scriptResp'] = "done";
        $output = ob_get_contents();
        ob_end_clean();
        $json['output'] = $output;
        $json['rep'] = $report;
        $json['enlace'] = $path;
        echo json_encode($json);
        return;
    }

    //          REPORT           //
    if ($method == 'report') {
        $apiuri = $_POST['apiuri'];

        // USUARIOS ACTIVOS EN LA PLATAFORMA //
        $query = "SELECT * FROM public.user WHERE created_at >= '2019-11-11' and is_provider = 'f'";
        $result = pg_query($dbconn, $query);
        $treg = pg_fetch_all($result);
        $num_fields = count($treg);

        $headers = array('Nombre', 'Apellido', 'Email', 'Creado en', 'Telefono');

        $fp = fopen('php://output', 'w');
        if ($fp && $result) {
            fputcsv($fp, $headers, ';');
            foreach ($treg as $userReg) {
                $row = [];
                $row[] = $userReg['first_name'];
                $row[] = $userReg['last_name'];
                $row[] = $userReg['email'];
                $row[] = $userReg['created_at'];
                $row[] = $userReg['cell_phone_number'];
                fputcsv($fp, $row, ';');
            }
            header('Content-Type: text/csv; charset=utf-8');
            header("Content-Disposition: attachment; filename=usuariosregistrados" . date('Ymd-His') . ".csv");
            return;
        }

        $json['scriptResp'] = "noRep";
        $output = ob_get_contents();
        ob_end_clean();
        $json['output'] = $output;
        echo json_encode($json);
        return;
    }

    //          GUARDAR NUEVA TOMA           //
    if ($method == 'saveNewToma') {

        $date = date('Y-m-d H:i:s');
        $queryNext = " INSERT INTO gt_tomas ( userToma, fechaToma, objToma, statusToma) ";
        $queryNext .= " VALUES ('" . $_POST['userToma'] . "','" . $date . "','" . json_encode($_POST['inventario']) . "','1') ";
        $resultNext = $c->query($queryNext);

        if ($resultNext) {

            error_log('//////////////////   PRESO           ///////////////////////////////');
            $opts = array(
                'http' => array(
                    'user_agent' => 'PHPSoapClient'
                )
            );
            $context = stream_context_create($opts);
            $soapClientOptions = array(
                'stream_context' => $context,
                'cache_wsdl' => WSDL_CACHE_NONE
            );

            $wsdlUrl = 'http://10.238.26.69:9298/Service1.asmx?wsdl';
            $client = new SoapClient($wsdlUrl);

            error_log('//////////////////   POSSO           ///////////////////////////////');
            $params = new stdClass();
            $params->inventario = $_POST['inventario'];
            $result = $client->CreateInventarioFisico($params);

            $json['scriptResp'] = "done";
            $json['status'] = "saved";
            $output = ob_get_contents();
            ob_end_clean();
            $json['output'] = $output;
            echo json_encode($json);
            return;
        } else {
            $json['scriptResp'] = "error";
            $json['q'] = $queryNext;
            $json['qer'] = $c->error;
            $output = ob_get_contents();
            ob_end_clean();
            $json['output'] = $output;
            echo json_encode($json);
            return;
        }
    }

	//          VERIFICAR NUEVA TOMA           //
    if ($method == 'saveVerToma') {

        $date = date('Y-m-d H:i:s');
        $queryNext = " INSERT INTO gt_tomas ( userToma, fechaToma, objToma, statusToma) ";
        $queryNext .= " VALUES ('" . $_POST['userToma'] . "','" . $date . "','" . json_encode($_POST['inventario']) . "','1') ";
        $resultNext = $c->query($queryNext);
		$array = json_decode($_POST['inventario'],true);
		$array1 =$array['inventario']['inventariodetail'];
		$array2= json_decode($array1);
		$var = $array2['inventario'];
        if ($resultNext) {

			foreach($array1 as $tomas){
				
				//$sql = "INSERT INTO JOIN_INVENTARIO_FISICO_REV (BODEGA,UBICACION,CAJAMASTER,CODBARRAS,UNIDADES,FECHAALTA,USUARIO,GONDOLA,DOCUMENTO,IDTRANSACCION,IDLINEAT,IDESTADO,REV) 
				//		VALUES ('" . $tomas['bodega'] . "','". $tomas['ubicacion'] . "','". $tomas['cajamaster']."','".$tomas['codbarras']."',".$tomas['unidades'].",'".$date."',".$tomas['usuario'].",".$tomas['gondola'].",0,".$tomas['idtransaccion'].",".$tomas['idlinea'].",0,".$tomas['rev'].") ";
				//$resultNext1 = $c->query($queryNext1);
				$sql = "INSERT INTO JOIN_INVENTARIO_FISICO_REV (BODEGA,UBICACION,CAJAMASTER,CODBARRAS,UNIDADES,FECHAALTA,USUARIO,GONDOLA,DOCUMENTO,IDTRANSACCION,IDLINEAT,IDESTADO,REV) 
						VALUES ('".$tomas['bodega']."','".$tomas['ubicacion']."','".$tomas['cajamaster']."','".$tomas['codbarras']."',".$tomas['unidades'].",GETDATE(),'".$tomas['usuario']."',".$tomas['gondola'].",0,".$tomas['idtransaccion'].",".$tomas['idlineat'].",0,".$tomas['rev'].")";
				$op1 = array("scrollable" => SQLSRV_CURSOR_KEYSET);
				$pa1 = array();
				$re1 = sqlsrv_query($conexion, $sql, $pa1, $op1);
				
				$json['q'] = $re1;
				$json['qer'] = $sql;//$c->error;
				$json['qer1'] = sqlsrv_errors();
				//$json['qer2'] = $c->error;
				
			}
            $json['scriptResp'] = "done";
            $json['status'] = "saved";
            $output = ob_get_contents();
            ob_end_clean();
            $json['output'] = $output;
            echo json_encode($json);
			//sqlsrv_close($conexion);
            return;
        } else {
            $json['scriptResp'] = "error";
            $json['q'] = $queryNext;
            $json['qer'] = $c->error;
            $output = ob_get_contents();
            ob_end_clean();
            $json['output'] = $output;
            echo json_encode($json);
            return;
        }
    }
    
	//          CONSULTAR DEVOLUCION        //
    if ($method == 'consultarDevol') {

        $order = $_POST['devolVal'];

        $wsdlUrl = 'http://10.238.26.69:9298/Service1.asmx?wsdl';
        $client = new SoapClient($wsdlUrl);

        error_log('//////////////////  ///////////////////////////////');
        $params = new stdClass();
        $params->numero = (int)$order;
        $params->tipo = 25;
        $result = $client->GetReturnOrdenByNumber($params);

        $json['scriptResp'] = "done";
        $json['resp'] = $result;
        $output = ob_get_contents();
        ob_end_clean();
        $json['output'] = $output;
        echo json_encode($json);
        return;
    }

    //          GUARDAR NUEVA DEVOLUCION           //
    if ($method == 'saveNewDevol') {

        $date = date('Y-m-d H:i:s');
        $devols = json_decode($_POST['devol'], true);
        $queryNext = " INSERT INTO gt_devols ( userDevol, fechaDevol, objDevol, statusDevol) ";
        $queryNext .= " VALUES ('" . $_POST['userDevol'] . "','" . $date . "','" . json_encode($_POST['devol']) . "','1') ";
        $resultNext = $c->query($queryNext);

        if ($resultNext) {

            /** DESACTIVAR LA PUBLICACION */
            foreach ($devols as $devol) {
                $wsdlUrl = 'http://10.238.26.69:9298/Service1.asmx?wsdl';
                $client = new SoapClient($wsdlUrl);

                error_log('//////////////////       DEVOL    ///////////////////////////////' .  print_r($devol, true));
                $string = '';
                foreach ($devol as $key => $value) {
                    if ($string == '') {
                        $string .= $key . ":" . $value;
                    } else {
                        $string .= "," . $key . ":" . $value;
                    }
                }
                error_log('//////////////////       DEVOLstring    ///////////////////////////////' .  print_r($string, true));
                $params = new stdClass();
                $params->detail = $string;
                $result = $client->SaveReturnDetail($params);
            }

            $json['scriptResp'] = "done";
            $json['status'] = "saved";
            $output = ob_get_contents();
            ob_end_clean();
            $json['output'] = $output;
            echo json_encode($json);
            return;
        } else {
            $json['scriptResp'] = "error";
            $json['q'] = $queryNext;
            $json['qer'] = $c->error;
            $output = ob_get_contents();
            ob_end_clean();
            $json['output'] = $output;
            echo json_encode($json);
            return;
        }
    }

    //          CONSULTAR RECEPCION         //
    if ($method == 'consultarReceps') {

        $order = $_POST['devolVal'];

        $wsdlUrl = 'http://10.238.26.69:9298/Service1.asmx?wsdl';
        $client = new SoapClient($wsdlUrl);

        error_log('//////////////////  ///////////////////////////////');
        $params = new stdClass();
        $params->numero = (int)$order;
        $params->tipo = 2;
        $result = $client->GetReturnOrdenByNumber($params);

        $json['scriptResp'] = "done";
        $json['resp'] = $result;
        $output = ob_get_contents();
        ob_end_clean();
        $json['output'] = $output;
        echo json_encode($json);
        return;
    }
 //          CONSULTAR RECEPCION   TMK      //
    if ($method == 'recepciontmk') {

        $order = $_POST['devolVal'];
		$carrito = $_POST['carrito'];

        $wsdlUrl = 'http://10.238.26.69:9298/Service1.asmx?wsdl';
        $client = new SoapClient($wsdlUrl);

        error_log('//////////////////  ///////////////////////////////');
        $params = new stdClass();
        $params->pedido = (int)$order;
		$params->carrito = (int)$carrito;
        //$params->tipo = 2;
        $result = $client->recepciontmk($params);

        $json['scriptResp'] = "done";
        $json['resp'] = $result;
        $output = ob_get_contents();
        ob_end_clean();
        $json['output'] = $output;
        echo json_encode($json);
        return;
    }
	//RECEPCION TMK TEST 
	if ($method == 'recepciontmkTEST') {

        $order = $_POST['devolVal'];
		$carrito = $_POST['carrito'];
		$json['resp'] = "ERROR";
		
		$sql = "EXECUTE JOIN_INV_TRAS_ING_TMK " . $order . " , " . $carrito;
        $pa1 = array();
        $op1 = array("scrollable" => SQLSRV_CURSOR_KEYSET);

        $re1 = sqlsrv_query($conexion, $sql, $pa1, $op1);
        if (sqlsrv_num_rows($re1) != 0) {
			$json['resp'] = "OK";
            while ($fila = sqlsrv_fetch_array($re1)) {
                $json['rows'][] = $fila;
            }
        }
		$json['sql'] = $sql;
        /*$wsdlUrl = 'http://10.238.26.69:9298/Service1.asmx?wsdl';
        $client = new SoapClient($wsdlUrl);
        error_log('//////////////////  ///////////////////////////////');
        $params = new stdClass();
        $params->pedido = (int)$order;
		$params->carrito = (int)$carrito;
        //$params->tipo = 2;
        $result = $client->recepciontmk($params);*/

        $json['scriptResp'] = "done";
        $output = ob_get_contents();
        ob_end_clean();
        $json['output'] = $output;
        echo json_encode($json);
        return;
    }

    //          GUARDAR NUEVA ORDEN DE RECEPCION           //
    if ($method == 'saveNewReceps') {

        $date = date('Y-m-d H:i:s');
        $devols = json_decode($_POST['devol'], true);
        $queryNext = " INSERT INTO gt_devols ( userDevol, fechaDevol, objDevol, statusDevol) ";
        $queryNext .= " VALUES ('" . $_POST['userDevol'] . "','" . $date . "','" . json_encode($_POST['devol']) . "','1') ";
        $resultNext = $c->query($queryNext);

        if ($resultNext) {

            /** DESACTIVAR LA PUBLICACION */
            foreach ($devols as $devol) {
                $wsdlUrl = 'http://10.238.26.69:9298/Service1.asmx?wsdl';
                $client = new SoapClient($wsdlUrl);
                error_log('//////////////////       DEVOL    ///////////////////////////////' .  print_r($devol, true));
                $string = '';
                foreach ($devol as $key => $value) {
                    if ($string == '') {
                        $string .= $key . ":" . $value;
                    } else {
                        $string .= "," . $key . ":" . $value;
                    }
                }
                echo "
                
                " . $string;
                error_log('//////////////////       DEVOLstring    ///////////////////////////////' .  print_r($string, true));
                $params = new stdClass();
                $params->detail = $string;
                $result = $client->SaveReturnDetail($params);
            }

            $json['scriptResp'] = "done";
            $json['status'] = "saved";
            $output = ob_get_contents();
            ob_end_clean();
            $json['output'] = $output;
            echo json_encode($json);
            return;
        } else {
            $json['scriptResp'] = "error";
            $json['q'] = $queryNext;
            $json['qer'] = $c->error;
            $output = ob_get_contents();
            ob_end_clean();
            $json['output'] = $output;
            echo json_encode($json);
            return;
        }
    }


 //          CONSULTAR PRODUCTO EN ORIGEN           //
    if ($method == 'OrigenProd') {
		
        $producto = $_POST['OrigProd'];
		$Origen = $_POST['Origen'];
		$TipoOrigen = $_POST['TipoOrg'];
		
		$bod = $_POST['bod'];
		
        $sql = "DECLARE @TIPO NVARCHAR(10) = '".$TipoOrigen."'
				DECLARE @ID NVARCHAR(1) = 'P'
				DECLARE @CODBARRAS NVARCHAR(25) = '".$producto."'
				DECLARE @O NVARCHAR(20) = '".$Origen."'
				DECLARE @BOD NVARCHAR(4) = '".$bod."'
				

				BEGIN
                
				
				IF @TIPO ='U' AND @ID = 'P' 
				  AND (SELECT SUM(CANTIDADARTICULOS) EX FROM JOIN_CAJAMASTER_2 AS A INNER JOIN
					(SELECT TOP(1) CODARTICULO, TALLA,COLOR FROM ARTICULOSLIN WHERE ( CODBARRAS = @CODBARRAS OR CODBARRAS2 = @CODBARRAS OR CODBARRAS3 = @CODBARRAS ) ) AS B
					 ON A.CODARTICULO = B.CODARTICULO
					AND A.TALLA = B.TALLA COLLATE Latin1_General_CS_AI AND A.COLOR = b.COLOR COLLATE Latin1_General_CS_AI
					INNER JOIN JOIN_UBICACIONES AS JU ON A.CODUBICACION = JU.IDUBICACION
					WHERE A.CODIGOBARRAS = '0000' AND A.CODUBICACION = @O AND JU.BODEGA = @BOD  ) >0
					BEGIN
					SELECT 'S' ESTADO
					END
					ELSE


				  IF @TIPO ='C' AND @ID = 'P' AND
				  (SELECT SUM(CANTIDADARTICULOS) EX FROM JOIN_CAJAMASTER_2 AS A INNER JOIN
				  (SELECT TOP(1) CODARTICULO, TALLA,COLOR FROM ARTICULOSLIN WHERE CODBARRAS = @CODBARRAS OR CODBARRAS2 = @CODBARRAS OR CODBARRAS3 = @CODBARRAS ) AS B ON A.CODARTICULO = B.CODARTICULO
					AND A.TALLA = B.TALLA COLLATE Latin1_General_CS_AI AND A.COLOR = b.COLOR COLLATE Latin1_General_CS_AI
					INNER JOIN JOIN_UBICACIONES AS JU ON A.CODUBICACION = JU.IDUBICACION
					WHERE A.CODIGOBARRAS =@O AND JU.BODEGA = @BOD   ) >0
				  BEGIN
					SELECT 'S' ESTADO
					END
					ELSE


				IF @TIPO ='U' AND @ID = 'C' AND
				(
					SELECT SUM(CANTIDADARTICULOS) EX FROM JOIN_CAJAMASTER_2 AS A 
					WHERE A.CODIGOBARRAS = @CODBARRAS   AND A.CODUBICACION = @O ) >0
				  BEGIN
					SELECT 'S' ESTADO
					END
					ELSE
					BEGIN
					SELECT 'N' ESTADO
					END
				  
					
				  END";
		
		//$sql = "SELECT TOP(1) NUMSERIE FROM ALBVENTACAB";
		$op1 = array("scrollable" => SQLSRV_CURSOR_KEYSET);
		$pa1 = array();
		$re1 = sqlsrv_query($conexion, $sql, $pa1, $op1);
        if ($re1) {
			$result = sqlsrv_fetch_array($re1);
            /** Recorrer el resultado */
            foreach($result as $devol) {
                $json['qer'] = $devol;
            }
			$json['q'] = $sql;
			//$json['qer'] = sqlsrv_fetch_array ($re1);
			$json['scriptResp'] = "done";
            $json['status'] = "saved";
            $output = ob_get_contents();
            ob_end_clean();
            $json['output'] = $output;
            echo json_encode($json);
            return;
        } else {
            $json['scriptResp'] = "done"; // ESTE DEBE SER VALOR "done" TAMBIEN PARA QUE APICALL TE FUNCIONE Y DIGA QUE PASA.
            $json['q'] = $sql; // este para que te salga en la pantalla el query que ejecutas a ver si un valor esta null
            $json['qer'] = sqlsrv_errors();
            $output = ob_get_contents();
            ob_end_clean();
            $json['output'] = $output;
            echo json_encode($json);
            return;
        }
    }
	
	
 //          CONSULTAR PRODUCTO EN ORIGEN  AJUSTE         //
    if ($method == 'OrigenProdaj') {
		
        $producto = $_POST['OrigProd'];
		$Origen = $_POST['Origen'];
		$TipoOrigen = $_POST['TipoOrg'];
		$ensa = $_POST['ensa'];
		$bod = $_POST['bod'];
		
        $sql = "DECLARE @TIPO NVARCHAR(10) = '".$TipoOrigen."'
				DECLARE @ID NVARCHAR(1) = 'P'
				DECLARE @CODBARRAS NVARCHAR(25) = '".$producto."'
				DECLARE @O NVARCHAR(20) = '".$Origen."'
				DECLARE @BOD NVARCHAR(4) = '".$bod."'
				DECLARE @TIPOAJUSTE NVARCHAR(10) = '".$ensa."'

				BEGIN
                IF @TIPOAJUSTE  = 'SALIDA' 
				BEGIN 
				IF @TIPO ='U' AND @ID = 'P' 
				  AND (SELECT SUM(CANTIDADARTICULOS) EX FROM JOIN_CAJAMASTER_2 AS A INNER JOIN
					(SELECT TOP(1) CODARTICULO, TALLA,COLOR FROM ARTICULOSLIN WHERE CODBARRAS = @CODBARRAS ) AS B
					 ON A.CODARTICULO = B.CODARTICULO
					AND A.TALLA = B.TALLA COLLATE Latin1_General_CS_AI AND A.COLOR = b.COLOR COLLATE Latin1_General_CS_AI
					INNER JOIN JOIN_UBICACIONES AS JU ON A.CODUBICACION = JU.IDUBICACION
					WHERE A.CODIGOBARRAS = '0000' AND A.CODUBICACION = @O AND JU.BODEGA = @BOD  ) >0
					BEGIN
					SELECT 'S' ESTADO
					END
					ELSE


				  IF @TIPO ='C' AND @ID = 'P' AND
				  (SELECT SUM(CANTIDADARTICULOS) EX FROM JOIN_CAJAMASTER_2 AS A INNER JOIN
				  (SELECT TOP(1) CODARTICULO, TALLA,COLOR FROM ARTICULOSLIN WHERE CODBARRAS = @CODBARRAS) AS B ON A.CODARTICULO = B.CODARTICULO
					AND A.TALLA = B.TALLA COLLATE Latin1_General_CS_AI AND A.COLOR = b.COLOR COLLATE Latin1_General_CS_AI
					INNER JOIN JOIN_UBICACIONES AS JU ON A.CODUBICACION = JU.IDUBICACION
					WHERE A.CODIGOBARRAS =@O AND JU.BODEGA = @BOD   ) >0
				  BEGIN
					SELECT 'S' ESTADO
					END
					ELSE


				IF @TIPO ='U' AND @ID = 'C' AND
				(
					SELECT SUM(CANTIDADARTICULOS) EX FROM JOIN_CAJAMASTER_2 AS A 
					WHERE A.CODIGOBARRAS = @CODBARRAS   AND A.CODUBICACION = @O ) >0
				  BEGIN
					SELECT 'S' ESTADO
					END
					ELSE
					BEGIN
					SELECT 'N' ESTADO
					END
				  
					END
				  END";
		
		//$sql = "SELECT TOP(1) NUMSERIE FROM ALBVENTACAB";
		$op1 = array("scrollable" => SQLSRV_CURSOR_KEYSET);
		$pa1 = array();
		$re1 = sqlsrv_query($conexion, $sql, $pa1, $op1);
        if ($re1) {
			$result = sqlsrv_fetch_array($re1);
            /** Recorrer el resultado */
            foreach($result as $devol) {
                $json['qer'] = $devol;
            }
			$json['q'] = $sql;
			//$json['qer'] = sqlsrv_fetch_array ($re1);
			$json['scriptResp'] = "done";
            $json['status'] = "saved";
            $output = ob_get_contents();
            ob_end_clean();
            $json['output'] = $output;
            echo json_encode($json);
            return;
        } else {
            $json['scriptResp'] = "done"; // ESTE DEBE SER VALOR "done" TAMBIEN PARA QUE APICALL TE FUNCIONE Y DIGA QUE PASA.
            $json['q'] = $sql; // este para que te salga en la pantalla el query que ejecutas a ver si un valor esta null
            $json['qer'] = sqlsrv_errors();
            $output = ob_get_contents();
            ob_end_clean();
            $json['output'] = $output;
            echo json_encode($json);
            return;
        }
    }
	
	//          CONSULTAR STOCK DE PRODCUTOS           //
    if ($method == 'StockProd') {
		
        $producto = $_POST['OrigProd'];
		$Origen = $_POST['Origen'];
		$TipoOrigen = $_POST['TipoOrg'];
		$bod = $_POST['bod'];
		
        $sql = "DECLARE @TIPO NVARCHAR(10) = '".$TipoOrigen."'
				DECLARE @ID NVARCHAR(1) = 'P'
				DECLARE @CODBARRAS NVARCHAR(25) = '".$producto."'
				DECLARE @O NVARCHAR(20) = '".$Origen."'
				DECLARE @BOD NVARCHAR(4) = '".$bod."'

				BEGIN

				IF @TIPO ='U' AND @ID = 'P' 
				  AND (SELECT SUM(CANTIDADARTICULOS) EX FROM JOIN_CAJAMASTER_2 AS A INNER JOIN
					(SELECT TOP(1) CODARTICULO, TALLA,COLOR FROM ARTICULOSLIN WHERE CODBARRAS = @CODBARRAS ) AS B
					 ON A.CODARTICULO = B.CODARTICULO
					AND A.TALLA = B.TALLA COLLATE Latin1_General_CS_AI AND A.COLOR = b.COLOR COLLATE Latin1_General_CS_AI
					INNER JOIN JOIN_UBICACIONES AS JU ON A.CODUBICACION = JU.IDUBICACION
					WHERE A.CODIGOBARRAS = '0000' AND A.CODUBICACION = @O AND JU.BODEGA = @BOD  ) >0
					BEGIN
					SELECT 'S' ESTADO
					END
					ELSE


				  IF @TIPO ='C' AND @ID = 'P' AND
				  (SELECT SUM(CANTIDADARTICULOS) EX FROM JOIN_CAJAMASTER_2 AS A INNER JOIN
				  (SELECT TOP(1) CODARTICULO, TALLA,COLOR FROM ARTICULOSLIN WHERE CODBARRAS = @CODBARRAS) AS B ON A.CODARTICULO = B.CODARTICULO
					AND A.TALLA = B.TALLA COLLATE Latin1_General_CS_AI AND A.COLOR = b.COLOR COLLATE Latin1_General_CS_AI
					INNER JOIN JOIN_UBICACIONES AS JU ON A.CODUBICACION = JU.IDUBICACION
					WHERE A.CODIGOBARRAS =@O AND JU.BODEGA = @BOD   ) >0
				  BEGIN
					SELECT 'S' ESTADO
					END
					ELSE


				IF @TIPO ='U' AND @ID = 'C' AND
				(
					SELECT SUM(CANTIDADARTICULOS)  )EX FROM JOIN_CAJAMASTER_2 AS A 
					WHERE A.CODIGOBARRAS = @CODBARRAS   AND A.CODUBICACION = @O ) >0
				  BEGIN
					SELECT 'S' ESTADO
					END
					ELSE
					BEGIN
					SELECT 'N' ESTADO
					END
				  

				  END";
		
		//$sql = "SELECT TOP(1) NUMSERIE FROM ALBVENTACAB";
		$op1 = array("scrollable" => SQLSRV_CURSOR_KEYSET);
		$pa1 = array();
		$re1 = sqlsrv_query($conexion, $sql, $pa1, $op1);
        if ($re1) {
			$result = sqlsrv_fetch_array($re1);
            /** Recorrer el resultado */
            foreach($result as $devol) {
                $json['qer'] = $devol;
            }
			$json['q'] = $sql;
			//$json['qer'] = sqlsrv_fetch_array ($re1);
			$json['scriptResp'] = "done";
            $json['status'] = "saved";
            $output = ob_get_contents();
            ob_end_clean();
            $json['output'] = $output;
            echo json_encode($json);
            return;
        } else {
            $json['scriptResp'] = "done"; // ESTE DEBE SER VALOR "done" TAMBIEN PARA QUE APICALL TE FUNCIONE Y DIGA QUE PASA.
            $json['q'] = $sql; // este para que te salga en la pantalla el query que ejecutas a ver si un valor esta null
            $json['qer'] = sqlsrv_errors();
            $output = ob_get_contents();
            ob_end_clean();
            $json['output'] = $output;
            echo json_encode($json);
            return;
        }
    }
    
	//          GUARDAR NUEVA REUBICACION DE PRODUCTOS         //
    if ($method == 'saveNewReub') {

        $date = date('Y-m-d H:i:s');
        $devols = json_decode($_POST['objReub'], true);
        $queryNext = " INSERT INTO gt_devols ( userDevol, fechaDevol, objDevol, statusDevol) ";
        $queryNext .= " VALUES ('" . $_POST['userReub'] . "','" . $date . "','REUB - " . json_encode($_POST['objReub']) . "','1') ";
        $resultNext = $c->query($queryNext);

        if ($resultNext) {

            $json['rowsUpds'] = [];


            /** DESACTIVAR LA PUBLICACION */
            foreach ($devols as $devol) {

                $sql = " EXECUTE JOIN_REUBICACIONES_AUXT '" . $devol['orig'] . "' , '" . $devol['dest'] . "', '" . $devol['prod'] . "', '" . $devol['totalUnidades'] . "', '" . $devol['tiporig']  . "-" . $devol['tipdest']  . "','P','" . $devol['bod'] . "'";
                $pa1 = array();
                $op1 = array("scrollable" => SQLSRV_CURSOR_KEYSET);
                $re1 = sqlsrv_query($conexion, $sql, $pa1, $op1);
                $json['quers'][] = $re1;
   
            }

           // $json['post'] = json_encode($_POST);
            $json['scriptResp'] = "done";
            $json['status'] = "saved";
            $output = ob_get_contents();
            ob_end_clean();
            $json['output'] = $output;
            echo json_encode($json);
            return;
        } else {
            $json['scriptResp'] = "error";
            $json['q'] = $queryNext;
            $json['qer'] = $c->error;
            $output = ob_get_contents();
            ob_end_clean();
            $json['output'] = $output;
            echo json_encode($json);
            return;
        }
    }

  //          GUARDAR AJUSTE DE INVENTARIO        //
    if ($method == 'guardarajuste') {

        $date = date('Y-m-d H:i:s');
        $devols = json_decode($_POST['objReub'], true);
        $queryNext = " INSERT INTO gt_devols ( userDevol, fechaDevol, objDevol, statusDevol) ";
        $queryNext .= " VALUES ('" . $_POST['userReub'] . "','" . $date . "','REUB - " . json_encode($_POST['objReub']) . "','1') ";
        $resultNext = $c->query($queryNext);

        if ($resultNext) {

            $json['rowsUpds'] = [];


            /** DESACTIVAR LA PUBLICACION */
            foreach ($devols as $devol) {

                $sql = " EXECUTE JOIN_AJUSTES_APP_SP '" . $devol['orig'] . "' , '" . $devol['dest'] . "', '" . $devol['prod'] . "', '" . $devol['totalUnidades'] . "', '" . $devol['tiporig']  . "-" . $devol['tipdest']  . "','P','" . $devol['bod'] . "','" . $devol['idtransaccion'] . "','" . $devol['idlinea'] . "'"   ;
                $pa1 = array();
                $op1 = array("scrollable" => SQLSRV_CURSOR_KEYSET);
                $re1 = sqlsrv_query($conexion, $sql, $pa1, $op1);
                $json['quers'][] = $re1;
   
            }

           // $json['post'] = json_encode($_POST);
            $json['scriptResp'] = "done";
            $json['status'] = "saved";
            $output = ob_get_contents();
            ob_end_clean();
            $json['output'] = $output;
            echo json_encode($json);
            return;
        } else {
            $json['scriptResp'] = "error";
            $json['q'] = $queryNext;
            $json['qer'] = $c->error;
            $output = ob_get_contents();
            ob_end_clean();
            $json['output'] = $output;
            echo json_encode($json);
            return;
        }
    }

    //          CONSULTAR TRASLADO         //
    if ($method == 'consultarTraslado') {

        $order = $_POST['trasladoVal'];
        $userId = $_POST['userId'];

        $wsdlUrl = 'http://10.238.26.69:9298/Service1.asmx?wsdl';
        $client = new SoapClient($wsdlUrl);


        $codArt = $_POST['codArt'];
        $talla = $_POST['talla'];
        $color = $_POST['color'];
        $suPedido = $_POST['suPedido'];

        $json['rows'] = [];

        $sql = "
                EXECUTE JOIN_INV_PREP_TRASLADOS  '" . $order . "' , '" . $userId . "'
        ";
        $pa1 = array();
        $op1 = array("scrollable" => SQLSRV_CURSOR_KEYSET);

        $re1 = sqlsrv_query($conexion, $sql, $pa1, $op1);
        if (sqlsrv_num_rows($re1) != 0) {
            while ($fila = sqlsrv_fetch_array($re1)) {
                $sqlref = "
                            SELECT AC.CODIGO_FABRICANTE 
                            FROM ARTICULOSCAMPOSLIBRES AS AC 
                            WHERE  AC.CODARTICULO = ".$fila['CODARTICULO'] . "
                    ";
                $pa1ref = array();
                $op1ref = array("scrollable" => SQLSRV_CURSOR_KEYSET);

                $re1ref = sqlsrv_query($conexion, $sqlref, $pa1ref, $op1ref);
                if (sqlsrv_num_rows($re1ref) != 0) {
                    while ($filaref = sqlsrv_fetch_array($re1ref)) {
                        $fila['CODIGO_FABRICANTE'] = $filaref['CODIGO_FABRICANTE'];
                    }
                }
                $params = explode('-', $fila['TODORECIBIDO']);
                $fila[25] = $params[1] ? $params[1] : 0;
                $json['rows'][] = $fila;
            }
        }

        if ($order == '300147') {
            $sql2 = "
                SELECT PC.NUMSERIE, PC.NUMPEDIDO, PC.SUPEDIDO, PL.NUMLIN, PL.CODARTICULO, A.DESCRIPCION, PL.REFERENCIA, PL.TALLA, PL.COLOR, PL.UNIDADESTOTAL, PL.CODALMACEN, 
                ( 
                    SELECT TOP(1)  B.PASILLO+'-'+A.CODUBICACION 
                    FROM JOIN_CAJAMASTER_2 AS A  
                    INNER JOIN JOIN_UBICACIONES As B ON A.CODUBICACION = B.IDUBICACION 
                    WHERE (A.CODARTICULO = PL.CODARTICULO) AND (A.TALLA = PL.TALLA COLLATE Latin1_General_CS_AI) AND (B.BODEGA = PL.CODALMACEN COLLATE Latin1_General_CS_AI) 
                ) PASILLO_UBICACION, PL.CODVENDEDOR, V.NOMVENDEDOR, D.DESCRIPCION AS DEPARTAMENTO, AC.PAIS_FABRICANTE AS PAIS, AC.CODIGO_FABRICANTE 
                FROM  
                PEDVENTACAB AS PC  
                INNER JOIN PEDVENTALIN AS PL ON (PC.NUMSERIE = PL.NUMSERIE) AND (PC.NUMPEDIDO = PL.NUMPEDIDO) 
                INNER JOIN ARTICULOS AS A ON (PL.CODARTICULO = A.CODARTICULO) 
                INNER JOIN ARTICULOSCAMPOSLIBRES AS AC ON (A.CODARTICULO = AC.CODARTICULO)
                LEFT JOIN VENDEDORES AS V ON (PL.CODVENDEDOR = V.CODVENDEDOR) 
                LEFT JOIN DEPARTAMENTO AS D ON (A.DPTO = D.NUMDPTO) 
                WHERE (PC.NUMSERIE = 'CVA') AND (PC.NUMPEDIDO = 434) 
                ORDER BY PL.NUMLIN ASC
            ";
            $pa12 = array();
            $op12 = array("scrollable" => SQLSRV_CURSOR_KEYSET);

            $re12 = sqlsrv_query($conexion, $sql2, $pa12, $op12);
            if (sqlsrv_num_rows($re12) != 0) {
                while ($fila = sqlsrv_fetch_array($re12)) {
                    $compCod = $fila['REFERENCIA'] . $fila['COLOR'] . $fila['TALLA'];
                    $fila['CODGEN'] = $compCod;
                    foreach ($json['rows'] as $key => $value) {
                        if ($fila['SUPEDIDO'] == $order) {
                            if ($value['CODBARRAS'] == $compCod) {
                                $json['rows'][$key]['UNIDADESTOTAL'] = $fila['UNIDADESTOTAL'];
                            }
                        }
                    }
                }
            }
        }

        $json['scriptResp'] = "done";
        $json['resp'] = $json['rows'];
        $json['sql'] = $sql;
        $json['params'] = $params;
        $output = ob_get_contents();
        ob_end_clean();
        $json['output'] = $output;
        echo json_encode($json);
        return;
    }
	
    //          GUARDAR NUEVA ORDEN DE RECEPCION           //
    if ($method == 'saveNewTraslado') {

        $date = date('Y-m-d H:i:s');
        $devols = json_decode($_POST['devol'], true);
        $queryNext = " INSERT INTO gt_devols ( userDevol, fechaDevol, objDevol, statusDevol) ";
        $queryNext .= " VALUES ('" . $_POST['userDevol'] . "','" . $date . "','" . json_encode($_POST['devol']) . "','1') ";
        $resultNext = $c->query($queryNext);

        if ($resultNext) {
			try{
				foreach ($devols as $devol) {
					$wsdlUrl = 'http://10.238.26.69:9298/Service1.asmx?wsdl';
					$client = new SoapClient($wsdlUrl);
					error_log('//////////////////       TRASLADO    ///////////////////////////////' .  print_r($devol, true));
					$string = '';
					foreach ($devol as $key => $value) {
						if ($string == '') {
							$string .= $key . ":" . $value;
						} else {
							$string .= "," . $key . ":" . $value;
						}
					}

					$sqlC = "
							UPDATE JOIN_CAJAMASTER_2 SET CODUBICACION = '00000' WHERE IDCAJA = '15788'
						";
					$pa1C = array();
					$op1C = array("scrollable" => SQLSRV_CURSOR_KEYSET);

					$re1C = sqlsrv_query($conexion, $sqlC, $pa1C, $op1C);
					
					if (sqlsrv_num_rows($re1C) != 0) {
						while ($filaC = sqlsrv_fetch_array($re1C)) {
							$json['rowsupdatedCaja'][] = $filaC;
						}
					}
					error_log('//////////////////       DEVOLstring    ///////////////////////////////' .  print_r($string, true));
					$params = new stdClass();
					$params->detail = $string;
					$result = $client->SaveReturnDetail($params);
				}

				$json['scriptResp'] = "done";
				$json['status'] = "saved";
				$output = ob_get_contents();
				ob_end_clean();
				$json['output'] = $output;
				echo json_encode($json);
				return;
			}catch(Exception $e){
				$json['scriptResp'] = "error";
				$json['error'] = $queryNext;
				$json['qer'] = "Error en el servicio";
				$output = ob_get_contents();
				ob_end_clean();
				$json['output'] = $output;
				echo json_encode($json);
				return;
			}
        } else {
			
            $json['scriptResp'] = "error";
            $json['q'] = $queryNext;
            $json['qer'] = $c->error;
            $output = ob_get_contents();
            ob_end_clean();
            $json['output'] = $output;
            echo json_encode($json);
            return;
        }
    }

    //          PREGUNTAMOS EL TOTAL DE PRODUCTOS EN ESA CAJA           //
    if ($method == 'totalProdsInBox') {

        $codigoArticulo = $_POST['codigoArticulo'];
        $talla = $_POST['talla'];
        $color = $_POST['color'];
        $codigoBarrasCaja = $_POST['codigoBarrasCaja'];
        /* 
        $codigoArticulo = 8362;
        $talla = '360';
        $color = '020';
        $codigoBarrasCaja = '20000669'; */

        $wsdlUrl = 'http://10.238.26.69:9298/Service1.asmx?wsdl';
        $client = new SoapClient($wsdlUrl);

        $params = new stdClass();
        $params->codigoArticulo = (int)$codigoArticulo;
        $params->talla = $talla;
        $params->color = $color;
        $params->codigoBarrasCaja = $codigoBarrasCaja;
        $result = $client->GetQuantityProductInMasterBox($params);

        $json['scriptResp'] = "done";
        $json['status'] = "gotback";
        $json['result'] = $result;
        $output = ob_get_contents();
        ob_end_clean();
        $json['output'] = $output;
        echo json_encode($json);
        return;
    }

    //          CONSULTAR CAJAMASTER CONTENIDO         //
    if ($method == 'consultarCajaMaster') {

        $cajaVal = $_POST['cajaVal'];
        $suPedido = $_POST['suPedido'];

        $json['rows'] = [];

        $sql = " 
        DECLARE @DOCUMENTO NVARCHAR(15) = '" . $suPedido . "'
        DECLARE @CAJAMASTER NVARCHAR(20) = '" . $cajaVal . "'
        DECLARE @ALMACEN NVARCHAR(4) =
        (
        SELECT  TOP(1) B.CODALMACEN
                                        FROM PEDVENTACAB  AS A INNER JOIN PEDVENTALIN AS B ON A.NUMSERIE = B.NUMSERIE AND A.NUMPEDIDO = B.NUMPEDIDO
                                        WHERE SUPEDIDO =@DOCUMENTO
                                        GROUP BY CODALMACEN
        
                                        )
        
        IF @ALMACEN = '20' BEGIN
        
        SELECT AA.CODIGOBARRAS,AA.CODARTICULO, AA.TALLA, AA.COLOR,AA.CODBARRAS , AA.CANTIDADARTICULOS  FROM (
        
                    SELECT A.CODIGOBARRAS, A.CODARTICULO, A.TALLA, A.COLOR, AL.CODBARRAS, A.CANTIDADARTICULOS- ISNULL(DSC.DESPACHADOS,0) CANTIDADARTICULOS
                                            FROM JOIN_CAJAMASTER_2 AS  A LEFT JOIN ARTICULOSLIN AS AL ON A.CODARTICULO = AL.CODARTICULO 
                                            AND A.TALLA = AL.TALLA  COLLATE Latin1_General_CS_AI
                                            AND A.COLOR = AL.COLOR COLLATE Latin1_General_CS_AI
                                            LEFT JOIN JOIN_UBICACIONES AS B ON A.CODUBICACION = B.IDUBICACION
                                            LEFT JOIN (
                                        SELECT CAJAMASTER, CODIGOARTICULO, TALLA,COLOR,SUM(CANTIDADDEVUELTA )DESPACHADOS FROM JOIN_DEVOLUCIONES
                                        WHERE CAJAMASTER = @CAJAMASTER
                                        AND MODULO = 22 AND CONVERT(DATE,FECHA,3)>='2020-12-21'
                                        
                                        GROUP BY CAJAMASTER, CODIGOARTICULO, TALLA,COLOR) AS DSC ON A.CODIGOBARRAS = DSC.CAJAMASTER AND A.CODARTICULO = DSC.CODIGOARTICULO
                                        AND A.TALLA = DSC.TALLA AND A.COLOR = DSC.COLOR
                                        WHERE A.CODIGOBARRAS =@CAJAMASTER
                                        AND  B.BODEGA = (SELECT B.CODALMACEN
                                        FROM PEDVENTACAB  AS A INNER JOIN PEDVENTALIN AS B ON A.NUMSERIE = B.NUMSERIE AND A.NUMPEDIDO = B.NUMPEDIDO
                                        WHERE SUPEDIDO =@DOCUMENTO
                                        GROUP BY CODALMACEN) COLLATE Latin1_General_CS_AI
                                        ) AS AA
                                        WHERE AA.CANTIDADARTICULOS>0
        END
        ELSE BEGIN

		IF @ALMACEN = '21' BEGIN
        
        SELECT AA.CODIGOBARRAS,AA.CODARTICULO, AA.TALLA, AA.COLOR,AA.CODBARRAS , AA.CANTIDADARTICULOS  FROM (
        
                    SELECT A.CODIGOBARRAS, A.CODARTICULO, A.TALLA, A.COLOR, AL.CODBARRAS, A.CANTIDADARTICULOS- ISNULL(DSC.DESPACHADOS,0) CANTIDADARTICULOS
                                            FROM JOIN_CAJAMASTER_2 AS  A LEFT JOIN ARTICULOSLIN AS AL ON A.CODARTICULO = AL.CODARTICULO 
                                            AND A.TALLA = AL.TALLA  COLLATE Latin1_General_CS_AI
                                            AND A.COLOR = AL.COLOR COLLATE Latin1_General_CS_AI
                                            LEFT JOIN JOIN_UBICACIONES AS B ON A.CODUBICACION = B.IDUBICACION
                                            LEFT JOIN (
                                        SELECT CAJAMASTER, CODIGOARTICULO, TALLA,COLOR,SUM(CANTIDADDEVUELTA )DESPACHADOS FROM JOIN_DEVOLUCIONES
                                        WHERE CAJAMASTER = @CAJAMASTER
                                        AND MODULO = 22 AND CONVERT(DATE,FECHA,3)>='2020-12-28'
                                        
                                        GROUP BY CAJAMASTER, CODIGOARTICULO, TALLA,COLOR) AS DSC ON A.CODIGOBARRAS = DSC.CAJAMASTER AND A.CODARTICULO = DSC.CODIGOARTICULO
                                        AND A.TALLA = DSC.TALLA AND A.COLOR = DSC.COLOR
                                        WHERE A.CODIGOBARRAS =@CAJAMASTER
                                        AND  B.BODEGA = (SELECT B.CODALMACEN
                                        FROM PEDVENTACAB  AS A INNER JOIN PEDVENTALIN AS B ON A.NUMSERIE = B.NUMSERIE AND A.NUMPEDIDO = B.NUMPEDIDO
                                        WHERE SUPEDIDO =@DOCUMENTO
                                        GROUP BY CODALMACEN) COLLATE Latin1_General_CS_AI
                                        ) AS AA
                                        WHERE AA.CANTIDADARTICULOS>0
        END
        ELSE BEGIN

        
        SELECT AA.CODIGOBARRAS,AA.CODARTICULO, AA.TALLA, AA.COLOR,AA.CODBARRAS , AA.CANTIDADARTICULOS  FROM (
        
                    SELECT A.CODIGOBARRAS, A.CODARTICULO, A.TALLA, A.COLOR, AL.CODBARRAS, A.CANTIDADARTICULOS- ISNULL(DSC.DESPACHADOS,0) CANTIDADARTICULOS
                                            FROM JOIN_CAJAMASTER_2 AS  A LEFT JOIN ARTICULOSLIN AS AL ON A.CODARTICULO = AL.CODARTICULO 
                                            AND A.TALLA = AL.TALLA  COLLATE Latin1_General_CS_AI
                                            AND A.COLOR = AL.COLOR COLLATE Latin1_General_CS_AI
                                            LEFT JOIN JOIN_UBICACIONES AS B ON A.CODUBICACION = B.IDUBICACION
                                            LEFT JOIN (
                                        SELECT CAJAMASTER, CODIGOARTICULO, TALLA,COLOR,SUM(CANTIDADDEVUELTA )DESPACHADOS FROM JOIN_DEVOLUCIONES
                                        WHERE CAJAMASTER = @CAJAMASTER
                                        AND MODULO = 22
                                        GROUP BY CAJAMASTER, CODIGOARTICULO, TALLA,COLOR) AS DSC ON A.CODIGOBARRAS = DSC.CAJAMASTER AND A.CODARTICULO = DSC.CODIGOARTICULO
                                        AND A.TALLA = DSC.TALLA AND A.COLOR = DSC.COLOR
                                        WHERE A.CODIGOBARRAS =@CAJAMASTER
                                        AND  B.BODEGA = (SELECT B.CODALMACEN
                                        FROM PEDVENTACAB  AS A INNER JOIN PEDVENTALIN AS B ON A.NUMSERIE = B.NUMSERIE AND A.NUMPEDIDO = B.NUMPEDIDO
                                        WHERE SUPEDIDO =@DOCUMENTO
                                        GROUP BY CODALMACEN) COLLATE Latin1_General_CS_AI
                                        ) AS AA
                                        WHERE AA.CANTIDADARTICULOS>0
        
        END
		END
        ";
        /* $sql = "
            SELECT A.CODIGOBARRAS, A.CODARTICULO, A.TALLA, A.COLOR, AL.CODBARRAS, A.CANTIDADARTICULOS
            FROM JOIN_CAJAMASTER_2 AS  A LEFT JOIN ARTICULOSLIN AS AL ON A.CODARTICULO = AL.CODARTICULO 
            AND A.TALLA = AL.TALLA  COLLATE Latin1_General_CS_AI
            AND A.COLOR = AL.COLOR COLLATE Latin1_General_CS_AI
            WHERE CODIGOBARRAS = '" . $cajaVal . "'
        "; */
        $pa1 = array();
        $op1 = array("scrollable" => SQLSRV_CURSOR_KEYSET);

        $re1 = sqlsrv_query($conexion, $sql, $pa1, $op1);
        if (sqlsrv_num_rows($re1) != 0) {
            while ($fila = sqlsrv_fetch_array($re1)) {
                $json['rows'][] = $fila;
            }
        }

        $json['scriptResp'] = "done";
        $json['status'] = "gotback";
        $json['result'] = $result;
        $output = ob_get_contents();
        ob_end_clean();
        $json['output'] = $output;
        echo json_encode($json);
        return;
    }

    //          CONSULTAR CAJAMASTER CONTENIDO         //
    if ($method == 'consultarCajaMasterIF') {

        $cajaVal = $_POST['cajaVal'];
        $suPedido = $_POST['suPedido'];

        $json['rows'] = [];

        $sql = "
        SELECT   AA.CODIGOBARRAS,AA.CODARTICULO, AA.TALLA, AA.COLOR,AA.CODBARRAS , AA.CANTIDADARTICULOS, AA.CODUBICACION  FROM (

            SELECT A.CODUBICACION,  A.CODIGOBARRAS, A.CODARTICULO, A.TALLA, A.COLOR, AL.CODBARRAS, A.CANTIDADARTICULOS- ISNULL(DSC.DESPACHADOS,0) CANTIDADARTICULOS
                                    FROM JOIN_CAJAMASTER_2 AS  A LEFT JOIN ARTICULOSLIN AS AL ON A.CODARTICULO = AL.CODARTICULO 
                                    AND A.TALLA = AL.TALLA  COLLATE Latin1_General_CS_AI
                                    AND A.COLOR = AL.COLOR COLLATE Latin1_General_CS_AI
                                    LEFT JOIN JOIN_UBICACIONES AS B ON A.CODUBICACION = B.IDUBICACION
                                    LEFT JOIN (
                                SELECT CAJAMASTER, CODIGOARTICULO, TALLA,COLOR,SUM(CANTIDADDEVUELTA )DESPACHADOS FROM JOIN_DEVOLUCIONES
                                   WHERE CAJAMASTER = '" . $cajaVal . "'
                                AND MODULO = 22
                                GROUP BY CAJAMASTER, CODIGOARTICULO, TALLA,COLOR) AS DSC ON A.CODIGOBARRAS = DSC.CAJAMASTER AND A.CODARTICULO = DSC.CODIGOARTICULO
                                AND A.TALLA = DSC.TALLA AND A.COLOR = DSC.COLOR
                                WHERE A.CODIGOBARRAS = '" . $cajaVal . "'
                                AND  B.BODEGA ='" . $suPedido . "'
                                ) AS AA
                                WHERE AA.CANTIDADARTICULOS>0
                                ";

        $pa1 = array();
        $op1 = array("scrollable" => SQLSRV_CURSOR_KEYSET);

        $re1 = sqlsrv_query($conexion, $sql, $pa1, $op1);
        if (sqlsrv_num_rows($re1) != 0) {
            while ($fila = sqlsrv_fetch_array($re1)) {
                $json['rows'][] = $fila;
            }
        }

        $json['scriptResp'] = "done";
        $json['status'] = "gotback";
        $json['result'] = $result;
        $output = ob_get_contents();
        ob_end_clean();
        $json['output'] = $output;
        echo json_encode($json);
        return;
    }

    //          CONSULTAR UBICACION PRODUCTO         //
    if ($method == 'consultarUbics') {

        $codArt = $_POST['codArt'];
        $talla = $_POST['talla'];
        $color = $_POST['color'];
        $suPedido = $_POST['suPedido'];

        $json['rows'] = [];

        $sql = "
                  DECLARE @CODARTICULO  INT =  '" . $codArt . "'
DECLARE @TALLA NVARCHAR(20) = '" . $talla . "'
DECLARE @COLOR NVARCHAR(20) = '" . $color . "'
DECLARE @PEDIDO NVARCHAR(40) = '" . $suPedido . "'
DECLARE @BODEGA NVARCHAR(4) = (SELECT B.CODALMACEN
                FROM PEDVENTACAB  AS A INNER JOIN PEDVENTALIN AS B ON A.NUMSERIE = B.NUMSERIE AND A.NUMPEDIDO = B.NUMPEDIDO
                WHERE SUPEDIDO = @PEDIDO AND B.UNIDADESTOTAL > 0
                GROUP BY CODALMACEN )

SELECT CODIGOBARRAS CAJAMASTER, A.UB UBICACION , SUM(ISNULL(A.CN,0)-ISNULL(B.CN2,0)) STOCK FROM (
SELECT  CODIGOBARRAS, A.CODUBICACION ,ISNULL(SUM(CANTIDADARTICULOS),0)CN  ,
CAST(B.IDUBICACION AS NVARCHAR(50))+'-'+ B.CODUBICACION AS UB
FROM JOIN_CAJAMASTER_2 AS  A INNER JOIN JOIN_UBICACIONES AS B ON A.CODUBICACION = B.IDUBICACION
WHERE CODARTICULO = @CODARTICULO AND TALLA = @TALLA AND COLOR = @COLOR
AND CODIGOBARRAS <> '0000' AND B.BODEGA = @BODEGA
GROUP BY CODIGOBARRAS, A.CODUBICACION , B.IDUBICACION ,B.CODUBICACION
) AS A
LEFT JOIN
------
(
SELECT   CAJAMASTER,  UBICACION,  ISNULL(SUm(CANTIDADDEVUELTA),0)CN2 FROM JOIN_DEVOLUCIONES AS A
WHERE CODIGOARTICULO = @CODARTICULO AND TALLA = @TALLA AND COLOR = @COLOR AND 
CONVERT(DATE,FECHA,3)>=(SELECT ULTIMAREG FROM JOIN_ULTIMAREG WHERE CODALMACEN = @BODEGA )
AND MODULO IN (22,220) AND CAJAMASTER<>'0000'
AND dbo.JOIN_OBTENERBODEGASUPEDIDO (A.DOCUMENTO) = @BODEGA
GROUP BY CAJAMASTER,UBICACION 
) AS B ON A.CODIGOBARRAS = B.CAJAMASTER
GROUP BY CODIGOBARRAS, A.CODUBICACION  , A.UB
HAVING SUM(ISNULL(A.CN,0)-ISNULL(B.CN2,0))>0
UNION ALL
-----
SELECT A.CODIGOBARRAS,A.UB CODUBICACION, SUM(ISNULL(A.CN,0)-ISNULL(B.CN2,0)) STOCK
FROM (
SELECT  CODIGOBARRAS, A.CODUBICACION ,ISNULL(SUM(CANTIDADARTICULOS),0)CN 
,CAST(B.IDUBICACION AS NVARCHAR(50))+'-'+ B.CODUBICACION AS UB
FROM JOIN_CAJAMASTER_2 A INNER JOIN JOIN_UBICACIONES AS B ON A.CODUBICACION = B.IDUBICACION
WHERE CODARTICULO = @CODARTICULO AND TALLA = @TALLA AND COLOR = @COLOR
AND CODIGOBARRAS = '0000' AND B.BODEGA =@BODEGA
GROUP BY CODIGOBARRAS, B.IDUBICACION, A.CODUBICACION , B.CODUBICACION
) AS A LEFT JOIN (
SELECT   CAJAMASTER,UBICACION, ISNULL( SUm(CANTIDADDEVUELTA),0)CN2 FROM JOIN_DEVOLUCIONES AS A
WHERE CODIGOARTICULO = @CODARTICULO AND TALLA = @TALLA AND COLOR = @COLOR AND 
CONVERT(DATE,FECHA,3)>=(SELECT ULTIMAREG FROM JOIN_ULTIMAREG WHERE CODALMACEN = @BODEGA )
AND MODULO IN (22,220) AND CAJAMASTER ='0000'
AND dbo.JOIN_OBTENERBODEGASUPEDIDO (A.DOCUMENTO) = @BODEGA
GROUP BY CAJAMASTER,UBICACION ) AS B ON A.CODIGOBARRAS = B.CAJAMASTER AND A.CODUBICACION = B.UBICACION
GROUP BY CODIGOBARRAS, A.CODUBICACION , A.UB
HAVING  SUM( ISNULL(A.CN,0)- ISNULL(B.CN2,0))>0
        ";
        /* $sql = "
            SELECT  CODIGOBARRAS CAJAMASTER , M.CODUBICACION +'-'+B.PASILLO+'-'+B.IDESTANTERIA+'-'+B.COLUMNA  UBICACION
            FROM JOIN_CAJAMASTER_2 AS M INNER JOIN JOIN_UBICACIONES AS B ON M.CODUBICACION = B.IDUBICACION
            WHERE CODARTICULO = '" . $codArt . "' AND TALLA = '" . $talla . "' ANd COLOR = '" . $color . "' 
        "; */
        $pa1 = array();
        $op1 = array("scrollable" => SQLSRV_CURSOR_KEYSET);

        $re1 = sqlsrv_query($conexion, $sql, $pa1, $op1);
        if (sqlsrv_num_rows($re1) != 0) {
            while ($fila = sqlsrv_fetch_array($re1)) {
                $json['rows'][] = $fila;
            }
        }

        $json['scriptResp'] = "done";
        $json['status'] = "gotback";
        $output = ob_get_contents();
        ob_end_clean();
        $json['q'] = $sql;
        $json['output'] = $output;
        echo json_encode($json);
        return;
    }
    
	//          CONSULTAR UBICACION PRODUCTO  PICKING       //
    if ($method == 'consultarUbicsp') {

        $codArt = $_POST['codArt'];
        $talla = $_POST['talla'];
        $color = $_POST['color'];
        $suPedido = $_POST['suPedido'];

        $json['rows'] = [];

        $sql = "
                  DECLARE @CODARTICULO  INT =  '" . $codArt . "'
DECLARE @TALLA NVARCHAR(20) = '" . $talla . "'
DECLARE @COLOR NVARCHAR(20) = '" . $color . "'
DECLARE @PEDIDO NVARCHAR(40) = '" . $suPedido . "'
DECLARE @BODEGA NVARCHAR(4) = (SELECT B.CODALMACEN
                FROM PEDVENTACAB  AS A INNER JOIN PEDVENTALIN AS B ON A.NUMSERIE = B.NUMSERIE AND A.NUMPEDIDO = B.NUMPEDIDO
                WHERE SUPEDIDO = @PEDIDO AND B.UNIDADESTOTAL > 0
                GROUP BY CODALMACEN )

SELECT CODIGOBARRAS CAJAMASTER, A.CODUBICACION UBICACION , SUM(ISNULL(A.CN,0)-ISNULL(B.CN2,0)) STOCK FROM (
SELECT  CODIGOBARRAS, A.CODUBICACION ,ISNULL(SUM(CANTIDADARTICULOS),0)CN 
FROM JOIN_CAJAMASTER_2 AS  A INNER JOIN JOIN_UBICACIONES AS B ON A.CODUBICACION = B.IDUBICACION
WHERE CODARTICULO = @CODARTICULO AND TALLA = @TALLA AND COLOR = @COLOR
AND CODIGOBARRAS <> '0000' AND B.BODEGA = @BODEGA
GROUP BY CODIGOBARRAS, A.CODUBICACION 
) AS A
LEFT JOIN
------
(
SELECT   CAJAMASTER,UBICACION,  ISNULL(SUm(CANTIDADDEVUELTA),0)CN2 FROM JOIN_DEVOLUCIONES AS A
WHERE CODIGOARTICULO = @CODARTICULO AND TALLA = @TALLA AND COLOR = @COLOR AND 
CONVERT(DATE,FECHA,3)>=(SELECT ULTIMAREG FROM JOIN_ULTIMAREG WHERE CODALMACEN = @BODEGA )
AND MODULO IN (22,220) AND CAJAMASTER<>'0000'
AND dbo.JOIN_OBTENERBODEGASUPEDIDO (A.DOCUMENTO) = @BODEGA
GROUP BY CAJAMASTER,UBICACION 
) AS B ON A.CODIGOBARRAS = B.CAJAMASTER
GROUP BY CODIGOBARRAS, A.CODUBICACION
HAVING SUM(ISNULL(A.CN,0)-ISNULL(B.CN2,0))>0
UNION ALL
-----
SELECT A.CODIGOBARRAS, A.CODUBICACION, SUM(ISNULL(A.CN,0)-ISNULL(B.CN2,0)) STOCK
FROM (
SELECT  CODIGOBARRAS, A.CODUBICACION ,ISNULL(SUM(CANTIDADARTICULOS),0)CN 
FROM JOIN_CAJAMASTER_2 A INNER JOIN JOIN_UBICACIONES AS B ON A.CODUBICACION = B.IDUBICACION
WHERE CODARTICULO = @CODARTICULO AND TALLA = @TALLA AND COLOR = @COLOR
AND CODIGOBARRAS = '0000' AND B.BODEGA =@BODEGA
GROUP BY CODIGOBARRAS, A.CODUBICACION 
) AS A LEFT JOIN (
SELECT   CAJAMASTER,UBICACION, ISNULL( SUm(CANTIDADDEVUELTA),0)CN2 FROM JOIN_DEVOLUCIONES AS A
WHERE CODIGOARTICULO = @CODARTICULO AND TALLA = @TALLA AND COLOR = @COLOR AND 
CONVERT(DATE,FECHA,3)>=(SELECT ULTIMAREG FROM JOIN_ULTIMAREG WHERE CODALMACEN = @BODEGA )
AND MODULO IN (22,220) AND CAJAMASTER ='0000'
AND dbo.JOIN_OBTENERBODEGASUPEDIDO (A.DOCUMENTO) = @BODEGA
GROUP BY CAJAMASTER,UBICACION ) AS B ON A.CODIGOBARRAS = B.CAJAMASTER AND A.CODUBICACION = B.UBICACION
GROUP BY CODIGOBARRAS, A.CODUBICACION
HAVING  SUM( ISNULL(A.CN,0)- ISNULL(B.CN2,0))>0
        ";
        /* $sql = "
            SELECT  CODIGOBARRAS CAJAMASTER , M.CODUBICACION +'-'+B.PASILLO+'-'+B.IDESTANTERIA+'-'+B.COLUMNA  UBICACION
            FROM JOIN_CAJAMASTER_2 AS M INNER JOIN JOIN_UBICACIONES AS B ON M.CODUBICACION = B.IDUBICACION
            WHERE CODARTICULO = '" . $codArt . "' AND TALLA = '" . $talla . "' ANd COLOR = '" . $color . "' 
        "; */
        $pa1 = array();
        $op1 = array("scrollable" => SQLSRV_CURSOR_KEYSET);

        $re1 = sqlsrv_query($conexion, $sql, $pa1, $op1);
        if (sqlsrv_num_rows($re1) != 0) {
            while ($fila = sqlsrv_fetch_array($re1)) {
                $json['rows'][] = $fila;
            }
        }

        $json['scriptResp'] = "done";
        $json['status'] = "gotback";
        $output = ob_get_contents();
        ob_end_clean();
        $json['q'] = $sql;
        $json['output'] = $output;
        echo json_encode($json);
        return;
    }
	
	  //          CONSULTAR UBICACION PRODUCTO  PICKING   X FAC    //
    if ($method == 'consultarUbicxf') {

        $codarticulo = $_POST['codarticulo'];
        $talla = $_POST['talla'];
        $color = $_POST['color'];
        $suPedido = $_POST['suPedido'];

        $json['rows'] = [];

        $sql = "
			DECLARE @CODARTICULO  INT =  '" . $codarticulo . "'
			DECLARE @TALLA NVARCHAR(20) = '" . $talla . "'
			DECLARE @COLOR NVARCHAR(20) = '" . $color . "'

			SELECT * FROM (
			SELECT   A.CAJAMASTER, A.CODUBICACION, UNIDADES - ISNULL(SALIDAS,0) STOCK ,A.UBICACION,A.MODELO, A.DESCRIPCION,  A.CODARTICULO, A.TALLA, A.COLOR, A.CODBARRAS
			  
			  FROM  
			  ( SELECT  B.BODEGA,  A.CODIGOBARRAS CAJAMASTER, A.CODUBICACION UBICACION, A.CODARTICULO, AR.REFPROVEEDOR MODELO, AR.DESCRIPCION, 
				A.TALLA, A.COLOR, ARL.CODBARRAS, A.CANTIDADARTICULOS AS UNIDADES, B.CODUBICACION 
				FROM JOIN_CAJAMASTER_2 AS A  
				LEFT JOIN JOIN_UBICACIONES AS B ON CONVERT(VARCHAR, A.CODUBICACION) = CONVERT(VARCHAR, B.IDUBICACION) 
				LEFT JOIN ARTICULOS AS AR ON (A.CODARTICULO = AR.CODARTICULO) 
				LEFT JOIN ARTICULOSLIN AS ARL ON (A.CODARTICULO = ARL.CODARTICULO) AND (A.TALLA = ARL.TALLA COLLATE Latin1_General_CS_AI) AND (A.COLOR = ARl.COLOR COLLATE Latin1_General_CS_AI) 
				WHERE (B.BODEGA = '31') AND A.CODIGOBARRAS <>'0000'
			  ) AS A LEFT JOIN 
			  ( SELECT CAJAMASTER, CODIGOARTICULO, TALLA,COLOR, SUM(SALIDAS) SALIDAS 
				FROM JOIN_REPORTE_STOCK_BOG_TB AS AA WHERE BODEGA = '31' 
				AND CAJAMASTER <>'0000'
				GROUP BY CAJAMASTER, CODIGOARTICULO, TALLA,COLOR
			  ) AS B ON (A.CODARTICULO = B.CODIGOARTICULO) AND (A.TALLA = B.TALLA) 
			  AND (A.COLOR = B.COLOR) AND (A.CAJAMASTER = B.CAJAMASTER) WHERE 
			  (UNIDADES - ISNULL(SALIDAS,0) <>0) 
			UNION ALL
			SELECT   A.CAJAMASTER, A.CODUBICACION , ( ISNULl(UNIDADES,0) - ISNULL(SALIDAS,0))- ISNULL(C.REST,0) STOCK ,A.UBICACION,A.MODELO, A.DESCRIPCION,  A.CODARTICULO, A.TALLA, A.COLOR, A.CODBARRAS
			 
			  FROM  
			  ( 
			  	SELECT  B.BODEGA,  A.CODIGOBARRAS CAJAMASTER, A.CODUBICACION UBICACION, A.CODARTICULO, AR.REFPROVEEDOR MODELO, AR.DESCRIPCION, 
			  	A.TALLA, A.COLOR, ARL.CODBARRAS, A.CANTIDADARTICULOS AS UNIDADES, B.CODUBICACION 
			  	FROM JOIN_CAJAMASTER_2 AS A  
			  	LEFT JOIN JOIN_UBICACIONES AS B ON CONVERT(VARCHAR, A.CODUBICACION) = CONVERT(VARCHAR, B.IDUBICACION) 
			  	LEFT JOIN ARTICULOS AS AR ON (A.CODARTICULO = AR.CODARTICULO) 
				LEFT JOIN JOIN_ULTIMAREG R ON R.CODALMACEN = B.BODEGA
			  	LEFT JOIN ARTICULOSLIN AS ARL ON (A.CODARTICULO = ARL.CODARTICULO) AND (A.TALLA = ARL.TALLA COLLATE Latin1_General_CS_AI) AND (A.COLOR = ARl.COLOR COLLATE Latin1_General_CS_AI) 
			  	WHERE (B.BODEGA = '31') AND A.CODIGOBARRAS ='0000' AND A.FECHAREGISTRO >= R.ULTIMAREG
			  ) AS A LEFT JOIN 
			  ( SELECT CAJAMASTER,UBICACION, CODIGOARTICULO, TALLA,COLOR, SUM(SALIDAS) SALIDAS 
			  	FROM JOIN_REPORTE_STOCK_BOG_UB AS AA WHERE BODEGA = '31' 
				GROUP BY CAJAMASTER,UBICACION, CODIGOARTICULO, TALLA,COLOR
			  ) AS B ON (A.CODARTICULO = B.CODIGOARTICULO) AND (A.TALLA = B.TALLA) 
			  AND (A.COLOR = B.COLOR) AND (A.CAJAMASTER = B.CAJAMASTER)
			  AND  A.UBICACION = B.UBICACION
			  LEFT JOIN 
			   (SELECT '0000' CAJAMASTER , A.CODARTICULO, A.TALLA,A.COLOR, A.CODUBICACION, SUM(ISNULL(A.UNIDADES,0)) REST 
				FROm JOIN_AUX_PICKING_FACTURAS AS A INNER JOIN JOIN_UBICACIONES AS B ON A.CODUBICACION = B.IDUBICACION 
			  	LEFT JOIN JOIN_ULTIMAREG R ON R.CODALMACEN = B.BODEGA
				WHERE A.FECHA >= R.ULTIMAREG
				GROUP BY A.CODARTICULO, A.TALLA,A.COLOR, A.CODUBICACION) AS C ON  
				(A.CODARTICULO = C.CODARTICULO) AND (A.TALLA = C.TALLA)  
		      AND (A.COLOR = C.COLOR) AND (A.CAJAMASTER = C.CAJAMASTER) 
			  AND  A.UBICACION = C.CODUBICACION 
			  WHERE 
			  (( ISNULl(UNIDADES,0) - ISNULL(SALIDAS,0)) <> 0)  AND A.CODARTICULO = @CODARTICULO AND A.COLOR = @COLOR AND A.TALLA = @TALLA
			) H WHERE H.STOCK > 0   
        ";
        /* $sql = "
            SELECT  CODIGOBARRAS CAJAMASTER , M.CODUBICACION +'-'+B.PASILLO+'-'+B.IDESTANTERIA+'-'+B.COLUMNA  UBICACION
            FROM JOIN_CAJAMASTER_2 AS M INNER JOIN JOIN_UBICACIONES AS B ON M.CODUBICACION = B.IDUBICACION
            WHERE CODARTICULO = '" . $codArt . "' AND TALLA = '" . $talla . "' ANd COLOR = '" . $color . "' 
        "; */
        $pa1 = array();
        $op1 = array("scrollable" => SQLSRV_CURSOR_KEYSET);

        $re1 = sqlsrv_query($conexion, $sql, $pa1, $op1);
        if (sqlsrv_num_rows($re1) != 0) {
            while ($fila = sqlsrv_fetch_array($re1)) {
                $json['rows'][] = $fila;
            }
        }

        $json['scriptResp'] = "done";
        $json['status'] = "gotback";
        $output = ob_get_contents();
        ob_end_clean();
        $json['q'] = $sql;
        $json['output'] = $output;
        echo json_encode($json);
		//sqlsrv_close($conexion);
        return;
    }
	
	//Consultamos si existe stock //
	if ($method == 'consultastockxf') {

        $codubic = $_POST['codubic'];
		$codbarras = $_POST['codbarras'];
		$tipo = $_POST['tipo'];
		$json['status'] = "noprod";
		if($tipo == 'U' ){ $sql = " 
DECLARE @UBICACION NVARCHAR(50) =  '" . $codubic . "'
DECLARE @CAJAMASTER NVARCHAR(50) =   '0000'
DECLARE @CODBARRAS NVARCHAR(50) =  '". $codbarras . "' 
DECLARE @BODEGA NVARCHAR(4) 
DECLARE @REGULARIZACION DATE
DECLARE @CODARTICULO NVARCHAR(10)
DECLARE @COLOR NVARCHAR(10)
DECLARE @TALLA NVARCHAR(10)


SET @BODEGA = (SELECT BODEGA FROM JOIN_UBICACIONES WHERE IDUBICACION = @UBICACION)
SET @REGULARIZACION = ( SELECT TOP(1) ULTIMAREG FROM JOIN_ULTIMAREG WHERE CODALMACEN = @BODEGA )
SET @CODARTICULO = (SELECT TOP 1(SELECT CODARTICULO FROM ARTICULOSLIN WHERE CODBARRAS = @CODBARRAS
					UNION ALL SELECT CODARTICULO FROM ARTICULOSLIN WHERE CODBARRAS2 = @CODBARRAS
					UNION ALL SELECT CODARTICULO FROM ARTICULOSLIN WHERE CODBARRAS3 = @CODBARRAS) AS A)

SET @COLOR = (SELECT TOP 1(SELECT COLOR FROM ARTICULOSLIN WHERE CODBARRAS = @CODBARRAS
					UNION ALL SELECT COLOR FROM ARTICULOSLIN WHERE CODBARRAS2 = @CODBARRAS
					UNION ALL SELECT COLOR FROM ARTICULOSLIN WHERE CODBARRAS3 = @CODBARRAS) AS B)

SET @TALLA = (SELECT TOP 1(SELECT TALLA FROM ARTICULOSLIN WHERE CODBARRAS = @CODBARRAS
					UNION ALL SELECT TALLA FROM ARTICULOSLIN WHERE CODBARRAS2 = @CODBARRAS
					UNION ALL SELECT TALLA FROM ARTICULOSLIN WHERE CODBARRAS3 = @CODBARRAS) AS C)

SELECT * FROM ( SELECT CODARTICULO, COLOR, TALLA, SUM(INGRESOS) INGRESOS, SUM(SALIDAS) SALIDAS, 
(SUM(INGRESOS)-SUM(SALIDAS)) STOCK
FROM 
(	 
			 SELECT CODUBICACION, CODIGOBARRAS CAJAMASTER,CODARTICULO, COLOR, TALLA, CANTIDADARTICULOS INGRESOS, 0 SALIDAS
			 FROM JOIN_CAJAMASTER_2 
			 WHERE CODUBICACION=@UBICACION AND CODIGOBARRAS=@CAJAMASTER AND CODARTICULO=@CODARTICULO AND COLOR=@COLOR AND TALLA=@TALLA
			 AND CONVERT(DATE,FECHAREGISTRO,3) >= @REGULARIZACION
			 
			 UNION ALL

			 SELECT UBICACION CODUBICACION, CAJAMASTER,CODIGOARTICULO CODARTICULO, COLOR, TALLA, 0 INGRESOS,CANTIDADDEVUELTA SALIDAS
			 FROM JOIN_DEVOLUCIONES
			 WHERE UBICACION=@UBICACION AND CAJAMASTER=@CAJAMASTER AND CODIGOARTICULO=@CODARTICULO AND COLOR=@COLOR AND TALLA=@TALLA
					AND MODULO IN (22) AND CONVERT(DATE,FECHA,3) >= @REGULARIZACION


			UNION ALL

			SELECT CODUBICACION UBICACION, '0000' CAJAMASTER, CODARTICULO, COLOR, TALLA, 0 INGRESOS, UNIDADES SALIDAS
			FROM JOIN_AUX_PICKING_FACTURAS
			WHERE CODARTICULO=@CODARTICULO AND COLOR=@COLOR AND TALLA=@TALLA AND CODUBICACION=@UBICACION
			AND CONVERT(DATE,FECHA,3) >= @REGULARIZACION

		) AS C 
		GROUP BY CODARTICULO, COLOR, TALLA ) AS D WHERE D.STOCK > 0				";
		}else{
			$sql = " SELECT IDUBICACION FROM JOIN_UBICACIONES WHERE IDUBICACION = '" . $codbarras . "' AND BODEGA = '" . $cajamaster . "'  ";
		}
         
		
        $pa1 = [];
        $op1 = array("scrollable" => SQLSRV_CURSOR_KEYSET);
        $re1 = sqlsrv_query($conexion, $sql, $pa1, $op1);
        if ($re1) {
            if (sqlsrv_num_rows($re1) != 0) {
                while ($fila = sqlsrv_fetch_array($re1)) {
                    $json['rows'][] = $fila;
                    $json['status'] = "gotProd";
                }
            }
        }
        $json['scriptResp'] = "done";
        $json['sql'] = $sql;
        $output = ob_get_contents();
        ob_end_clean();
        $json['output'] = $output;
        echo json_encode($json);
		//sqlsrv_close($conexion);
        return;
    }
	
    //          CONSULTAR RECEPCION DE TRASLADO        //
    if ($method == 'consultarRecepTrasl') {

        $devolVal = $_POST['devolVal'];
        $carritoVal = $_POST['carritoVal'];

        $json['rows'] = [];

        $sql = "    EXEC JOIN_INV_RECEPTRASLADOS '" . $devolVal . "' , '" . $carritoVal . "'        ";
        $pa1 = array();
        $op1 = array("scrollable" => SQLSRV_CURSOR_KEYSET);

        $re1 = sqlsrv_query($conexion, $sql, $pa1, $op1);
        if (sqlsrv_num_rows($re1) != 0) {
            while ($fila = sqlsrv_fetch_array($re1)) {
                $json['rows'][] = $fila;
            }
        }

        $json['scriptResp'] = "done";
        $json['status'] = "gotback";
        $output = ob_get_contents();
        ob_end_clean();
        $json['q'] = $sql;
        $json['output'] = $output;
        echo json_encode($json);
		//sqlsrv_close($conexion);
        return;
    }

    //          GUARDAR NUEVA ORDEN DE RECEPCION   DE TRASLADO        //
    if ($method == 'saveNewRecepsTrals') {

        $date = date('Y-m-d H:i:s');
        $devols = json_decode($_POST['devol'], true);
        $queryNext = " INSERT INTO gt_devols ( userDevol, fechaDevol, objDevol, statusDevol) ";
        $queryNext .= " VALUES ('" . $_POST['userDevol'] . "','" . $date . "','" . json_encode($_POST['devol']) . "','1') ";
        $resultNext = $c->query($queryNext);

        if ($resultNext) {

            /** DESACTIVAR LA PUBLICACION */
            foreach ($devols as $devol) {

                $json['rowsUpds'] = [];
                $json['rowsQs'] = [];
                if ($devol['cajamas'] != '0000') {
                    $cajaTextAnd = " AND CAJAMASTER = '" . $devol['cajamas'] . "'";
                }

                $sql = "
                            UPDATE JOIN_DEVOLUCIONES SET RECIBODESTINO = '" . $devol['returnquantity'] . "'
                            WHERE CODIGOARTICULO = '" . $devol['codarticulo'] . "' AND TALLA = '" . $devol['talla'] . "' AND COLOR = '" . $devol['color'] . "'  AND MODULO = '22' AND DOCUMENTO = '" . $devol['doc'] . "' " . $cajaTextAnd . "
                ";
                $pa1 = array();
                $op1 = array("scrollable" => SQLSRV_CURSOR_KEYSET);

                $re1 = sqlsrv_query($conexion, $sql, $pa1, $op1);

                $json['rowsUpds'][] = "UPDATED " . $devol['codarticulo'];
                $json['rowsQs'][] = $sql;

                /** INCOVAMOS EL WS */
                $wsdlUrl = 'http://10.238.26.69:9298/Service1.asmx?wsdl';
                $client = new SoapClient($wsdlUrl);

                error_log('//////////////////       DEVOL    ///////////////////////////////' .  print_r($devol, true));
                $string = '';
                foreach ($devol as $key => $value) {
                    if ($string == '') {
                        $string .= $key . ":" . $value;
                    } else {
                        $string .= "," . $key . ":" . $value;
                    }
                }
                error_log('//////////////////       DEVOLstring    ///////////////////////////////' .  print_r($string, true));
                $params = new stdClass();
                $params->detail = $string;
                $result = $client->SaveReturnDetail($params);
            }

            $json['scriptResp'] = "done";
            $json['status'] = "saved";
            $output = ob_get_contents();
            ob_end_clean();
            $json['output'] = $output;
            echo json_encode($json);
			//sqlsrv_close($conexion);
            return;
        } else {
            $json['scriptResp'] = "error";
            $json['q'] = $queryNext;
            $json['qer'] = $c->error;
            $output = ob_get_contents();
            ob_end_clean();
            $json['output'] = $output;
            echo json_encode($json);
            return;
        }
    }

    //          CONSULTAR CAJAMASTER TRASLADO         //
    if ($method == 'consultarCajaMasterTrasl') {

        $cajaVal = $_POST['cajaVal'];
        $doc = $_POST['supedido'];

        $json['rows'] = [];

        $sql = "
            SELECT * FROM JOIN_DEVOLUCIONES WHERE CAJAMASTER = '" . $cajaVal . "' AND MODULO IN ( '220' , '22' )  AND DOCUMENTO = '" . $doc . "' AND CANTIDADDEVUELTA > 0
        ";
        $pa1 = array();
        $op1 = array("scrollable" => SQLSRV_CURSOR_KEYSET);

        $re1 = sqlsrv_query($conexion, $sql, $pa1, $op1);
        if (sqlsrv_num_rows($re1) != 0) {
            while ($fila = sqlsrv_fetch_array($re1)) {
                $json['rows'][] = $fila;
            }
        }

        $json['scriptResp'] = "done";
        $json['status'] = "gotback";
        $json['result'] = $result;
        $output = ob_get_contents();
        ob_end_clean();
        $json['output'] = $output;
        $json['q'] = $sql;
        echo json_encode($json);
		//sqlsrv_close($conexion);
        return;
    }

    //          GUARDAR NUEVA REUBICACION DE CAJA MASTER         //
    if ($method == 'saveNewReubCaja') {

        $date = date('Y-m-d H:i:s');
        $devols = json_decode($_POST['objReubCaja'], true);
        $queryNext = " INSERT INTO gt_devols ( userDevol, fechaDevol, objDevol, statusDevol) ";
        $queryNext .= " VALUES ('" . $_POST['userReub'] . "','" . $date . "','REUBCAJA - " . json_encode($_POST['objReubCaja']) . "','1') ";
        $resultNext = $c->query($queryNext);


        if ($resultNext) {

            $json['rowsUpds'] = [];
            $json['rowsparams'] = [];

            /** DESACTIVAR LA PUBLICACION */
            foreach ($devols as $devol) {

               /* $wsdlUrl = 'http://10.238.26.69:9298/Service1.asmx?wsdl';
                $client = new SoapClient($wsdlUrl);
                $params = new stdClass();

                $sql = "
                    SELECT  TOP(1)CODIGOBARRAS  FROM JOIN_CAJAMASTER_2
                    WHERE CODIGOBARRAS = '" . $devol['prod'] . "'
                    AND CODUBICACION = '" . $devol['orig'] . "'
                    ";
                $pa1 = array();
                $op1 = array("scrollable" => SQLSRV_CURSOR_KEYSET);
                $re1 = sqlsrv_query($conexion, $sql, $pa1, $op1);
                $i = 0;
                if (sqlsrv_num_rows($re1) != 0) {
                    while ($fila = sqlsrv_fetch_array($re1)) {
                        if ($i == 3) {
                            break;
                        }
                        $json['rows'][] = $fila;
                        $i++;
                    }}

                    $params->barCodeBoxMasterOrigin = $devol['prod'];
                    $params->ubicacionOrigin = $devol['orig'];
                    $params->ubicacionDestiny = $devol['dest'];

                    $result = $client->CreateReubicacionBoxMaster($params);
                    $json['rowsUpds'][] = $result;
                    $json['rowsparams'][] = $params;
                } else {
                    $json['rowErr'][] = $devol['prod'] . ' - ' . $devol['orig'] . ' - ' . $devol['dest'];
                }*/
				$sql = " EXECUTE JOIN_REUBICACIONES_AUXT '" . $devol['orig'] . "' , '" . $devol['dest'] . "', '" . $devol['prod'] . "', '0', 'U-U','C','10'  ";
                $pa1 = array();
                $op1 = array("scrollable" => SQLSRV_CURSOR_KEYSET);
                $re1 = sqlsrv_query($conexion, $sql, $pa1, $op1);
                $json['quers'][] = $re1;
				
            }

            $json['scriptResp'] = "done";
            $json['status'] = "saved";
            $output = ob_get_contents();
            ob_end_clean();
            $json['output'] = $output;
            echo json_encode($json);
			//sqlsrv_close($conexion);
            return;
        } else {
            $json['scriptResp'] = "error";
            $json['q'] = $queryNext;
            $json['qer'] = $c->error;
            $output = ob_get_contents();
            ob_end_clean();
            $json['output'] = $output;
            echo json_encode($json);
			//sqlsrv_close($conexion);
            return;
        }
    }

    //          CONSULTAR LISTADO DE PICKING      //
    if ($method == 'consultarRecepTrasl') {

        $devolVal = $_POST['devolVal'];
        $carritoVal = $_POST['carritoVal'];

        $json['rows'] = [];

        $sql = "    EXEC JOIN_INV_RECEPTRASLADOS '" . $devolVal . "' , '" . $carritoVal . "'        ";
        $pa1 = array();
        $op1 = array("scrollable" => SQLSRV_CURSOR_KEYSET);

        $re1 = sqlsrv_query($conexion, $sql, $pa1, $op1);
        if (sqlsrv_num_rows($re1) != 0) {
            while ($fila = sqlsrv_fetch_array($re1)) {
                $json['rows'][] = $fila;
            }
        }

        $json['scriptResp'] = "done";
        $json['status'] = "gotback";
        $output = ob_get_contents();
        ob_end_clean();
        $json['q'] = $sql;
        $json['output'] = $output;
        echo json_encode($json);
		//sqlsrv_close($conexion);
        return;
    }

    //          CONSULTAR RECEPCION         //
    if ($method == 'consultarPicking') {

        $userId = $_POST['userId'];

        /*$filename = 'assets/isCall.json';
        if (file_exists($filename)) {
            sleep(15);
            return;
        } else {
            file_put_contents($filename, "{'val':'yes'}");
        }*/

        $wsdlUrl = 'http://10.238.26.69:9298/Service1.asmx?wsdl';
        $client = new SoapClient($wsdlUrl);

        $params = new stdClass();
        $params->user = $userId;
        $result = $client->GetPickingDetail($params);
        unlink($filename);

        $json['scriptResp'] = "done";
        $json['resp'] = $result;
        $output = ob_get_contents();
        ob_end_clean();
        $json['output'] = $output;
        echo json_encode($json);
        return;
    }
   //          CONSULTAR PICKIN POR ID PICKING         //
    if ($method == 'consultarPickingg') {

        $userId = $_POST['userId'];
		$idpicking = $_POST['idpicking'];

        $wsdlUrl = 'http://10.238.26.69:9298/Service1.asmx?wsdl';
        $client = new SoapClient($wsdlUrl);

        $params = new stdClass();
        $params->user = $userId;
		$params->idpicking =  $idpicking;
        $result = $client->GetPickingDetaill($params);
        unlink($filename);
		
		$pedidoEcom = (explode("600",$idpicking));
		//ACTUALIZAR ESTADO DEL PEDIDO EN ECOMMERCE //
		$seriePEd = $pedidoEcom[0];
		$numeroPed = $pedidoEcom[1];

		if($seriePEd == 'PZAF'){
			
			$data['getIdPed']=$numeroPed;
			$data['getIdEst']=25;
			//$data['IdRastreo']=$idpicking;
			
			$tuCurl = curl_init(); 
			curl_setopt($tuCurl, CURLOPT_URL, "https://agora.com.gt/tta/api.php?meth=actualizarPed"); 
			curl_setopt($tuCurl, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($tuCurl, CURLOPT_POSTFIELDS, $data); 
			curl_exec($tuCurl); 
			if(!curl_errno($tuCurl)){
				$info = curl_getinfo($tuCurl);
			//echo 'Tiempo :' . $info['total_time'] . ' en ejecutar: ' . $info['url'];
			} else {
				echo 'Curl error: ' . curl_error($tuCurl);
			}
		}

        $json['scriptResp'] = "done";
        $json['resp'] = $result;
        $output = ob_get_contents();
        ob_end_clean();
        $json['output'] = $output;
        echo json_encode($json);
        return;
    }
	 //          CONSULTAR PACKING         //
    if ($method == 'consultarPacking') {

        $userId = $_POST['userId'];
		$idpicking = $_POST['idpicking'];

        $wsdlUrl = 'http://10.238.26.69:9298/Service1.asmx?wsdl';
        $client = new SoapClient($wsdlUrl);

        $params = new stdClass();
        $params->user = $userId;
		$params->idpicking =  $idpicking;
        $result = $client->GetPackingDetail($params);
        unlink($filename);

        $json['scriptResp'] = "done";
        $json['resp'] = $result;
        $output = ob_get_contents();
        ob_end_clean();
        $json['output'] = $output;
        echo json_encode($json);
        return;
		
    }
	
	//CONSULTA LISTA DE TRANSPORTISTAS
	if($method == 'getCurriers'){
		
		$variable = $_POST['data'];
		$json['scriptResp2'] = $variable;
		
		$sql = "EXECUTE JOIN_INV__GET_COURIER";
		$pa1 = array();
		$op1 = array("scrollable" => SQLSRV_CURSOR_KEYSET);
		$re1 = sqlsrv_prepare($conexion, $sql, $pa1);
		$result = sqlsrv_execute($re1);
		//$data =sqlsrv_fetch_array($re1);
		
		//RETURN //
		$json['scriptResp'] = "done";
		
		if($result){
			$json['status'] = "OK";
			while($data =sqlsrv_fetch_array($re1)){
				$json['result'][] = $data;
			}
		}else{
			$json['status'] = "NoOk";
		}
		//$json['data'] = $data;
		$output = ob_get_contents();
		ob_end_clean();
		$json['output'] = $output;
		echo json_encode($json);
		return;
		
		
	}
	
	//GUARDAR LISTA DE GUIAS CON DELIVERY
	if($method == 'saveNewGuiaDelivery'){
		
		$IdUser = $_POST['userId'];
		$ArrayGuias = json_decode($_POST['guiasData']);
		$IdCurrier = $_POST['currierId'];
		
		$json['status'] = 'ERROR';
		$json['data'] = $ArrayGuias;
		
		foreach($ArrayGuias as $GuiaDatos){
			
			//$json['guia'] = $GuiaDatos->guia;
			
			$sql = "EXECUTE JOIN_INV_ENVIO_INSERT '".$GuiaDatos->guia."', ".$IdUser.", ".$IdCurrier;
			$pa1 = array();
			$op1 = array("scrollable" => SQLSRV_CURSOR_KEYSET);
			$re1 = sqlsrv_prepare($conexion, $sql, $pa1);
			$result = sqlsrv_execute($re1);
			
			$json['sql'] = $sql;
			
			if($result){
				$json['status'] = 'OK';
			}
			
		}
		$json['scriptResp'] = "done";
		$output = ob_get_contents();
		ob_end_clean();
		$json['output'] = $output;
		echo json_encode($json);
		return;
		
	}
	
	//VALIDAR UBICACIONES MASIVO//
	if($method == 'valUbics'){
		
		$origen = $_POST['OrgCod'];
		$destino = $_POST['desCod'];
		$json['valid'] = 'ERROR';
		
		$sql = "EXECUTE JOIN_INV_REU_GET ".$origen.", ".$destino;
		$pa1 = array();
		//$op1 = array("scrollable" => SQLSRV_CURSOR_KEYSET);
		$re1 = sqlsrv_prepare($conexion, $sql, $pa1);
		$result = sqlsrv_execute($re1);
		
		if($result){
			
			while($data =sqlsrv_fetch_array($re1)){
				
				$json['valid'] = $data['RESPUESTA'];
				$json['msg'] = $data['MENSAJE'];
				array_push($guiasPitadas,$GuiaID);
			}	
		}
		
		$json['scriptResp'] = "done";
		$output = ob_get_contents();
		ob_end_clean();
		$json['output'] = $output;
		echo json_encode($json);
		return;
	}
	
	//GUARDAR REUBICACION MASIVA UBICACION//
	if($method == 'saveNewReubicMAsivo'){
		
		$OrgCod = $_POST['orgCod'];
		$DetCod = $_POST['desCod'];
		$userID = $_POST['userCod'];
		
		$json['status'] = 'ERROR';
		
		$sql = "EXECUTE JOIN_INV_ENVIO_INSERT '".$GuiaDatos->guia."', ".$IdUser.", ".$IdCurrier;
		$pa1 = array();
		$op1 = array("scrollable" => SQLSRV_CURSOR_KEYSET);
		$re1 = sqlsrv_prepare($conexion, $sql, $pa1);
		$result = sqlsrv_execute($re1);
		
		if($result){
			
			$json['status'] = 'OK';
		}
		
		$json['scriptResp'] = "done";
		$output = ob_get_contents();
		ob_end_clean();
		$json['output'] = $output;
		echo json_encode($json);
		return;
		
	}
	
	//CONSULTAR VALIDAR GUIA//
	if($method == 'validarGuia'){
			
		$IDUser = '';
		$GuiaID = '';
		
		if(!ISSET($_POST['UsuerID'])){
			
			$IDUser = $_GET['UsuerID'];
		}else{
			$IDUser = $_POST['UsuerID'];
		}
		
		if(!ISSET($_POST['NumGuia'])){
			
			$GuiaID = $_GET['NumGuia'];
		}else{
			$GuiaID = $_POST['NumGuia'];
		}
		
		$sql = "EXECUTE JOIN_INV_ENVIO_GET ".$IDUser.",'".$GuiaID."'";
		
		$re1 = sqlsrv_prepare($conexion, $sql, array());
		$result = sqlsrv_execute($re1);
		//$data =sqlsrv_fetch_array($re1)
		//RETURN //
		$json['query'] = $sql;
		$json['scriptResp'] = "done";
		
		if($result){
			$json['status'] = "OK";
			if(in_array($GuiaID,$guiasPitadas)){
				
				$json['result'] = "F";
				
			}else{
				
				while($data =sqlsrv_fetch_array($re1)){
					$json['result'] = $data['ESTADO'];
					array_push($guiasPitadas,$GuiaID);
				}
			}
			/*
			$pedidoEcom = (explode("600",$idpicking));
			//ACTUALIZAR ESTADO DEL PEDIDO EN ECOMMERCE //
			$seriePEd = $pedidoEcom[0];
			$numeroPed = $pedidoEcom[1];

			if($seriePEd == 'PZAF'){
				
				$data['getIdPed']=$numeroPed;
				$data['getIdEst']=25;
				//$data['IdRastreo']=$idpicking;
				
				$tuCurl = curl_init(); 
				curl_setopt($tuCurl, CURLOPT_URL, "https://agora.com.gt/tta/api.php?meth=actualizarPed"); 
				curl_setopt($tuCurl, CURLOPT_RETURNTRANSFER, 1);
				curl_setopt($tuCurl, CURLOPT_POSTFIELDS, $data); 
				curl_exec($tuCurl); 
				if(!curl_errno($tuCurl)){
					$info = curl_getinfo($tuCurl);
				//echo 'Tiempo :' . $info['total_time'] . ' en ejecutar: ' . $info['url'];
				} else {
					echo 'Curl error: ' . curl_error($tuCurl);
				}
			}*/
			
		}else{
			
			$json['status'] = "ERROR";
		}
		
		$output = ob_get_contents();
		ob_end_clean();
		$json['output'] = $output;
		echo json_encode($json);
		return;
	
	}
	//CONSULTAR DATOS DE GUIA//
	if($method == 'consultarenvio'){
		
		$IDUser = $_POST['userId'];
		$idGuia = $_POST['idguia'];
		
		$sql = "EXECUTE JOIN_INV_ENVIO_GET ".$IDUser.",'".$idGuia."'";
		//$sql = "EXECUTE JOIN_INV_ENVIO_GET 1 ,'GI-0000070864'";
		$pa1 = array();
		$op1 = array("scrollable" => SQLSRV_CURSOR_KEYSET);
		//CONEXION A SQLSERVER//
		//$re1 = sqlsrv_query($conexion, $sql, $pa1, $op1);
		
		$re1 = sqlsrv_prepare($conexion, $sql, $pa1);
		$result = sqlsrv_execute($re1);
		$data =sqlsrv_fetch_array($re1);
		
		$validar = sqlsrv_num_rows($re1);
		/*
		if (sqlsrv_num_rows($re1) != 0) {
			$json['reslst'] = $re1;
            while ($fila = sqlsrv_fetch_array($re1)) {
                $json['rows'][] = $fila;
            }
        }*/
		$json['ques'] = $sql;
		$json['rows'] = $data;
		
		//RETURN //
		$json['scriptResp'] = "done";
		
		if($result){
			$json['status'] = "ok";
		}else{
			$json['status'] = "NoOk";
		}
		
		$output = ob_get_contents();
		ob_end_clean();
		$json['output'] = $output;
		echo json_encode($json);
		return;
		
	}
	
	//ACTUALIZAR DATOS DE GUIA//
	if($method == 'updateEnvio'){
		
		$IDUser = $_POST['userId'];
		$idGuia = $_POST['idguia'];
		
		$sql = "EXECUTE JOIN_INV_ENVIO_UPDATE ".$IDUser.",'".$idGuia."'";
		//$sql = "EXECUTE JOIN_INV_ENVIO_GET 1 ,'GI-0000070864'";
		$pa1 = array();
		$op1 = array("scrollable" => SQLSRV_CURSOR_KEYSET);
		//CONEXION A SQLSERVER//
		//$re1 = sqlsrv_query($conexion, $sql, $pa1, $op1);
		
		$re1 = sqlsrv_prepare($conexion, $sql, $pa1);
		$result = sqlsrv_execute($re1);
		//$data =sqlsrv_fetch_array($re1);
		/*
		if (sqlsrv_num_rows($re1) != 0) {
			$json['reslst'] = $re1;
            while ($fila = sqlsrv_fetch_array($re1)) {
                $json['rows'][] = $fila;
            }
        }*/
		$json['ques'] = $sql;
		$json['result'] = $result;
		
		//RETURN //
		$json['scriptResp'] = "done";
		$json['status'] = "saved";
		$output = ob_get_contents();
		ob_end_clean();
		$json['output'] = $output;
		echo json_encode($json);
		return;
	
		
	}
	 //          CONSULTAR PACKING         //
    if ($method == 'consultarpackingemb') {

        $userId = $_POST['userId'];
		$idpicking = $_POST['idpicking'];

        /*$filename = 'assets/isCall.json';
        if (file_exists($filename)) {
            sleep(15);
            return;
        } else {
            file_put_contents($filename, "{'val':'yes'}");
        }*/

        $wsdlUrl = 'http://10.238.26.69:9298/Service1.asmx?wsdl';
        $client = new SoapClient($wsdlUrl);

        $params = new stdClass();
        $params->user = $userId;
		$params->idpicking =  $idpicking;
        $result = $client->GetPackingGuia($params);
        unlink($filename);

        $json['scriptResp'] = "done";
        $json['resp'] = $result;
        $output = ob_get_contents();
        ob_end_clean();
        $json['output'] = $output;
        echo json_encode($json);
        return;
    }
    //          GUARDAR NUEVA ORDEN DE RECEPCION           //
    if ($method == 'saveNewPicking') {

        $date = date('Y-m-d H:i:s');
        $devols = json_decode($_POST['devol'], true);
        $queryNext = " INSERT INTO gt_devols ( userDevol, fechaDevol, objDevol, statusDevol) ";
        $queryNext .= " VALUES ('" . $_POST['userDevol'] . "','" . $date . "',' PICKING - " . json_encode($_POST['devol']) . "','1') ";
		
		//CONEXION A MYSQL//
        $resultNext = $c->query($queryNext);

        if ($resultNext) {

            /** DESACTIVAR LA PUBLICACION */
            foreach ($devols as $devol) {
                /* $wsdlUrl = 'http://10.238.26.69:9298/Service1.asmx?wsdl';
                $client = new SoapClient($wsdlUrl);

                error_log('//////////////////       DEVOL    ///////////////////////////////' .  print_r($devol, true));
                $string = '';
                foreach ($devol as $key => $value) {
                    if ($string == '') {
                        $string .= $key . ":" . $value;
                    } else {
                        $string .= "," . $key . ":" . $value;
                    }
                }
                error_log('//////////////////       DEVOLstring    ///////////////////////////////' .  print_r($string, true));
                $params = new stdClass();
                $params->detail = $string;
                $result = $client->SaveReturnDetail($params); */
                if ($devol['carrito'] == '0000') {
                    /* EXECUTE JOIN_POS_PEDIDDOS_PEPARADOS_NG @USER INT , @SUPEDIDO NVARCHAR(10) */
                    $sql = "
                        EXECUTE JOIN_POS_PEDIDDOS_PEPARADOS_NG '" . $devol['usuario'] . "', '" . $devol['supedido'] . "' 
                    ";
                } else {
                    $sql = "
                                EXECUTE JOIN_POS_PEDIDDOS_PEPARADOS '" . $devol['usuario'] . "', '" . $devol['supedido'] . "' , '" . $devol['numlin'] . "' , '" . $devol['unidades'] . "' , '" . $devol['carrito'] . "' 
                        ";
                }

                $pa1 = array();
                $op1 = array("scrollable" => SQLSRV_CURSOR_KEYSET);

                $re1 = sqlsrv_query($conexion, $sql, $pa1, $op1);
                $json['ques'][] = $sql;
                $json['reslst'][] = $re1;
            }

            $json['scriptResp'] = "done";
            $json['status'] = "saved";
            $output = ob_get_contents();
            ob_end_clean();
            $json['output'] = $output;
            echo json_encode($json);
            return;
        } else {
            $json['scriptResp'] = "error";
            $json['q'] = $queryNext;
            $json['qer'] = $c->error;
            $output = ob_get_contents();
            ob_end_clean();
            $json['output'] = $output;
            echo json_encode($json);
            return;
        }
    }
	
	 //          GUARDAR NUEVA ORDEN DE RECEPCION           //
    if ($method == 'saveNewPickingf') {

        $date = date('Y-m-d H:i:s');
        $devols = json_decode($_POST['devol'], true);
        $queryNext = " INSERT INTO gt_devols ( userDevol, fechaDevol, objDevol, statusDevol) ";
        $queryNext .= " VALUES ('" . $_POST['userDevol'] . "','" . $date . "',' PICKING - " . json_encode($_POST['devol']) . "','1') ";
        $resultNext = $c->query($queryNext);
		
		$idPedido = '';
		
        if ($resultNext) {

            /** DESACTIVAR LA PUBLICACION */
            foreach ($devols as $devol) {
               
                if ($devol['carrito'] == '0000') {
                 
                    $sql = "
                        EXECUTE JOIN_POS_PEDIDDOS_PEPARADOS_NG '" . $devol['usuario'] . "', '" . $devol['supedido'] . "' 
                    ";
                } else {
                    $sql = "
                                EXECUTE JOIN_POS_FACTURAS_PEPARADOS '" . $devol['usuario'] . "', '" . $devol['supedido'] . "' , '" . $devol['numlin'] . "' , '" . $devol['unidades'] . "' , '" . $devol['carrito'] . "' , '" . $devol['codarticulo'] . "' , '" . $devol['talla'] . "' , '" . $devol['color'] . "' , '" . $devol['idtransaccion'] . "' , '" . $devol['idlinea'] . "'  , '" . $devol['ubicacion'] . "' , '" . $devol['codalmacen'] . "' 
                        ";
                }
				$idPedido = $devol['supedido'];
                $pa1 = array();
                $op1 = array("scrollable" => SQLSRV_CURSOR_KEYSET);

                $re1 = sqlsrv_query($conexion, $sql, $pa1, $op1);
                $json['ques'][] = $sql;
                $json['reslst'][] = $re1;
            }
	
            $json['scriptResp'] = "done";
            $json['status'] = "saved";
            $output = ob_get_contents();
            ob_end_clean();
            $json['output'] = $output;
            echo json_encode($json);
            return;
        } else {
            $json['scriptResp'] = "error";
            $json['q'] = $queryNext;
            $json['qer'] = $c->error;
            $output = ob_get_contents();
            ob_end_clean();
            $json['output'] = $output;
            echo json_encode($json);
            return;
        }
    }
	 //         GUARDAR PACKING        //
    if ($method == 'guardarpacking') {

        $date = date('Y-m-d H:i:s');
        $devols = json_decode($_POST['devol'], true);
        $queryNext = " INSERT INTO gt_devols ( userDevol, fechaDevol, objDevol, statusDevol) ";
        $queryNext .= " VALUES ('" . $_POST['userDevol'] . "','" . $date . "',' PICKING - " . json_encode($_POST['devol']) . "','1') ";
        $resultNext = $c->query($queryNext);
		if ($resultNext) {
		foreach ($devols as $devol) {
            
                if ($devol['carrito'] == '00000000') {
                    /* EXECUTE JOIN_POS_PEDIDDOS_PEPARADOS_NG @USER INT , @SUPEDIDO NVARCHAR(10) */
                    $sql = "
                        EXECUTE JOIN_INV_PREP_PACKING_INSERT '" . $devol['usuario'] . "', '" . $devol['supedido'] . "' 
                    ";
                } else {
                    $sql = "
                                EXECUTE JOIN_INV_PREP_PACKING_INSERT '" . $devol['supedido'] . "', '" . $devol['codbarras'] . "' ,  '" . $devol['unidades'] . "' 
                        ";
                }

                $pa1 = array();
                $op1 = array("scrollable" => SQLSRV_CURSOR_KEYSET);

                $re1 = sqlsrv_query($conexion, $sql, $pa1, $op1);
                $json['ques'][] = $sql;
                $json['reslst'][] = $re1;
            }

            $json['scriptResp'] = "done";
            $json['status'] = "saved";
            $output = ob_get_contents();
            ob_end_clean();
            $json['output'] = $output;
            echo json_encode($json);
            return;
        } else {
            $json['scriptResp'] = "error";
            $json['q'] = $queryNext;
            $json['qer'] = $c->error;
            $output = ob_get_contents();
            ob_end_clean();
            $json['output'] = $output;
            echo json_encode($json);
            return;
        }
    }
 //         GUARDAR PACKING   EMPACADO      //
    if ($method == 'guardarpackingemp') {

        $date = date('Y-m-d H:i:s');
        $devols = json_decode($_POST['devol'], true);
        $queryNext = " INSERT INTO gt_devols ( userDevol, fechaDevol, objDevol, statusDevol) ";
        $queryNext .= " VALUES ('" . $_POST['userDevol'] . "','" . $date . "',' PICKING - " . json_encode($_POST['devol']) . "','1') ";
        $resultNext = $c->query($queryNext);
		if ($resultNext) {
		foreach ($devols as $devol) {
            
                if ($devol['carrito'] == '00000000') {
                    /* EXECUTE JOIN_POS_PEDIDDOS_PEPARADOS_NG @USER INT , @SUPEDIDO NVARCHAR(10) */
                    $sql = "
                        EXECUTE JOIN_PACKING_EMBALAJE_UPDATE '" . $devol['usuario'] . "', '" . $devol['carrito'] . "' 
                    ";
                } else {
                    $sql = "
                                EXECUTE JOIN_PACKING_EMBALAJE_UPDATE '" . $devol['usuario'] . "', '" . $devol['carrito'] . "' 
                        ";
                }

                $pa1 = array();
                $op1 = array("scrollable" => SQLSRV_CURSOR_KEYSET);

                $re1 = sqlsrv_query($conexion, $sql, $pa1, $op1);
                $json['ques'][] = $sql;
                $json['reslst'][] = $re1;
				$seriePEd = $devol['serie'];
				$numeroPed = $devol['numero'];
								
				if($seriePEd == 'PZAF'){
					$numeroPed = substr($numeroPed,3);
					$idRastreo = $devol['carrito'];
					
                    $data['getIdPed']=$numeroPed;
					$data['getIdEst']=26;
					$data['IdRastreo']=$idRastreo;
					
					$tuCurl = curl_init(); 
					curl_setopt($tuCurl, CURLOPT_URL, "https://agora.com.gt/tta/api.php?meth=actualizarPed"); 
					curl_setopt($tuCurl, CURLOPT_RETURNTRANSFER, 1);
					curl_setopt($tuCurl, CURLOPT_POSTFIELDS, $data); 
					curl_exec($tuCurl); 
					if(!curl_errno($tuCurl)){
						$info = curl_getinfo($tuCurl);
					//echo 'Tiempo :' . $info['total_time'] . ' en ejecutar: ' . $info['url'];
					} else {
						echo 'Curl error: ' . curl_error($tuCurl);
					}
                }
				
            }

            $json['scriptResp'] = "done";
            $json['status'] = "saved";
            $output = ob_get_contents();
            ob_end_clean();
            $json['output'] = $output;
            echo json_encode($json);
            return;
        } else {
            $json['scriptResp'] = "error";
            $json['q'] = $queryNext;
            $json['qer'] = $c->error;
            $output = ob_get_contents();
            ob_end_clean();
            $json['output'] = $output;
            echo json_encode($json);
            return;
        }
    }

    //          CONSULTAR PRODUCTO NO LISTADO PNL      //
    if ($method == 'consultarPNL') {

        $codbar = $_POST['codbar'];
        $json['status'] = "noprod";
		
		$sql = "EXECUTE JOIN_INV_CODBARRAS_GET '" . $codbar . "' ";
        //$sql = " SELECT CODARTICULO, TALLA, COLOR FROM ARTICULOSLIN WHERE CODBARRAS = '" . $codbar . "' ";
        $pa1 = [];
        $op1 = array("scrollable" => SQLSRV_CURSOR_KEYSET);
        $re1 = sqlsrv_query($conexion, $sql, $pa1, $op1);
        if ($re1) {
            if (sqlsrv_num_rows($re1) != 0) {
                while ($fila = sqlsrv_fetch_array($re1)) {
                    $json['rows'][] = $fila;
                    $json['status'] = "gotProd";
					$json['provs'][] = $fila['NOMPROVEEDOR'];
                }
            }
        }
        /*$sql = " SELECT CODARTICULO, TALLA, COLOR FROM ARTICULOSLIN WHERE CODBARRAS2 = '" . $codbar . "' ";
        $pa1 = [];
        $op1 = array("scrollable" => SQLSRV_CURSOR_KEYSET);
        $re1 = sqlsrv_query($conexion, $sql, $pa1, $op1);
        if ($re1) {
            if (sqlsrv_num_rows($re1) != 0) {
                while ($fila = sqlsrv_fetch_array($re1)) {
                    $json['rows2'][] = $fila;
                    $json['status'] = "gotProd";
                }
                $sqlProv = " SELECT P.NOMPROVEEDOR 
                FROM ARTICULOSLIN AS AL INNER JOIN REFERENCIASPROV AS R ON AL.CODARTICULO = R.CODARTICULO
                LEFT JOIN PROVEEDORES AS P ON R.CODPROVEEDOR = P.CODPROVEEDOR
                WHERE CODBARRAS = '" . $codbar . "' 
                ";
                $pa1p = [];
                $op1p = array("scrollable" => SQLSRV_CURSOR_KEYSET);
                $re1p = sqlsrv_query($conexion, $sqlProv, $pa1p, $op1p);

                if (sqlsrv_num_rows($re1p) != 0) {
                    while ($fila = sqlsrv_fetch_array($re1p)) {
                        $json['provs'][] = $fila;
                    }
                }
            }
        }
        $sql = " SELECT CODARTICULO, TALLA, COLOR FROM ARTICULOSLIN WHERE CODBARRAS3 = '" . $codbar . "' ";
        $pa1 = [];
        $op1 = array("scrollable" => SQLSRV_CURSOR_KEYSET);
        $re1 = sqlsrv_query($conexion, $sql, $pa1, $op1);
        if ($re1) {
            if (sqlsrv_num_rows($re1) != 0) {
                while ($fila = sqlsrv_fetch_array($re1)) {
                    $json['rows3'][] = $fila;
                    $json['status'] = "gotProd";
                }
                $sqlProv = " SELECT P.NOMPROVEEDOR 
                FROM ARTICULOSLIN AS AL INNER JOIN REFERENCIASPROV AS R ON AL.CODARTICULO = R.CODARTICULO
                LEFT JOIN PROVEEDORES AS P ON R.CODPROVEEDOR = P.CODPROVEEDOR
                WHERE CODBARRAS = '" . $codbar . "' 
                ";
                $pa1p = [];
                $op1p = array("scrollable" => SQLSRV_CURSOR_KEYSET);
                $re1p = sqlsrv_query($conexion, $sqlProv, $pa1p, $op1p);

                if (sqlsrv_num_rows($re1p) != 0) {
                    while ($fila = sqlsrv_fetch_array($re1p)) {
                        $json['provs'][] = $fila;
                    }
                }
            }
        }*/

        $json['scriptResp'] = "done";
        $json['sql'] = $sql;
        $output = ob_get_contents();
        ob_end_clean();
        $json['output'] = $output;
        echo json_encode($json);
        return;
    }

    //          CONSULTAR SI LA UBICACION EXISTE      //
    if ($method == 'consultarUbic') {

        $codUbi = $_POST['codUbi'];
		$bod = $_POST['bod'];
		$tiporigdest = $_POST['tiporigdest1'];
        $json['status'] = "noprod";

        if($tiporigdest == 'C' ){
			$sql = " SELECT CODIGOBARRAS FROM JOIN_CAJAMASTER_2 AS A INNER JOIN JOIN_UBICACIONES AS B ON A.CODUBICACION = B.IDUBICACION   WHERE CODIGOBARRAS = '" . $codUbi . "' AND B.BODEGA = '" . $bod . "'";
		}else{
			//$sql = " SELECT IDUBICACION FROM JOIN_UBICACIONES WHERE IDUBICACION = '" . $codUbi . "' AND BODEGA = '" . $bod . "' ";
			$sql = "DECLARE @UBI NVARCHAR(20) = '" . $codUbi . "'
					DECLARE @BOD  NVARCHAR(20) = '" . $bod . "'

					IF LEN(@BOD)=0  BEGIN
					SELECT IDUBICACION FROM JOIN_UBICACIONES WHERE IDUBICACION = @UBI
					END
					ELSE
					BEGIN
					SELECT IDUBICACION FROM JOIN_UBICACIONES WHERE IDUBICACION = @UBI AND BODEGA =  @BOD 
					END";
		}
        $pa1 = [];
        $op1 = array("scrollable" => SQLSRV_CURSOR_KEYSET);
        $re1 = sqlsrv_query($conexion, $sql, $pa1, $op1);
        if ($re1) {
            if (sqlsrv_num_rows($re1) != 0) {
                while ($fila = sqlsrv_fetch_array($re1)) {
                    $json['rows'][] = $fila;
                    $json['status'] = "gotProd";
                }
            }
        }
		$json['letra'] = $tiporigdest;
        $json['scriptResp'] = "done";
        $json['sql'] = $sql;
        $output = ob_get_contents();
        ob_end_clean();
        $json['output'] = $output;
        echo json_encode($json);
        return;
    }
	/// consultamos si la gondola existe 
	
	 if ($method == 'consultargon') {

        $gon = $_POST['gon'];
		$json['status'] = "gotProd";  
        $sql = " SELECT TOP(1) GONDOLA CODIGOBARRAS FROM JOIN_INVENTARIO_FISICO WHERE FECHAALTA >= '07/24/2021' AND GONDOLA  = '" . $gon . "'";
		$pa1 = [];
        $op1 = array("scrollable" => SQLSRV_CURSOR_KEYSET);
        $re1 = sqlsrv_query($conexion, $sql, $pa1, $op1);
        if ($re1) {
            if (sqlsrv_num_rows($re1) != 0) {
                while ($fila = sqlsrv_fetch_array($re1)) {
                    $json['rows'][] = $fila;
                    $json['status'] = "noprod";
                }
            }
        }
		$json['letra'] = $gon;
        $json['scriptResp'] = "done";
        $json['sql'] = $sql;
        $output = ob_get_contents();
        ob_end_clean();
        $json['output'] = $output;
        echo json_encode($json);
        return;
    }
	
	/// consultamos si la gondola existe en la revision
	
	 if ($method == 'consultargonrev') {

        $gon = $_POST['gon'];
		$json['status'] = "gotProd";  
        $sql = " SELECT TOP(1) GONDOLA CODIGOBARRAS FROM JOIN_INVENTARIO_FISICO_REV WHERE FECHAALTA >= '07/24/2021' AND GONDOLA  = '" . $gon . "'";
		$pa1 = [];
        $op1 = array("scrollable" => SQLSRV_CURSOR_KEYSET);
        $re1 = sqlsrv_query($conexion, $sql, $pa1, $op1);
        if ($re1) {
            if (sqlsrv_num_rows($re1) != 0) {
                while ($fila = sqlsrv_fetch_array($re1)) {
                    $json['rows'][] = $fila;
                    $json['status'] = "noprod";
                }
            }
        }
		$json['letra'] = $gon;
        $json['scriptResp'] = "done";
        $json['sql'] = $sql;
        $output = ob_get_contents();
        ob_end_clean();
        $json['output'] = $output;
        echo json_encode($json);
        return;
    }
	//VALidaMos si El destino eXiste //
	if ($method == 'consultarDest') {

        $codUbi = $_POST['codUbi'];
		$bod = $_POST['bod'];
		$tiporigdest = $_POST['tiporigdest'];
        $json['status'] = "noprod";
		if($tiporigdest == 'C' ){
			$sql = "DECLARE @CODBARRASCM NVARCHAR(40)
			DECLARE @BODEGA NVARCHAR(4)
				SET @CODBARRASCM  = '".$codUbi."'
				SET @BODEGA  = '".$bod."'
				SELECT * FROM (
				SELECT CODIGOBARRAS FROM JOIN_CAJAMASTER_2 AS A INNER JOIN JOIN_UBICACIONES AS B ON A.CODUBICACION = B.IDUBICACION 
				WHERE CODIGOBARRAS = @CODBARRASCM AND B.BODEGA =  @BODEGA
				UNION ALL
				SELECT CODIGOBARRAS FROM JOIN_CAJAMASTER_UBICACION A INNER JOIN JOIN_UBICACIONES AS B ON A.UBICACION = B.IDUBICACION  WHERE CODIGOBARRAS = @CODBARRASCM AND B.BODEGA =  @BODEGA) AS A";
		}else{
			$sql = " SELECT IDUBICACION FROM JOIN_UBICACIONES WHERE IDUBICACION = '" . $codUbi . "' AND BODEGA = '" . $bod . "'  ";
		}
         
		
        $pa1 = [];
        $op1 = array("scrollable" => SQLSRV_CURSOR_KEYSET);
        $re1 = sqlsrv_query($conexion, $sql, $pa1, $op1);
        if ($re1) {
            if (sqlsrv_num_rows($re1) != 0) {
                while ($fila = sqlsrv_fetch_array($re1)) {
                    $json['rows'][] = $fila;
                    $json['status'] = "gotProd";
                }
            }
        }
        $json['scriptResp'] = "done";
        $json['sql'] = $sql;
        $output = ob_get_contents();
        ob_end_clean();
        $json['output'] = $output;
        echo json_encode($json);
        return;
    }
	
	//VALIDAR PORDUCTO EN UBICACION
	
	if($method == 'consultarUbiXCod'){
		
		$CodUbic = $_POST['UbicCod'];
		$CodProd = $_POST['CodProd'];
		$CodCajaM = $_POST['CodCajaM'];
		
		$json['scriptResp'] = "done";
		$json['status'] = 'ERROR';
		
		$sql = "EXECUTE JOIN_INV_STOCK '".$CodUbic."','".$CodCajaM."','".$CodProd."'";
		$stm = sqlsrv_prepare($conexion,$sql, array());
		$res = sqlsrv_execute($stm);
		if($res){
			while($row = sqlsrv_fetch_array($stm)){
				$json['status'] = $row['VALIDO'];
				$json['stock'] = $row['STOCK'];
				$json['msg'] = $row['MENSAJE'];
			}
		}
		
        $json['scriptResp'] = "done";
        $json['sql'] = $sql;
        $output = ob_get_contents();
        ob_end_clean();
        $json['output'] = $output;
        echo json_encode($json);
        return;
		
	}
	
	//Consultamos si existe stock //
	if ($method == 'consultastockxf') {

        $codubic = $_POST['codubic'];
		$codbarras = $_POST['codbarras'];
		$tipo = $_POST['tipo'];
		$json['status'] = "noprod";
		if($tipo == 'U' ){ 
				$sql = " SELECT  A.BODEGA, A.CAJAMASTER,A.UBICACION,A.MODELO, A.DESCRIPCION,  A.CODARTICULO, A.TALLA, A.COLOR, A.CODBARRAS, 
			  UNIDADES - ISNULL(SALIDAS,0) STOCK, A.CODUBICACION 
			  FROM  
			  ( SELECT  B.BODEGA,  A.CODIGOBARRAS CAJAMASTER, A.CODUBICACION UBICACION, A.CODARTICULO, AR.REFPROVEEDOR MODELO, AR.DESCRIPCION, 
			  	A.TALLA, A.COLOR, ARL.CODBARRAS, A.CANTIDADARTICULOS AS UNIDADES, B.CODUBICACION 
			  	FROM JOIN_CAJAMASTER_2 AS A  
			  	LEFT JOIN JOIN_UBICACIONES AS B ON CONVERT(VARCHAR, A.CODUBICACION) = CONVERT(VARCHAR, B.IDUBICACION) 
			  	LEFT JOIN ARTICULOS AS AR ON (A.CODARTICULO = AR.CODARTICULO) 
			  	LEFT JOIN ARTICULOSLIN AS ARL ON (A.CODARTICULO = ARL.CODARTICULO) AND (A.TALLA = ARL.TALLA COLLATE Latin1_General_CS_AI) AND (A.COLOR = ARl.COLOR COLLATE Latin1_General_CS_AI) 
			  	WHERE (B.BODEGA = '31') AND A.CODIGOBARRAS <>'0000'
			  ) AS A LEFT JOIN 
			  ( SELECT CAJAMASTER, CODIGOARTICULO, TALLA,COLOR, SUM(SALIDAS) SALIDAS 
			  	FROM JOIN_REPORTE_STOCK_BOG_TB AS AA WHERE BODEGA = '31' 
				AND CAJAMASTER <>'0000'
				GROUP BY CAJAMASTER, CODIGOARTICULO, TALLA,COLOR
			  ) AS B ON (A.CODARTICULO = B.CODIGOARTICULO) AND (A.TALLA = B.TALLA) 
			  AND (A.COLOR = B.COLOR) AND (A.CAJAMASTER = B.CAJAMASTER) WHERE 
			  (UNIDADES - ISNULL(SALIDAS,0) <>0) 
				UNION ALL
			   SELECT  A.BODEGA, A.CAJAMASTER,A.UBICACION,A.MODELO, A.DESCRIPCION,  A.CODARTICULO, A.TALLA, A.COLOR, A.CODBARRAS, 
			  ( UNIDADES - ISNULL(SALIDAS,0))- ISNULL(C.REST,0) STOCK, A.CODUBICACION  
			  FROM  
			  ( 
			  	SELECT  B.BODEGA,  A.CODIGOBARRAS CAJAMASTER, A.CODUBICACION UBICACION, A.CODARTICULO, AR.REFPROVEEDOR MODELO, AR.DESCRIPCION, 
			  	A.TALLA, A.COLOR, ARL.CODBARRAS, A.CANTIDADARTICULOS AS UNIDADES, B.CODUBICACION 
			  	FROM JOIN_CAJAMASTER_2 AS A  
			  	LEFT JOIN JOIN_UBICACIONES AS B ON CONVERT(VARCHAR, A.CODUBICACION) = CONVERT(VARCHAR, B.IDUBICACION) 
			  	LEFT JOIN ARTICULOS AS AR ON (A.CODARTICULO = AR.CODARTICULO) 
			  	LEFT JOIN ARTICULOSLIN AS ARL ON (A.CODARTICULO = ARL.CODARTICULO) AND (A.TALLA = ARL.TALLA COLLATE Latin1_General_CS_AI) AND (A.COLOR = ARl.COLOR COLLATE Latin1_General_CS_AI) 
			  	WHERE (B.BODEGA = '31') AND A.CODIGOBARRAS ='0000' 
			  ) AS A LEFT JOIN 
			  ( SELECT CAJAMASTER,UBICACION, CODIGOARTICULO, TALLA,COLOR, SUM(SALIDAS) SALIDAS 
			  	FROM JOIN_REPORTE_STOCK_BOG_UB AS AA WHERE BODEGA = '31' 
				GROUP BY CAJAMASTER,UBICACION, CODIGOARTICULO, TALLA,COLOR
			  ) AS B ON (A.CODARTICULO = B.CODIGOARTICULO) AND (A.TALLA = B.TALLA) 
			  AND (A.COLOR = B.COLOR) AND (A.CAJAMASTER = B.CAJAMASTER)
			  AND  A.UBICACION = B.UBICACION
			  LEFT JOIN 
			   (SELECT '0000' CAJAMASTER , A.CODARTICULO, A.TALLA,A.COLOR, A.CODUBICACION, SUM(ISNULL(A.UNIDADES,0)) REST 
              FROm JOIN_AUX_PICKING_FACTURAS AS A INNER JOIN JOIN_UBICACIONES AS B ON A.CODUBICACION = B.IDUBICACION 
				GROUP BY A.CODARTICULO, A.TALLA,A.COLOR, A.CODUBICACION) AS C ON  
				(A.CODARTICULO = C.CODARTICULO) AND (A.TALLA = C.TALLA)  
		      AND (A.COLOR = C.COLOR) AND (A.CAJAMASTER = C.CAJAMASTER) 
			  AND  A.UBICACION = C.CODUBICACION 
			  WHERE 
			  (UNIDADES - ISNULL(SALIDAS,0) >0)  AND A.CODBARRAS = '" . $codbarras . "' AND A.UBICACION = '" . $codubic . "' ";
		}else{
			$sql = " SELECT IDUBICACION FROM JOIN_UBICACIONES WHERE IDUBICACION = '" . $codbarras . "' AND BODEGA = '" . $cajamaster . "'  ";
		}
         
		
        $pa1 = [];
        $op1 = array("scrollable" => SQLSRV_CURSOR_KEYSET);
        $re1 = sqlsrv_query($conexion, $sql, $pa1, $op1);
        if ($re1) {
            if (sqlsrv_num_rows($re1) != 0) {
                while ($fila = sqlsrv_fetch_array($re1)) {
                    $json['rows'][] = $fila;
                    $json['status'] = "gotProd";
                }
            }
        }
        $json['scriptResp'] = "done";
        $json['sql'] = $sql;
        $output = ob_get_contents();
        ob_end_clean();
        $json['output'] = $output;
        echo json_encode($json);
        return;
    }
	//VALidaMos que la caja exista en la ubicacion //
	if ($method == 'consultarMasterBosUbic') {

        $codUbi = $_POST['codUbi'];
		$CodMasterBox = $_POST['codMB'];
        $json['status'] = "noprod";

       
		$sql = "SELECT CODIGOBARRAS FROM JOIN_CAJAMASTER_2 WHERE CODIGOBARRAS = '".$CodMasterBox."' AND CODUBICACION = ".$codUbi;
        $pa1 = [];
        $op1 = array("scrollable" => SQLSRV_CURSOR_KEYSET);
        $re1 = sqlsrv_query($conexion, $sql, $pa1, $op1);
        if ($re1) {
            if (sqlsrv_num_rows($re1) != 0) {
                while ($fila = sqlsrv_fetch_array($re1)) {
                    $json['rows'][] = $fila;
                    $json['status'] = "gotProd";
                }
            }
        }
        $json['scriptResp'] = "done";
        $json['sql'] = $sql;
        $output = ob_get_contents();
        ob_end_clean();
        $json['output'] = $output;
        echo json_encode($json);
        return;
    }

    //          CONSULTAR PRODUCTO NO LISTADO PNL      //
    if ($method == 'consultarProdTomaFis') {

        $codbar = $_POST['codbar'];
        $json['status'] = "noprod";

        $sql = " SELECT  TOP(1) A.CODARTICULO, A.TALLA,A.COLOR,A.CODUBICACION
        FROM JOIN_CAJAMASTER_2 As A INNER JOIN ARTICULOSLIN AS AL ON A.CODARTICULO = AL.CODARTICULO
        AND A.TALLA = AL.TALLA COLLATE Latin1_General_CS_AI
        AND A.COLOR = AL.COLOR  COLLATE Latin1_General_CS_AI
        WHERE CODBARRAS = '" . $codbar . "'  AND A.CODUBICACION = '" . $codbar . "' 
        UNION
        SELECT  TOP(1)  A.CODARTICULO, A.TALLA,A.COLOR,A.CODUBICACION
        FROM JOIN_CAJAMASTER_2 As A INNER JOIN ARTICULOSLIN AS AL ON A.CODARTICULO = AL.CODARTICULO
        AND A.TALLA = AL.TALLA COLLATE Latin1_General_CS_AI
        AND A.COLOR = AL.COLOR  COLLATE Latin1_General_CS_AI
        WHERE CODBARRAS2 = '" . $codbar . "'   AND A.CODUBICACION = '" . $codbar . "' 
        UNION
        SELECT  TOP(1)  A.CODARTICULO, A.TALLA,A.COLOR,A.CODUBICACION
        FROM JOIN_CAJAMASTER_2 As A INNER JOIN ARTICULOSLIN AS AL ON A.CODARTICULO = AL.CODARTICULO
        AND A.TALLA = AL.TALLA COLLATE Latin1_General_CS_AI
        AND A.COLOR = AL.COLOR  COLLATE Latin1_General_CS_AI
        WHERE CODBARRAS3 = '" . $codbar . "'   AND A.CODUBICACION = '" . $codbar . "' ";
        $pa1 = [];
        $op1 = array("scrollable" => SQLSRV_CURSOR_KEYSET);
        $re1 = sqlsrv_query($conexion, $sql, $pa1, $op1);
        if ($re1) {
            if (sqlsrv_num_rows($re1) != 0) {
                while ($fila = sqlsrv_fetch_array($re1)) {
                    $json['rows'][] = $fila;
                    $json['status'] = "gotProd";
                }
            }
        }

        $json['scriptResp'] = "done";
        $json['sql'] = $sql;
        $output = ob_get_contents();
        ob_end_clean();
        $json['output'] = $output;
        echo json_encode($json);
        return;
    }

    //          CONSULTAR PRODUCTO NO LISTADO PNL      //
    if ($method == 'getBodegas') {


        $codbar = $_POST['codbar'];
        $json['status'] = "noprod";

        $sql = " SELECT CODALMACEN FROM GRUPOSALMACENLIN
        WHERE IDGRUPO = 1
        ";

        $pa1 = [];
        $op1 = array("scrollable" => SQLSRV_CURSOR_KEYSET);
        $re1 = sqlsrv_query($conexion, $sql, $pa1, $op1);
        if ($re1) {
            if (sqlsrv_num_rows($re1) != 0) {
                while ($fila = sqlsrv_fetch_array($re1)) {
                    $json['rows'][] = $fila;
                    $json['status'] = "gotBod";
                }
            }
        }

        $json['scriptResp'] = "done";
        $json['sql'] = $sql;
        $output = ob_get_contents();
        ob_end_clean();
        $json['output'] = $output;
        echo json_encode($json);
        return;
    }

    //          GUARDAR NUEVA ORDEN DE RECEPCION   DE TRASLADO  A CEDI      //
    if ($method == 'saveNewRecepsTralsCedi') {

        $date = date('Y-m-d H:i:s');
        $devols = json_decode($_POST['devol'], true);
        $queryNext = " INSERT INTO gt_devols ( userDevol, fechaDevol, objDevol, statusDevol) ";
        $queryNext .= " VALUES ('" . $_POST['userDevol'] . "','" . $date . "','CEDI - " . json_encode($_POST['devol']) . "','1') ";
        $resultNext = $c->query($queryNext);

        if ($resultNext) {

            /** DESACTIVAR LA PUBLICACION */
            foreach ($devols as $devol) {

                $json['rowsUpds'] = [];
                $json['rowsQs'] = [];
                if ($devol['cajamas'] != '0000') {
                    $cajaTextAnd = " AND CAJAMASTER = '" . $devol['cajamas'] . "'";
                }

                $sql = "
                            UPDATE JOIN_DEVOLUCIONES SET RECIBODESTINO = '" . $devol['returnquantity'] . "'
                            WHERE CODIGOARTICULO = '" . $devol['codarticulo'] . "' AND TALLA = '" . $devol['talla'] . "' AND COLOR = '" . $devol['color'] . "'  AND MODULO = '22' AND DOCUMENTO = '" . $devol['doc'] . "' " . $cajaTextAnd . "
                ";
                $pa1 = array();
                $op1 = array("scrollable" => SQLSRV_CURSOR_KEYSET);

                $re1 = sqlsrv_query($conexion, $sql, $pa1, $op1);

                $json['rowsUpds'][] = "UPDATED " . $devol['codarticulo'];
                $json['rowsQs'][] = $sql;

                /** INCOVAMOS EL WS */
                $wsdlUrl = 'http://10.238.26.69:9298/Service1.asmx?wsdl';
                $client = new SoapClient($wsdlUrl);

                error_log('//////////////////       DEVOL    ///////////////////////////////' .  print_r($devol, true));
                $string = '';
                foreach ($devol as $key => $value) {
                    if ($string == '') {
                        $string .= $key . ":" . $value;
                    } else {
                        $string .= "," . $key . ":" . $value;
                    }
                }
                error_log('//////////////////       DEVOLstring    ///////////////////////////////' .  print_r($string, true));
                $params = new stdClass();
                $params->detail = $string;
                $result = $client->SaveReturnDetail($params);

                /** CAMBIOS CEDI */
                $sql = " 
                DECLARE @CODARTICULO INT
                DECLARE @TALLA NVARCHAR(15)
                DECLARE @COLOR NVARCHAR(15)
                DECLARE @CAJAMASTER NVARCHAR(20)
                DECLARE @CANTIDAD FLOAT
                DECLARE @UBICACION NVARCHAR(10)
                DECLARE @USUARIO NVARCHAR(20)
                DECLARE @EXISTE INT 
                
                
                SET @CODARTICULO ='" . $devol['codarticulo'] . "'
                SET @TALLA = '" . $devol['talla'] . "'
                SET @COLOR ='" . $devol['color'] . "'
                SET @CAJAMASTER ='" . $devol['cajamas'] . "'
                SET @CANTIDAD ='" . $devol['returnquantity'] . "'
                SET @UBICACION = '" . $devol['ubi'] . "'
                SET @USUARIO = '" . $devol['usuario'] . "'
                SET @EXISTE =  (
                SELECT ISNULL(COUNT(*),0)CN FROM JOIN_CAJAMASTER_2 
                WHERE CODARTICULO = @CODARTICULO AND TALLA = @TALLA AND COLOR = @COLOR AND CODIGOBARRAS = @CAJAMASTER AND  CODUBICACION = @UBICACION )
                
                
                SELECT @EXISTE
                
                
                SELECT TOP(2)* FROM JOIN_CAJAMASTER_2 
                
                IF @EXISTE=0
                BEGIN
                INSERT INTO JOIN_CAJAMASTER_2 (CODIGOBARRAS,CODARTICULO, TALLA,COLOR, CODUBICACION,UNIDADESPORCAJA, CANTIDADARTICULOS,FECHAREGISTRO,USUARIOREGISTRO, USUARIOMODIFICACION)
                SELECT  @CAJAMASTER,@CODARTICULO,@TALLA,@COLOR, @UBICACION, 0, @CANTIDAD, GETDATE(), @USUARIO,@USUARIO
                END
                    ";
                $pa1 = array();
                $op1 = array("scrollable" => SQLSRV_CURSOR_KEYSET);

                $re1 = sqlsrv_query($conexion, $sql, $pa1, $op1);
                if (sqlsrv_num_rows($re1) != 0) {
                    while ($fila = sqlsrv_fetch_array($re1)) {
                        $json['rows'][] = $fila;
                    }
                }
            }

            $json['scriptResp'] = "done";
            $json['status'] = "saved";
            $output = ob_get_contents();
            ob_end_clean();
            $json['output'] = $output;
            echo json_encode($json);
            return;
        } else {
            $json['scriptResp'] = "error";
            $json['q'] = $queryNext;
            $json['qer'] = $c->error;
            $output = ob_get_contents();
            ob_end_clean();
            $json['output'] = $output;
            echo json_encode($json);
            return;
        }
    }

  //          CONSULTAR LA IMAGEN DEL PRODUCTO         //
    if ($method == 'consultarimg') {
        $referencia = $_POST['referencia'];
        $codbarras = $_POST['codbarras'];
        $json['rows'] = [];

        $sql = "SELECT TOP(1) 'https://agora.com.gt/tta/assets/syncimgs/prods/'+REFPROVEEDOR+'-'+AL.COLOR+'-1.jpg' UBICACION
				FROM ARTICULOS AS A INNER JOIN ARTICULOSLIN AS AL ON A.CODARTICULO = AL.CODARTICULO
				WHERE  AL.CODBARRAS ='" . $codbarras . "'  
        ";
   
        $pa1 = array();
        $op1 = array("scrollable" => SQLSRV_CURSOR_KEYSET);

        $re1 = sqlsrv_query($conexion, $sql, $pa1, $op1);
        if (sqlsrv_num_rows($re1) != 0) {
            while ($fila = sqlsrv_fetch_array($re1)) {
                $json['rows'][] = $fila;
            }
        }

        $json['scriptResp'] = "done";
        $json['status'] = "gotback";
        $output = ob_get_contents();
        ob_end_clean();
        $json['q'] = $sql;
        $json['output'] = $output;
        echo json_encode($json);
        return;
    }


    //          CONSULTAR REUBICACION         //
    if ($method == 'consultarReubic') {

        $userId = $_POST['userId']; 
		
		$sql = "SELECT A.REFERENCIA, A.DESCRIPCION, A.TALLA, A.COLOR, A.CODBARRAS, A.CODBARRAS2, A.CODBARRAS3, ABS(SUM(ISNULL(A.UNIDADES,0) -ISNULL(B.UNIDADES,0) ))UNIDADES FROM (
					(SELECT  AL.REFERENCIA, AL.DESCRIPCION, AL.TALLA, AL.COLOR, ARL.CODBARRAS, ARL.CODBARRAS2, ARL.CODBARRAS3, ABS(SUM(AL.UNIDADESTOTAL ))UNIDADES
					FROM FACTURASVENTA AS F
					INNER JOIN ALBVENTACAB AS AC ON F.NUMSERIE = AC.NUMSERIEFAC AND F.NUMFACTURA = AC.NUMFAC
					INNER JOIN ALBVENTALIN AS AL ON AC.NUMSERIE = AL.NUMSERIE AND AC.NUMALBARAN = AL.NUMALBARAN
					LEFT JOIN ARTICULOSLIN AS ARL ON AL.CODARTICULO = ARL.CODARTICULO AND  AL.TALLA = ARL.TALLA AND AL.COLOR = ARL.COLOR
					WHERE CONVERT(DATE,F.FECHA,3)=CONVERT(DATE,GETDATE(),3) AND AL.CODALMACEN = '12'
					GROUP BY AL.REFERENCIA, AL.DESCRIPCION, AL.TALLA, AL.COLOR, ARL.CODBARRAS, ARL.CODBARRAS2, ARL.CODBARRAS3
					) A 
				LEFT JOIN (
					SELECT CODBARRAS, SUM(UNIDADES) UNIDADES FROM JOIN_AUX_REUBICACIONES WHERE CONVERT(DATE,FECHA,3)= CONVERT(DATE,GETDATE(),3) AND ORIGEN = 4827 AND DESTINO = 5297
					GROUP BY ORIGEN, DESTINO,CODBARRAS,TIPO
				)B ON B.CODBARRAS IN (A.CODBARRAS COLLATE Modern_Spanish_CI_AS, A.CODBARRAS2 COLLATE Modern_Spanish_CI_AS, A.CODBARRAS3 COLLATE Modern_Spanish_CI_AS)
				) GROUP BY 
				A.REFERENCIA, A.DESCRIPCION, A.TALLA, A.COLOR, A.CODBARRAS, A.CODBARRAS2, A.CODBARRAS3
				HAVING SUM(ISNULL(A.UNIDADES,0) -ISNULL(B.UNIDADES,0) ) > 0 ";
				
		$sql = "EXECUTE JOININTEGRADOR.DBO.JOIN_INV_REU_B12_GET";
        $pa1 = [];
		
		$stm = sqlsrv_prepare($conexion, $sql,array());
		$exec = sqlsrv_execute($stm);
		
        $op1 = array("scrollable" => SQLSRV_CURSOR_KEYSET);
        $re1 = sqlsrv_query($conexion, $sql, $pa1, $op1);
        if ($exec) {
			while ($fila = sqlsrv_fetch_array($stm)) {
				$json['rows'][] = $fila;
				$json['status'] = "gotBod";
			}
            /*if (sqlsrv_num_rows($stm) != 0) {  
            }*/
        }

        $json['scriptResp'] = "done";
        $json['resp'] = $result;
        $output = ob_get_contents();
        ob_end_clean();
        $json['output'] = $output;
        echo json_encode($json);
        return;
    }

    //          CONSULTAR REUBICACION         //
    if ($method == 'consultarCajamas') {

        $userId = $_POST['userId'];
        $cajaVal = $_POST['cajaVal'];
		$CajaTip = $_POST['cajaTipo'];
		
		if($CajaTip == 'CB'){
			$json['tipo'] = 'CB';
			$codBar = $_POST['CodBar'];
			$codBod= $_POST['CodBod'];
			$sql = "EXECUTE JOIN_INV_STOCK_ART '".$codBod."','".$codBar."'";
			
			$stm = sqlsrv_prepare($conexion, $sql, array());
			$exe = sqlsrv_execute($stm);
			
			if ($exe) {
				
				while ($fila = sqlsrv_fetch_array($stm)) {
					$json['rows'][] = $fila;
					$json['status'] = "gotBod";
				}
				
			}

		}else if($CajaTip == 'U' || $CajaTip == 'u'){
			
			$json['tipo'] = $CajaTip;
			$sql = "SELECT * FROM JOIN_SOTCK_X_APP ('".$cajaVal."','U')";
			
			$stm = sqlsrv_prepare($conexion, $sql, array());
			$exe = sqlsrv_execute($stm);
			
			if ($exe){
				
				while ($fila = sqlsrv_fetch_array($stm)) {
					$json['rows'][] = $fila;
					$json['status'] = "gotBod";
				}
				
			}
		}else if($CajaTip == 'C'){
			
			$json['tipo'] = $CajaTip;
			$sql = "SELECT * FROM JOIN_SOTCK_X_APP ( '" . $cajaVal . "' , 'C' )";
			$pa1 = [];
			
			$stm = sqlsrv_prepare($conexion, $sql, array());
			$exe = sqlsrv_execute($stm);
			
			if ($exe){
				
				while ($fila = sqlsrv_fetch_array($stm)) {
					$json['rows'][] = $fila;
					$json['status'] = "gotBod";
				}
				
			}
		}

        $json['scriptResp'] = "done";
        $output = ob_get_contents();
        ob_end_clean();
        $json['output'] = $output;
        echo json_encode($json);
        return;
    }

    //          DEBUG           //
    if ($method == 'debug') {

        $sql = "

        SELECT  TOP(1)CODIGOBARRAS  FROM JOIN_CAJAMASTER_2
        WHERE CODIGOBARRAS = '20244263'
        AND CODUBICACION = '79'
        ";
        $pa1 = array();
        $op1 = array("scrollable" => SQLSRV_CURSOR_KEYSET);
        $re1 = sqlsrv_query($conexion, $sql, $pa1, $op1);
        $i = 0;
        if (sqlsrv_num_rows($re1) != 0) {
            while ($fila = sqlsrv_fetch_array($re1)) {
                if ($i == 3) {
                    break;
                }
                $json['rows'][] = $fila;
                $i++;
            }
        }

        $json['scriptResp'] = "done";
        $json['sql'] = $sql;
        $json['cont'] = $i;
        $output = ob_get_contents();
        ob_end_clean();
        $json['output'] = $output;
        error_log(json_encode($json));
        echo json_encode($json);
        return;
    }
}

//   Si no se llamó ningún método de la API     //
$output = ob_get_contents();
$json['post'] = json_encode($_POST);
$json['get'] = json_encode($_GET);
$json['files'] = json_encode($_FILES);
$json['msg'] = "Mute API";
$json['output'] = $output;
ob_end_clean();
echo json_encode($json);
return;
