<?

function loginapi($usuario,$password,$url){
$include=includec($url);
include ($include);
$query=mysqli_query($link,"SELECT *FROM vtiger_users where user_name='$usuario'");
$num=mysqli_num_rows($query);
if($num==1){
    $data= mysqli_fetch_array($query);  
    $pass=$data['user_hash'];
    if (md5($password) === $pass) {
        $iduser=$data['id'];
        $key_user=$data['accesskey'];
        $userarray[0]=array('id_user'=>$iduser,'user_key'=>$key_user,'opf_success'=>'1');
        echo json_encode($userarray);
    }else{
    $userarray[0]=array('id_user'=>$usuario,'user_key'=>'Password Error','opf_success'=>'0');
        echo json_encode($userarray);
    }
}else{
     $userarray[0]=array('id_user'=>'Username not found','user_key'=>$password,'opf_success'=>'0');
        echo json_encode($userarray);
}
}


function loginkey($usuario,$key,$url){
    if(empty($usuario) || empty($key) || empty($url)){
        return 0;
    }else{
        $include=includec($url);
        include ($include);
        $query=mysqli_query($link,"SELECT *FROM vtiger_users where id='$usuario' AND accesskey='$key'");
        $data= mysqli_num_rows($query);    
        if ($data>0) {
            return 1;    
        }else{
            return 0;    
        }        
    }    
}

function includec($url){
    $domain=explode(".",$url);
    $subdomain=$domain[0];
    $pdomain=$domain[1];
    $cdomain=$domain[2];
    $total=$pdomain.$cdomain;
    if($total=="globalbco" || $total=="globalbcocom" || $total=="globalbcocom/"  || $total=="globalb" ){
        $domain=explode("//",$subdomain);
        $domain=$domain[1];
        if($domain=="siromax"){
            $domain="siromax";
            $include="../".$domain."/popup/ConexionMobile.php";
        }else{   
            $include="../".$domain."/popup/ConexionMobile.php";
        }
        return $include;
    }else{
        return 0;
    }    
}



function includenative($user,$key,$url){
    $domain=explode(".",$url);
    $domain=$domain[0];
    $domain=explode("//",$domain);
    $domain=$domain[1];
    if($domain=="siromax"){
        $domain="siromax";
        $domain="/home/gbcoha2h/public_html/".$domain;
    }else{
        $domain="/home/gbcoha2h/public_html/".$domain;
    }   
    return $domain;
    
}

function diccionario($url,$campo){
    if (strpos($url, 'hoser') !== false) {
        $dcampos = array("userws"=>'gbcos','keyws'=>'RsFWUWIJfXhi6XRm','stockfisico' =>'cf_1792','completadooc'=>'cf_1790','completadoos'=>'cf_1782','traslados'=>'cf_1784','borigen'=>'cf_1786','bodestino'=>'cf_1788','codproduct'=>'cf_1228','cuentaoc'=>'cf_1588','vendorcode'=>'cf_1798','Bodegas'=>'41x','Paquetes'=>'49x','Slots'=>'46x','Racks'=>'45x','Movimientos'=>'47x','Inventario'=>'44x','RInv'=>'43x','DirCaja'=>'cf_1856','ComCaja'=>'cf_1858','RegCaja'=>'cf_1860','PaiCaja'=>'cf_1862','Resultadori'=>'cf_1864','BodAsset'=>'cf_1882','SlotAsset'=>'cf_1884','RackAsset'=>'cf_1886','SeccAsset'=>'cf_1888', 'FIngresoB'=>'cf_1890','FSalidaB'=>'cf_1892','LoteB'=>'cf_1894','QtyAsset'=>'cf_1896','UltInv'=>'cf_1898','MovAsset'=>'cf_1900','RegInvAsset'=>'cf_1902','EstadoAsset'=>'En Bodega','OsCongField'=>'cf_1662','OsCongEst'=>'04 - Consignacion (Guia)1','OCOSDevo'=>'cf_1959','accountst'=>'354','stockconsignacion'=>'cf_1965','AssetResv'=>'cf_1967','AssetOc'=>'cf_1971','CantReser'=>'cf_1969','cantidadped'=>'qtyindemand','cantidadproces'=>'cf_1949','OsBi'=>'cf_2967','Propiedad'=>'cf_2274', 'Modalidad'=>'cf_800' , 'DestinadoABI'=>'cf_1931','TipoOS'=>'cf_1660','DestinadoA'=>'cf_2813','AtendidoPor'=>'cf_2807','CodCCosto'=>'cf_2821','fechaSoftOc'=>'cf_1568','fechaIngresoFabrica'=>'cf_2847','fechaIngresoBodega'=>'cf_2831','CodCCostoCajas'=>'cf_2851','fechaSalidaBodega'=>'cf_2833','CatInventario'=>'""','SeccionRack'=>'cf_1929','TokenFireBase'=>'""','ZonaPickeo'=>'""');
    }
    if (strpos($url, 'siromax') !== false) {
        $dcampos = array("userws"=>'gbcollc','keyws'=>'6CDrYRrL34P05XL','stockfisico' =>'cf_1907','completadooc'=>'cf_1905','completadoos'=>'cf_1897','traslados'=>'cf_1899','borigen'=>'cf_1901','bodestino'=>'cf_1903','codproduct'=>'productcode','cuentaoc'=>'cf_1713','vendorcode'=>'cf_1909','Bodegas'=>'45x','Paquetes'=>'52x','Slots'=>'50x','Racks'=>'49x','Movimientos'=>'51x','Inventario'=>'48x','RInv'=>'47x','DirCaja'=>'cf_1937','ComCaja'=>'cf_1939','RegCaja'=>'cf_1941','PaiCaja'=>'cf_1943','Resultadori'=>'cf_2038','BodAsset'=>'cf_2009','SlotAsset'=>'cf_2011','RackAsset'=>'cf_2013','SeccAsset'=>'cf_2015','FIngresoB'=>'cf_2017','FSalidaB'=>'cf_2019','LoteB'=>'cf_2021','QtyAsset'=>'cf_2023','UltInv'=>'cf_2025','MovAsset'=>'cf_2027','RegInvAsset'=>'cf_2029','EstadoAsset'=>'En Stock','OsCongField'=>'cf_856','OsCongEst'=>'Consignacion','OCOSDevo'=>'cf_2144','accountst'=>'292','stockconsignacion'=>'cf_2148','AssetResv'=>'cf_2150','AssetOc'=>'cf_2152','CantReser'=>'cf_1218','cantidadped'=>'qtyindemand','cantidadproces'=>'cf_2080','OsBi'=>'cf_2549','TipoOS'=>'cf_856','ZonaPickeo'=>'""', 'CatInventario'=>'cf_2683', 'SeccionRack'=>'cf_2040');
    }
    if (strpos($url, 'opfdemo') !== false) {
        $dcampos = array("userws"=>'admin','keyws'=>'udqvkv7ht6noeclo','stockfisico' =>'cf_1907','completadooc'=>'cf_1905','completadoos'=>'cf_1897','traslados'=>'cf_1899','borigen'=>'cf_1901','bodestino'=>'cf_1903','codproduct'=>'productcode','cuentaoc'=>'cf_1713','vendorcode'=>'cf_1909','Bodegas'=>'45x','Paquetes'=>'52x','Slots'=>'50x','Racks'=>'49x','Movimientos'=>'51x','Inventario'=>'48x','RInv'=>'47x','DirCaja'=>'cf_1937','ComCaja'=>'cf_1939','RegCaja'=>'cf_1941','PaiCaja'=>'cf_1943','Resultadori'=>'cf_2038','BodAsset'=>'cf_2009','SlotAsset'=>'cf_2011','RackAsset'=>'cf_2013','SeccAsset'=>'cf_2015','FIngresoB'=>'cf_2017','FSalidaB'=>'cf_2019','LoteB'=>'cf_2021','QtyAsset'=>'cf_2023','UltInv'=>'cf_2025','MovAsset'=>'cf_2027','RegInvAsset'=>'cf_2029','EstadoAsset'=>'En Stock','OsCongField'=>'cf_856','OsCongEst'=>'Consignacion','OCOSDevo'=>'cf_2144','accountst'=>'292','stockconsignacion'=>'cf_2148','AssetResv'=>'cf_2150','AssetOc'=>'cf_2152','CantReser'=>'cf_1218','cantidadped'=>'qtyindemand','cantidadproces'=>'cf_2080','OsBi'=>'','TipoOS'=>'cf_856','ZonaPickeo'=>'""');
    }
    if (strpos($url, 'aquaplants') !== false) {
        $dcampos = array("userws"=>'admin','keyws'=>'mwwehvj5qxw2qvvn','stockfisico' =>'cf_1792','completadooc'=>'cf_1790','completadoos'=>'cf_1782','traslados'=>'cf_1784','borigen'=>'cf_1786','bodestino'=>'cf_1788','codproduct'=>'product_no','cuentaoc'=>'cf_1588','vendorcode'=>'cf_1798','Bodegas'=>'41x','Paquetes'=>'49x','Slots'=>'46x','Racks'=>'45x','Movimientos'=>'47x','Inventario'=>'44x','RInv'=>'43x','DirCaja'=>'cf_1856','ComCaja'=>'cf_1858','RegCaja'=>'cf_1860','PaiCaja'=>'cf_1862','Resultadori'=>'cf_1864','BodAsset'=>'cf_1882','SlotAsset'=>'cf_1884','RackAsset'=>'cf_1886','SeccAsset'=>'cf_1888', 'FIngresoB'=>'cf_1890','FSalidaB'=>'cf_1892','LoteB'=>'cf_1894','QtyAsset'=>'cf_1896','UltInv'=>'cf_1898','MovAsset'=>'cf_1900','RegInvAsset'=>'cf_1902','EstadoAsset'=>'En Bodega','OsCongField'=>'cf_1662','OsCongEst'=>'04 - Consignacion (Guia)1','OCOSDevo'=>'cf_1959','accountst'=>'354','stockconsignacion'=>'cf_1965','AssetResv'=>'cf_1967','AssetOc'=>'cf_1971','CantReser'=>'cf_1969','cantidadped'=>'qtyindemand','cantidadproces'=>'cf_1949','OsBi'=>'cf_2967','Propiedad'=>'cf_2274', 'Modalidad'=>'cf_800' , 'DestinadoABI'=>'cf_1931','TipoOS'=>'cf_1660','DestinadoA'=>'cf_2813','AtendidoPor'=>'cf_2807','CodCCosto'=>'cf_2821','fechaSoftOc'=>'cf_1568','fechaIngresoFabrica'=>'cf_2847','fechaIngresoBodega'=>'cf_2831','CodCCostoCajas'=>'cf_2851','fechaSalidaBodega'=>'cf_2833');
    }
    if (strpos($url, 'solucorp') !== false) {
        $dcampos = array("userws"=>'gbcollc','keyws'=>'6CDrYRrL34P05XL','stockfisico' =>'cf_1907','completadooc'=>'cf_1905','completadoos'=>'cf_1897','traslados'=>'cf_1899','borigen'=>'cf_1901','bodestino'=>'cf_1903','codproduct'=>'productcode','cuentaoc'=>'cf_1713','vendorcode'=>'cf_1909','Bodegas'=>'45x','Paquetes'=>'52x','Slots'=>'50x','Racks'=>'49x','Movimientos'=>'51x','Inventario'=>'48x','RInv'=>'47x','DirCaja'=>'cf_1937','ComCaja'=>'cf_1939','RegCaja'=>'cf_1941','PaiCaja'=>'cf_1943','Resultadori'=>'cf_2038','BodAsset'=>'cf_2009','SlotAsset'=>'cf_2011','RackAsset'=>'cf_2013','SeccAsset'=>'cf_2015','FIngresoB'=>'cf_2017','FSalidaB'=>'cf_2019','LoteB'=>'cf_2021','QtyAsset'=>'cf_2023','UltInv'=>'cf_2025','MovAsset'=>'cf_2027','RegInvAsset'=>'cf_2029','EstadoAsset'=>'En Stock','OsCongField'=>'cf_856','OsCongEst'=>'Consignacion','OCOSDevo'=>'cf_2144','accountst'=>'292','stockconsignacion'=>'cf_2148','AssetResv'=>'cf_2150','AssetOc'=>'cf_2152','CantReser'=>'cf_1218','cantidadped'=>'qtyindemand','cantidadproces'=>'cf_2080','OsBi'=>'cf_2549','TipoOS'=>'cf_856','CatInventario'=>'cf_2725','TokenFireBase'=>'cf_2733','ZonaPickeo'=>'cf_2737','Stock2'=>'cf_2739','CantidadLote2'=>'cf_2741','QtyAlmacenamiento'=>'cf_2743', 'SeccionRack'=>'cf_2040','EstadoWMS_OS'=>'cf_2757', 'EstadoWMS_OC'=>'cf_2759','F_planificado'=>'cf_2761','F_Asignado'=>'cf_2763','F_Preparacion'=>'cf_2765','F_FinalizadParcial'=>'cf_2767','F_Finalizado'=>'cf_2769','F_Despachado'=>'cf_2771');
    }

    return $dcampos[$campo];
}

function CamposAssets($url,$campo,$operacion){
    if (strpos($url, 'hoser') !== false) {
        if($operacion==1){
            $arra=array('assetname'=>$productname,'serialnumber'=>$serieBI,'assetstatus'=>$estadoAsset,'product'=>$productid,$lote=>'Individual',$cantasset=>'0',$fingreso=>$ingreso,$BodAsset=>$bodega,$SlotAsset=>$slotcodigo,$SeccAsset=>$seccion,$RackAsset=>$rack);
        }
        if($operacion==2){
            $arra=array('assetname'=>$productname,'serialnumber'=>$serieBI,'assetstatus'=>$estadoAsset,'product'=>$productid,$lote=>'Set',$fingreso=>$ingreso,$BodAsset=>$bodega,$SlotAsset=>$slotcodigo,$SeccAsset=>$seccion, $RackAsset=>$rack);
        }
        
    }
    if (strpos($url, 'siromax') !== false) {
        if($operacion==1){
            $arra=array('assetname'=>$productname,'serialnumber'=>$serieBI,'assetstatus'=>$estadoAsset,'product'=>$productid,$lote=>'Individual',$cantasset=>'0',$fingreso=>$ingreso,$BodAsset=>$bodega,$SlotAsset=>$slotcodigo,$SeccAsset=>$seccion,$RackAsset=>$rack,"account"=>"11x132743","contact"=>"12x203167","cf_864"=>"Armado de Clinica General","cf_870"=>"3 Meses");
        }
        if($operacion==2){
            $arra=array('assetname'=>$productname,'serialnumber'=>$serieBI,'assetstatus'=>$estadoAsset,'product'=>$productid,$lote=>'Set',$fingreso=>$ingreso,$BodAsset=>$bodega,$SlotAsset=>$slotcodigo,$SeccAsset=>$seccion, $RackAsset=>$rack,"account"=>"11x132743","contact"=>"12x203167","cf_864"=>"Armado de Clinica General","cf_870"=>"3 Meses");
        }
    } 
   
    if (strpos($url, 'opfdemo') !== false) {
        if($operacion==1){
            $arra=array('assetname'=>$productname,'serialnumber'=>$serieBI,'assetstatus'=>$estadoAsset,'product'=>$productid,$lote=>'Individual',$cantasset=>'0',$fingreso=>$ingreso,$BodAsset=>$bodega,$SlotAsset=>$slotcodigo,$SeccAsset=>$seccion,$RackAsset=>$rack,"account"=>"11x132743","contact"=>"12x203167","cf_864"=>"Armado de Clinica General","cf_870"=>"3 Meses");
        }
        if($operacion==2){
            $arra=array('assetname'=>$productname,'serialnumber'=>$serieBI,'assetstatus'=>$estadoAsset,'product'=>$productid,$lote=>'Set',$fingreso=>$ingreso,$BodAsset=>$bodega,$SlotAsset=>$slotcodigo,$SeccAsset=>$seccion, $RackAsset=>$rack,"account"=>"11x132743","contact"=>"12x203167","cf_864"=>"Armado de Clinica General","cf_870"=>"3 Meses");
        }
    }
    if (strpos($url, 'aquaplants') !== false) {
        if($operacion==1){
            $arra=array('assetname'=>$productname,'serialnumber'=>$serieBI,'assetstatus'=>$estadoAsset,'product'=>$productid,$lote=>'Individual',$cantasset=>'0',$fingreso=>$ingreso,$BodAsset=>$bodega,$SlotAsset=>$slotcodigo,$SeccAsset=>$seccion,$RackAsset=>$rack);
        }
        if($operacion==2){
            $arra=array('assetname'=>$productname,'serialnumber'=>$serieBI,'assetstatus'=>$estadoAsset,'product'=>$productid,$lote=>'Set',$fingreso=>$ingreso,$BodAsset=>$bodega,$SlotAsset=>$slotcodigo,$SeccAsset=>$seccion, $RackAsset=>$rack);
        }
    }
    if (strpos($url, 'solucorp') !== false) {
        if($operacion==1){
            $arra=array('assetname'=>$productname,'serialnumber'=>$serieBI,'assetstatus'=>$estadoAsset,'product'=>$productid,$lote=>'Individual',$cantasset=>'0',$fingreso=>$ingreso,$BodAsset=>$bodega,$SlotAsset=>$slotcodigo,$SeccAsset=>$seccion,$RackAsset=>$rack,"account"=>"11x132743","contact"=>"12x203167","cf_864"=>"Armado de Clinica General","cf_870"=>"3 Meses");
        }
        if($operacion==2){
            $arra=array('assetname'=>$productname,'serialnumber'=>$serieBI,'assetstatus'=>$estadoAsset,'product'=>$productid,$lote=>'Set',$fingreso=>$ingreso,$BodAsset=>$bodega,$SlotAsset=>$slotcodigo,$SeccAsset=>$seccion, $RackAsset=>$rack,"account"=>"11x132743","contact"=>"12x203167","cf_864"=>"Armado de Clinica General","cf_870"=>"3 Meses");
        }
    } 


    return $arra;
}


function stock($stock){
    $stock=explode(".",$stock);
    return $stock[0];
}

function username($usuario,$url){
    $include=includec($url);
    include ($include);
    $query=mysqli_query($link,"SELECT *FROM vtiger_users where id='$usuario'");
    $data= mysqli_fetch_array($query);  
    $name=$data['user_name'];
    return $name;
}


function DateApp($cdate){
    $meses = array("ene"=>"01", "feb"=>"02", "mar"=>"03", "abr"=>"04", "may"=>"05", "jun"=>"06", "jul"=>"07", "ago"=>"08", "sept"=>"09", "oct"=>"10", "nov"=>"11", "dic"=>"12"); 
    $mesesAnd = array("ene."=>"01", "feb."=>"02", "mar."=>"03", "abr."=>"04", "may."=>"05", "jun."=>"06", "jul."=>"07", "ago."=>"08", "sept."=>"09", "oct."=>"10", "nov."=>"11", "dic."=>"12"); 
    $mes=explode(" ", $cdate);
    $mest=$mes[1];
    if (strpos($mest,'.') !== false) {        
        $mesN=$mesesAnd[$mest];        
    }else{        
        $mesN=$meses[$mest];
    }
    
    $cdate=$mes[2]."-".$mesN."-".$mes[0];
    return $cdate;    
}

/*function caja_productos($cajaid,$url){
        $include=includec($url);
        include ($include);

        $query=mysqli_query($link,"SELECT *FROM vtiger_paquetes WHERE paquetesid='$cajaid'");

        $data=mysqli_fetch_array($query);
        $oc=$data['paquetes_tks_ordendecompra'];
        $os=$data['paquetes_tks_ordendesalida'];
    
        if (!empty($oc)) {
            $query=mysqli_query($link,"SELECT paquetesid 
                FROM vtiger_paquetes 
                INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_paquetes.paquetesid 
                WHERE vtiger_paquetes.paquetes_tks_ordendecompra='$oc' AND deleted='0'  AND paquetesid<>'$cajaid' ORDER BY createdtime DESC LIMIT 1");
            $num=mysqli_num_rows($query);
            if($num>0){
                $cajan=$cajaid;
                $data=mysqli_fetch_array($query);
                $cajaid=$data['paquetesid'];
                $query=mysqli_query($link,"SELECT productid, concat((cantidad-recibido),'.00') as 'quantity' FROM caja_productos where cajaid='$cajaid' AND estado='2'");
                $cajaid=$cajan;
                   $num=mysqli_num_rows($query);
            }else{    
                $query=mysqli_query($link,"SELECT vtiger_products.productid,quantity
                FROM vtiger_inventoryproductrel
                INNER JOIN vtiger_products ON vtiger_products.productid=vtiger_inventoryproductrel.productid
                WHERE id='$oc'");
                $num=mysqli_num_rows($query);
            }
        }
        if (!empty($os)) {
            $query=mysqli_query($link,"SELECT paquetesid 
                FROM vtiger_paquetes 
                INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_paquetes.paquetesid 
                WHERE vtiger_paquetes.paquetes_tks_ordendesalida='$os' AND deleted='0'  AND paquetesid<>'$cajaid'  ORDER BY createdtime DESC LIMIT 1");
            $num=mysqli_num_rows($query);
            if($num>0){
                $cajan=$cajaid;
                $data=mysqli_fetch_array($query);
                $cajaid=$data['paquetesid'];
                $query=mysqli_query($link,"SELECT productid, concat((cantidad-recibido),'.00') as 'quantity' FROM caja_productos where cajaid='$cajaid' AND estado='2'");
                $cajaid=$cajan;
                   $num=mysqli_num_rows($query);
            }else{    

                $query=mysqli_query($link,"SELECT vtiger_products.productid,quantity
                FROM vtiger_inventoryproductrel
                INNER JOIN vtiger_products ON vtiger_products.productid=vtiger_inventoryproductrel.productid
                WHERE id='$os'");
                $num2=mysqli_num_rows($query);
            }
        }    
        while ($row = mysqli_fetch_array($query)) {
            $productid=$row['productid'];
            $qtyinstock=$row['quantity'];
            $stock=explode(".", $qtyinstock);
            $qtyinstock=$stock[0];            
            mysqli_query($link,"INSERT INTO caja_productos VALUES ('$cajaid','$productid','$qtyinstock','0','0','0','0')");       
        }
        $return=$cajaid."-".$oc."-".$num."--".$num2;
        return $return;
}*/



function caja_productos($cajaid,$url){
        $cajan=$cajaid;
        $include=includec($url);
        include ($include);

        $query=mysqli_query($link,"SELECT *FROM vtiger_paquetes WHERE paquetesid='$cajaid'");

        $data=mysqli_fetch_array($query);
        $oc=$data['paquetes_tks_ordendecompra'];
        $os=$data['paquetes_tks_ordendesalida'];

        if(empty($os)){
            $os=$oc;
            $campoquery="vtiger_paquetes.paquetes_tks_ordendecompra";
        }else{
            $os=$os;
            $campoquery="vtiger_paquetes.paquetes_tks_ordendesalida";
        }

/*        if (1==1) {
            $query=mysqli_query($link,"SELECT paquetesid 
                FROM vtiger_paquetes
                INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_paquetes.paquetesid 
                WHERE ".$campoquery."='$os' AND deleted='0'  AND paquetesid<>'$cajaid'  ORDER BY createdtime DESC LIMIT 1");
            $num=mysqli_num_rows($query);
            if($num>0){
                $cajan=$cajaid;
                $data=mysqli_fetch_array($query);
                $cajaid=$data['paquetesid'];
        error_log("CAJA PROD: cajaquery: ".$cajaid."--OS/OC".$os." -- CAJALLEGA:".$cajan."\n", 3, "php.log");
                $query=mysqli_query($link,"SELECT productid,cantidad,  concat((cantidad-recibido),'.00') as 'quantity', estado FROM caja_productos where cajaid='$cajaid'");
                $a=0;
                while ($row = mysqli_fetch_array($query)) {
                    $productid=$row['productid'];
                    $qtyinstock=$row['quantity'];
                    $cantidad=$row['cantidad'];
                    $estado=$row['estado'];
                    $stock=explode(".", $qtyinstock);
                    $qtyinstock=$stock[0];
                    $arraycaja[$a]['producto']=$productid;
                    $arraycaja[$a]['qty']=$qtyinstock;
                    $arraycaja[$a]['cantidad']=$cantidad;
                    $arraycaja[$a]['estado']=$estado;
                    $a++;
                }

                $query=mysqli_query($link,"SELECT vtiger_products.productid,quantity
                FROM vtiger_inventoryproductrel
                INNER JOIN vtiger_products ON vtiger_products.productid=vtiger_inventoryproductrel.productid
                WHERE id='$os'");
                $a=0;
                while ($row = mysqli_fetch_array($query)) {
                    $productid=$row['productid'];
                    $qtyinstock=$row['quantity'];
                    $stock=explode(".", $qtyinstock);
                    $qtyinstock=$stock[0];
                    $arrayos[$a]['producto']=$productid;
                    $arrayos[$a]['qty']=$qtyinstock;
                    $arrayos[$a]['estado']=0;
                    $a++;
                }


                $countcaja=count($arraycaja);
                $countos=count($arrayos);
        error_log("CAJA PROD: countcaja.".$countcaja." --count os: ".$countos."\n", 3, "php.log");

                    $co=0;
                    while($co<$countos){
                        $producto=$arrayos[$co]['producto'];
                        $cantidad=$arrayos[$co]['qty'];
                        $cc=0;
                        while($cc<=$countcaja){
                            $banencontrado=0;
                            $productosearch=$arraycaja[$cc]['producto'];
                            $cantidadsearch=$arraycaja[$cc]['qty'];
                            $cantidadori=$arraycaja[$cc]['cantidad'];
                            $estadocaja=$arraycaja[$cc]['estado'];
                 error_log("CAJA PROD:CICLO: Producto:".$producto." -- Cantidad:".$cantidad."-- CAJA Prod:".$productosearch." -- cantidad:".$cantidadsearch." -- Cantidad ORI: ".$cantidadori." Estado caja:".$estadocaja."\n", 3, "php.log");
                            if($productosearch==$producto){
                                if($estadocaja!=1){
                                    if($cantidadsearch!=$cantidadori){
                                        //$cantidad=($cantidad-$cantidadori)+$cantidadsearch;
                    $cantidad=$cantidadsearch;
                                    }else{
                                        $cantidad=$cantidadsearch;
                                    }
                                    $arrayfinal[$co]['producto']=$producto;
                                    $arrayfinal[$co]['qty']=$cantidad;
                                    $arrayos[$co]['estado']=0;
                                }else{
                                    $arrayos[$co]['estado']=1;
                                }
                            }
                            $cc++;
                        }
                        $banencontrado=$arrayos[$co]['estado'];
                        if($banencontrado==0){
                            $arrayfinal[$co]['producto']=$producto;
                            $arrayfinal[$co]['qty']=$cantidad;
                        }
                        $co++;
                     }
            }else{

                $query=mysqli_query($link,"SELECT vtiger_products.productid,quantity
                FROM vtiger_inventoryproductrel
                INNER JOIN vtiger_products ON vtiger_products.productid=vtiger_inventoryproductrel.productid
                WHERE id='$os'");
                $a=0;
                while ($row = mysqli_fetch_array($query)) {
                    $productid=$row['productid'];
                    $qtyinstock=$row['quantity'];
                    $stock=explode(".", $qtyinstock);
                    $qtyinstock=$stock[0];
                    $arrayfinal[$a]['producto']=$productid;
                    $arrayfinal[$a]['qty']=$qtyinstock;
                    $a++;
                }
            }
        }*/
        
        /*if (strpos($url, 'hoser') !== false) {
	       $query1=mysqli_query($link,"SELECT * FROM vtiger_inventoryproductrel 
                INNER JOIN vtiger_products ON vtiger_products.productid=vtiger_inventoryproductrel.productid 
                INNER JOIN vtiger_productcf on vtiger_productcf.productid = vtiger_products.productid
                WHERE id='$os' and cf_2957 = 1");
        }else{
	        $query1=mysqli_query($link,"SELECT * FROM vtiger_inventoryproductrel INNER JOIN vtiger_products ON vtiger_products.productid=vtiger_inventoryproductrel.productid  WHERE id='$os'");
        }*/
        if (strpos($url, 'hoser') !== false) {
	       $query1=mysqli_query($link,"SELECT vtiger_inventoryproductrel.productid, SUM(quantity) as 'quantity', SUM(procesado) as 'procesado'
	        FROM vtiger_inventoryproductrel 
	        INNER JOIN vtiger_productcf ON vtiger_productcf.productid=vtiger_inventoryproductrel.productid  
	        WHERE id='$os' and cf_2957 = 1
	        GROUP by productid;");
        }else{
	        $query1=mysqli_query($link,"SELECT vtiger_inventoryproductrel.productid, SUM(quantity) as 'quantity', SUM(procesado) as 'procesado'
	        FROM vtiger_inventoryproductrel 
	        INNER JOIN vtiger_products ON vtiger_products.productid=vtiger_inventoryproductrel.productid  
	        WHERE id='$os'
            GROUP by productid;");
        }
        $i=0;
        while ($row = mysqli_fetch_array($query1)) {
            $productid=$row['productid'];
            $stock=explode('.',$row['quantity']);
            $procesado=$row['procesado'];
            $resta=$stock[0]-$procesado;
            if($resta!=0){
              $arrayfinal[$i]['producto']=$productid;
              $arrayfinal[$i]['qty']=$resta;
              $i++;
            }
        }
	
        $countfinal=count($arrayfinal);
        $arrayfinal = array_values($arrayfinal);
        $f=0;
        while($f<=$countfinal){
            $productid=$arrayfinal[$f]['producto'];
            $qtyinstock=$arrayfinal[$f]['qty'];
            mysqli_query($link,"INSERT INTO caja_productos VALUES ('$cajan','$productid','$qtyinstock','0','0','0','0')");
            $f++;
        }

     @mysqli_query($link,"DELETE FROM caja_productos WHERE productid='0'");

        $return=$cajaid."-".$oc."-".$num."--".$num2;
        return $return;
}






function caja_direccion_od($cajaid,$url){
    $include=includec($url);
    include ($include);

    $query=mysqli_query($link,"SELECT *FROM vtiger_paquetes WHERE paquetesid='$cajaid'");

    $data=mysqli_fetch_array($query);
    $oc=$data['paquetes_tks_ordendecompra'];
    $os=$data['paquetes_tks_ordendesalida'];

    if (!empty($oc)) {
        $query=mysqli_query($link,"SELECT vendorid FROM vtiger_purchaseorder WHERE purchaseorderid='$oc'");
        $data=mysqli_fetch_array($query);
        $vendor=$data['vendorid'];
        mysqli_query($link,"UPDATE vtiger_paquetes SET paquetes_tks_proveedor='$vendor' WHERE paquetesid='$cajaid'");
    }
    if (!empty($os)) {
        $query=mysqli_query($link,"SELECT vtiger_account.accountid,vtiger_salesorder.contactid,ship_street,ship_city,ship_state,ship_country 
            FROM vtiger_salesorder 
            INNER JOIN vtiger_account ON vtiger_account.accountid=vtiger_salesorder.accountid 
            INNER JOIN vtiger_soshipads ON vtiger_soshipads.soshipaddressid=vtiger_salesorder.salesorderid
            LEFT JOIN vtiger_contactdetails ON vtiger_contactdetails.contactid=vtiger_salesorder.contactid
            WHERE salesorderid='$os'");
        $data=mysqli_fetch_array($query);
        $cuenta=$data['accountid'];
        $contacto=$data['contactid'];
        $direccion=mysqli_real_escape_string($link, $data['ship_street']);
        $comuna=mysqli_real_escape_string($link, $data['ship_city']);
        $region=mysqli_real_escape_string($link, $data['ship_state']);
        $pais=mysqli_real_escape_string($link, $data['ship_country']);            
        mysqli_query($link,"UPDATE vtiger_paquetes   SET paquetes_tks_cuenta='$cuenta', paquetes_tks_contacto='$contacto'  WHERE paquetesid='$cajaid'");   
        $direccionc=diccionario($url,'DirCaja');
        $comunac=diccionario($url,'ComCaja');
        $regionc=diccionario($url,'RegCaja');
        $paisc=diccionario($url,'PaiCaja');        
        mysqli_query($link,"UPDATE vtiger_paquetescf SET ".$direccionc."='$direccion', ".$comunac."='$comuna',".$regionc."='$region', ".$paisc."='$pais'  WHERE paquetesid='$cajaid' ");


    }
}
function checkslot($slotcode,$url){
    $include=includec($url);
    include ($include);     
    $query=mysqli_query($link,"SELECT slots_tks_producto, slots_tks_cantidad
    FROM vtiger_slots 
    INNER JOIN vtiger_slotscf ON vtiger_slots.slotsid=vtiger_slotscf.slotsid 
    INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_slots.slotsid
    WHERE deleted='0' AND slots_tks_codigo='$slotcode'");
    $num=mysqli_num_rows($query);
    if($num<=0){
        $docs[0]=array('Result'=>'3', 'id'=>$slot);
        return json_encode($docs);              
    }else if($num>0){
        $data=mysqli_fetch_array($query);  
        $producto=$data['slots_tks_producto'];
        $cantidad=$data['slots_tks_cantidad'];
        if(((!empty($producto))&&($cantidad>0))){
            $docs[0]=array('Result'=>'2', 'id'=>$slot);
            return json_encode($docs);
        }else{
            return 1;
        }   
    }    
}



 function contabilizastock($entityId,$reservado,$url,$osoc=null){
    error_log("INICIO contabilizastock-> entityId: ".$entityId." Reservado: ".$reservado." URL: ".$url."\n", 3, "Stock.log");
    $include=includec($url);
    include ($include);
    $campo=diccionario($url,'MovAsset');
    $query=mysqli_query($link, "SELECT movimientos_tks_tipo,movimientos_tks_cantidad,movimientos_tks_slot,assetsid,productid,qtyinstock, movimientos_tks_ordendecompra, movimientos_tks_ordendesalida
        FROM vtiger_movimientos 
        INNER JOIN vtiger_movimientoscf ON vtiger_movimientoscf.movimientosid=vtiger_movimientos.movimientosid
        INNER JOIN vtiger_assets ON vtiger_assets.assetsid=vtiger_movimientos.".$campo."
        INNER JOIN vtiger_products ON vtiger_products.productid=vtiger_assets.product
        WHERE vtiger_movimientos.movimientosid='$entityId'");
    $data=mysqli_fetch_array($query);
    $tipo=$data['movimientos_tks_tipo'];
    $cantidad=$data['movimientos_tks_cantidad'];
    $slot=$data['movimientos_tks_slot'];
    $producto=$data['productid'];
    $qtyprod=$data['qtyinstock'];
	$os=$data['movimientos_tks_ordendesalida'];
    $oc=$data['movimientos_tks_ordendecompra'];
    $assetid=$data['assetsid'];
    $campot=diccionario($url,'traslados');   
    $querytraslado=mysqli_query($link, "SELECT * FROM vtiger_salesordercf WHERE salesorderid='$os' AND ".$campot."='1'");
    $numt=mysqli_num_rows($querytraslado);
    
    error_log(" DATA->contabilizastock-> Tipo: ".$tipo." Cantidad Mov: ".$cantidad." Slot: ".$slot." Producto: ".$producto." StockActual: ".$qtyprod." Campotraslado ".$campot." Traslado?".$numt."\n", 3, "Stock.log");
if($tipo=='Entrada'){
//If para SOLUCORP, con temas de conversion y stock por cajas y unidades
    if (strpos($url, 'solucorp') !== false) {
        $oc=explode("x",$osoc);
        $oc=$oc[1];
        error_log("Entra a Solucorp --  OS:".$oc."\n", 3, "Solucorp.log");
        $stock2=diccionario($url,'Stock2');
        $lote2=diccionario($url,'CantidadLote2');
        $qtyalmacen=diccionario($url,'QtyAlmacenamiento');
        error_log("CAMPOS ".$stock2."--".$lote2."\n", 3, "Solucorp.log");
        $queryconv=mysqli_query($link, "SELECT quantity, quantity_storage FROM vtiger_inventoryproductrel WHERE id='$oc'");
        $dataconv=mysqli_fetch_array($queryconv);
        $qty=explode(".",$dataconv['quantity']);
        $unidad=$dataconv['quantity_storage'];
        $conversion=($unidad/$qty[0])*$cantidad;
        error_log("DATOS".$qty[0]."--".$unidad."--".$conversion."\n", 3, "Solucorp.log");
        
        $queryasset=mysqli_query($link, "SELECT ".$lote2." as 'qtyprod', ".$stock2." as 'stock2', qtyinstock
        FROM vtiger_assetscf
        INNER JOIN vtiger_assets ON vtiger_assets.assetsid=vtiger_assetscf.assetsid
        INNER JOIN vtiger_products ON vtiger_products.productid=vtiger_assets.product
        INNER JOIN vtiger_productcf ON vtiger_products.productid=vtiger_productcf.productid
        WHERE vtiger_assets.assetsid='$assetid'");
        
        $dtasset=mysqli_fetch_array($queryasset);
        $qtyprod=$dtasset['qtyprod'];       //Cantidad de Producto Asset
        $qtystock2=NumerosNegativo($dtasset['qtyinstock']+$conversion, $producto, "qtyinstock", $url);     //Stock en Unidad de Almacenamiento	Producto
        $stockprod=NumerosNegativo($dtasset['stock2']+$cantidad, $producto,"stock2",$url);  // Stock Producto
        $conversion=NumerosNegativo($qtyprod+$conversion, $producto,"conversion", $url);
        $factor=$unidad/$qty[0];
        mysqli_query($link, "UPDATE vtiger_assetscf SET ".$lote2."='$conversion', ".$qtyalmacen."='$factor' WHERE assetsid='$assetid'");
        mysqli_query($link, "UPDATE vtiger_products SET qtyinstock='$qtystock2' WHERE productid='$producto'");
        mysqli_query($link, "UPDATE vtiger_productcf SET ".$stock2."='$stockprod' WHERE productid='$producto'");
    }else{
        if($numt<=0){
            $datelog=date('Y-m-d H:i:s');
        	$cantidadped=diccionario($url,'cantidadped');
        	$cantidadproces=diccionario($url,'cantidadproces');
    	    $query=mysqli_query($link,"SELECT qtyinstock,".$cantidadped." as 'cantidadped', ".$cantidadproces." as 'cantidadproces' 
        	FROM vtiger_products 
        	INNER JOIN vtiger_productcf ON vtiger_productcf.productid=vtiger_products.productid
    	    WHERE vtiger_products.productid='$producto'");
    	    $data=mysqli_fetch_array($query);
    	    
    	    error_log(" Entrada ".$datelog."->contabilizastock-> Stock Antes: Stock".$data['qtyinstock']." CantidadPedida: ".$data['cantidadped']." CantidadProceso: ".$data['cantidadproces']."\n", 3, "Stock.log");
    	    
        	$cantprod=NumerosNegativo($data['qtyinstock']+$cantidad, $producto,"qtyinstock", $url);
        	$cantped=NumerosNegativo($data['cantidadped']-$cantidad, $producto,"cantidadped",$url);
    	    $cantprod2=NumerosNegativo($data['cantidadproces']-$cantidad, $producto,"cantidadproces",$url);
    	    
        	error_log(" Entrada->contabilizastock-> NuevoStock: ".$cantprod." CantidadPedida: ".$cantped." CantidadProceso: ".$cantprod2."\n", 3, "Stock.log");
        	error_log(" EntradaFields->contabilizastock-> CantidadPedida: ".$cantidadped." CantidadProceso: ".$cantidadproces."\n", 3, "Stock.log");
    	    //mysqli_query($link, "UPDATE vtiger_products SET ".$cantidadped."='$cantped' WHERE productid='$producto'");
            mysqli_query($link, "UPDATE vtiger_products SET qtyinstock='$cantprod' WHERE productid='$producto'");
            mysqli_query($link, "UPDATE vtiger_productcf SET ".$cantidadproces."='$cantprod2' WHERE productid='$producto'");
        }
    }
}


if($tipo=='Salida'){
	if (strpos($url, 'solucorp') !== false) {
        $os=explode("x",$osoc);
        $os=$os[1];
        error_log("Entra a Solucorp --  OS:".$os."\n", 3, "Solucorp.log");
        $stock2=diccionario($url,'Stock2');
        $lote2=diccionario($url,'CantidadLote2');
        $qtyalmacen=diccionario($url,'QtyAlmacenamiento');
        error_log("CAMPOS ".$stock2."--".$lote2."\n", 3, "Solucorp.log");
        $queryconv=mysqli_query($link, "SELECT quantity, quantity_storage FROM vtiger_inventoryproductrel WHERE id='$os'");
        $dataconv=mysqli_fetch_array($queryconv);
        $qty=explode(".",$dataconv['quantity']);
        $unidad=$dataconv['quantity_storage'];
        error_log("DATOS".$qty[0]."--".$unidad."\n", 3, "Solucorp.log");
        
        $queryasset=mysqli_query($link, "SELECT ".$lote2." as 'qtyprod', ".$stock2." as 'stock2', ".$qtyalmacen." as 'conversion',  qtyinstock
        FROM vtiger_assetscf
        INNER JOIN vtiger_assets ON vtiger_assets.assetsid=vtiger_assetscf.assetsid
        INNER JOIN vtiger_products ON vtiger_products.productid=vtiger_assets.product
        INNER JOIN vtiger_productcf ON vtiger_products.productid=vtiger_productcf.productid
        WHERE vtiger_assets.assetsid='$assetid'");
        
        
        $dtasset=mysqli_fetch_array($queryasset);
        $conversion=$dtasset['conversion'];  //Conversion Asset
        $qtyasset=NumerosNegativo($dtasset['qtyprod']-($conversion*$cantidad), $producto, "cantlote", $url);       //Cantidad de Producto Asset
        $qtystock2=NumerosNegativo($dtasset['qtyinstock']-($conversion*$cantidad), $producto, "qtyinstock", $url);     //Stock en Unidad de Almacenamiento	Producto
        $stockprod=NumerosNegativo($dtasset['stock2']-$cantidad, $producto, "stock2", $url);  // Stock Producto
        mysqli_query($link, "UPDATE vtiger_assetscf SET ".$lote2."='$qtyasset' WHERE assetsid='$assetid'");
        mysqli_query($link, "UPDATE vtiger_products SET qtyinstock='$qtystock2' WHERE productid='$producto'");
        mysqli_query($link, "UPDATE vtiger_productcf SET ".$stock2."='$stockprod' WHERE productid='$producto'");
    }else{    
    if($reservado==1){
        	$CantReser=diccionario($url,'CantReser');
            $query=mysqli_query($link,"SELECT ".$CantReser." as 'reservado' FROM vtiger_productcf WHERE productid='$producto'");
            $data=mysqli_fetch_array($query);
            $reserva=NumerosNegativo($data['reservado']-1, $producto, "reserva", $url);
            error_log(" SalidaReserva->contabilizastock-> StockReserva: ".$reserva." CampoReserva: ".$CantReser."\n", 3, "Stock.log");
            mysqli_query($link, "UPDATE vtiger_productcf SET ".$CantReser."='$reserva' WHERE productid='$producto'");
    }else{
            $query=mysqli_query($link,"SELECT qtyinstock FROM vtiger_products WHERE productid='$producto'");
            $data=mysqli_fetch_array($query);
            $cantprod=NumerosNegativo($data['qtyinstock']-$cantidad, $producto, "qtyinstock", $url);
            error_log(" Salida->contabilizastock ".$producto."-> StockNuevo: ".$cantprod."\n", 3, "Stock.log");
            mysqli_query($link, "UPDATE vtiger_products SET qtyinstock='$cantprod' WHERE productid='$producto'");
    	}
	}

  }
error_log("FIN contabilizastock-> entityId: ".$entityId."\n", 3, "Stock.log");
}

 function vacioupdate($varentrada,$varupdate){
    if((empty($varentrada)) || $varentrada==NULL){
        return $varupdate;
    }else{
        return $varentrada;
    }

 }

 function cajarecibeproductos($url,$userid,$cajaid,$productid,$qty,$asset){
    $include=includec($url);
    include ($include);
    $query=mysqli_query($link,"SELECT cantidad,recibido FROM caja_productos WHERE cajaid='$cajaid' AND productid='$productid'  AND estado<>'1'");
    $data=mysqli_fetch_array($query);
    $recibido=$data['recibido'];
    $cantidad=$data['cantidad'];

    $queryc=mysqli_query($link,"SELECT paquetes_tks_ordendecompra , paquetes_tks_ordendesalida, paquetes_tks_tipo FROM vtiger_paquetes WHERE paquetesid='$cajaid'");
    $datac=mysqli_fetch_array($queryc);
    $os=$datac['paquetes_tks_ordendesalida'];
    $oc=$datac['paquetes_tks_ordendecompra'];
    $tipocaja=$datac['paquetes_tks_tipo'];
    
    $qtyori=$qty;
    mysqli_query($link,"INSERT INTO vtiger_crmentityrel VALUES ('$cajaid','Paquetes','$asset','Assets')");
    $qty=$recibido+$qty;
    //if($cantidad>=$qty){
    if($qty>=$cantidad){
        mysqli_query($link,"UPDATE caja_productos SET asset='$asset', recibido='$qty', estado='1' WHERE cajaid='$cajaid' AND productid='$productid'  AND estado<>'1' LIMIT 1");
    }else{
        mysqli_query($link,"UPDATE caja_productos SET asset='$asset', recibido='$qty' WHERE cajaid='$cajaid' AND productid='$productid' LIMIT 1");
    }
    
    $idrel=(empty($os))? $oc:$os;
    if (strpos($url, 'hoser') !== false) {
        $prdrel=mysqli_query($link,"SELECT procesado 
        FROM vtiger_inventoryproductrel 
        INNER JOIN vtiger_productcf on vtiger_productcf.productid =  vtiger_inventoryproductrel.productid 
        WHERE vtiger_inventoryproductrel.id='$idrel' AND vtiger_inventoryproductrel.productid='$productid' and vtiger_productcf.cf_2957 = 1");
    }else{
        $prdrel=mysqli_query($link,"SELECT procesado FROM vtiger_inventoryproductrel WHERE id='$idrel' AND productid='$productid'");
    }
    $datapdrel=mysqli_fetch_array($prdrel);
    $procesado=$datapdrel['procesado']+$qtyori;
    mysqli_query($link,"UPDATE vtiger_inventoryproductrel SET procesado='$procesado' WHERE id='$idrel' AND productid='$productid' limit 1");



    $query=mysqli_query($link,"SELECT * FROM caja_productos WHERE cajaid='$cajaid'");
    $ban=0;
    while ($row = mysqli_fetch_array($query)) {
        $estado=$row['estado'];
        if($estado==0){
            $ban=1;
        }             
    }
    if($ban==0){
        //$date=timezoneuser($url,$userid);
        $date=date('Y-m-d');
       mysqli_query($link,"UPDATE vtiger_paquetes SET paquetes_tks_estado='Finalizada' ,paquetes_tks_fechadecierre='$date' WHERE paquetesid='$cajaid'");
       
       if(strpos($url, 'solucorp') !== false){ 
            UpdateEstadoWMS($usuario, $password, $url,$idrel, 'Finalizado', $tipocaja);
        }
       
       $query=mysqli_query($link,"SELECT paquetes_tks_tipo FROM vtiger_paquetes WHERE paquetesid='$cajaid'");
            $data=mysqli_fetch_array($query);  
            $tipo=$data['paquetes_tks_tipo']; 
            if($tipo=="Entrada"){
             /*   $campo=diccionario($url,'stockfisico');
                $query=mysqli_query($link,"SELECT caja_productos.productid as producto,recibido, '$campo',qtyinstock 
                    FROM caja_productos INNER JOIN vtiger_products ON vtiger_products.productid=caja_productos.productid 
                    INNER JOIN vtiger_productcf ON vtiger_productcf.productid=caja_productos.productid 
                    WHERE cajaid='$cajaid' AND estado <>'0'");
                while ($row = mysqli_fetch_array($query)) {  
                        $producto=$row['producto'];
                        $recibido=$row['recibido'];
                        $stock=$row['qtyinstock'];
                        //$fisico=explode(".",$row[$campo]);
                        $fisico=$fisico+$recibido;                        
                        $stock=$stock+$recibido;
                        mysqli_query($link,"UPDATE vtiger_productcf SET '$campo'='$fisico' WHERE productid='$producto'");
                        mysqli_query($link,"UPDATE vtiger_products SET qtyinstock='$stock' WHERE productid='$producto'");
                }      */  
            }
            if($tipo=="Salida"){
                $query=mysqli_query($link,"SELECT accountid, contactid 
                    FROM vtiger_paquetes 
                    INNER JOIN vtiger_salesorder ON vtiger_salesorder.salesorderid=vtiger_paquetes.paquetes_tks_ordendesalida 
                    WHERE paquetesid='$cajaid'");
                $data=mysqli_fetch_array($query);    
                $cuenta=$data['accountid'];
                $contacto=$data['contactid'];
                //$query=mysqli_query($link,"SELECT asset FROM caja_productos WHERE cajaid='$cajaid'");
                $movasset=diccionario($url,'MovAsset');
                $query=mysqli_query($link,"SELECT ".$movasset. " as movimietoasset
                                FROM vtiger_movimientos
                                INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_movimientos.movimientosid
                                INNER JOIN vtiger_paquetes ON vtiger_paquetes.paquetesid=vtiger_movimientos.movimientos_tks_caja
                                WHERE paquetesid='$cajaid'");
                while ($row = mysqli_fetch_array($query)) {  
                    $asset=$row['movimietoasset'];
                    mysqli_query($link,"UPDATE vtiger_assets SET /*assetstatus='In Service',*/ account='$cuenta', contact='$contacto' WHERE assetsid='$asset'");
                    $salida=diccionario($url,'FSalidaB');
                    $date=date('Y-m-d');
                    mysqli_query($link,"UPDATE vtiger_assetscf SET ".$salida."='$date' WHERE assetsid='$asset'");
                }    

            }

       if(!empty($os)){
            $campoos=diccionario($url,'completadoos');
            mysqli_query($link,"UPDATE vtiger_salesordercf SET ".$campoos."='1' WHERE salesorderid='$os'");                     
       }
       if(!empty($oc)){
        $campooc=diccionario($url,'completadooc');
        mysqli_query($link,"UPDATE vtiger_purchaseordercf SET ".$campooc."='1' WHERE purchaseorderid='$oc'");
       } 
    }
    $return=$campoos;
    return $return;
 }

function cajadevolucion($cajaid,$os,$url,$userid){
    $include=includec($url);
    include ($include);
    $campo=diccionario($url,'traslados');
    $direccionf=diccionario($url,'DirCaja');
    $comunaf=diccionario($url,'ComCaja');
    $regionf=diccionario($url,'$RegCaja');
    $paisf=diccionario($url,'PaiCaja');
    $query=mysqli_query($link,"SELECT *
            FROM vtiger_paquetes 
            INNER JOIN vtiger_paquetescf ON vtiger_paquetes.paquetesid=vtiger_paquetescf.paquetesid 
            INNER JOIN vtiger_salesordercf ON vtiger_salesordercf.salesorderid=vtiger_paquetes.paquetes_tks_ordendesalida 
            INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_paquetes.paquetesid
            WHERE vtiger_paquetes.paquetesid='$cajaid' AND paquetes_tks_tipo='Salida' AND ".$campo."='1'");
        $num=mysqli_num_rows($query);
        if($num>0){
            $data=mysqli_fetch_array($query);            
            $tipo='Entrada';
            $status='Traslado';
            $asignado="19x".$data['smownerid'];
            $bodega=diccionario($url,"Bodegas").$data['paquetes_tks_bodega'];
            $seccion=$data['paquetes_tks_seccion'];
            $slot=$data['paquetes_tks_slot'];            
            $OCOS="6x".$data['paquetes_tks_ordendesalida'];            
            $Nguia=$data['paquetes_tks_noguiaodespacho'];
            $courier=$data['paquetes_tks_centrodecosto'];
            $borigen=diccionario($url,"Bodegas").$data['paquetes_tks_bodegaorigen'];
            $bodestino=diccionario($url,"Bodegas").$data['paquetes_tks_bodegadestino'];
            $aorigen=$data['paquetes_tks_respborigen'];
            $adestino=$data['paquetes_tks_respbdestino'];
            $direccion=$data[$direccionf];
            $comuna=$data[$comunaf];
            $region=$data[$regionf];
            $pais=$data[$paisf];
            $detalles=$data['paquetes_tks_detalles'];
            
            $includenat=includenative($userid,"6CDrYRrL34P05XL",$url);
            chdir($includenat);
            $username=username($userid,$url);
            include_once 'vtwsclib/Vtiger/WSClient.php';
            $userws=diccionario($url,'userws');
            $passws=diccionario($url,'keyws');
            $user = $userws;
            $key  = $passws;
            $url  = $url;
            $client = new Vtiger_WSClient($url);
            $login = $client->doLogin($user, $key);
            if(!$login) {
                echo 'Fallo';
            }else {
                $date_caja=date('Y-m-d');
                $record=$client->doCreate('Paquetes',array('paquetes_tks_noguiaodespacho'=>$Nguia,'paquetes_tks_estado'=>$status,'paquetes_tks_tipo'=>$tipo,'assigned_user_id'=>$asignado,'paquetes_tks_ordendesalida'=>$OCOS,'paquetes_tks_centrodecosto'=>$courier,'paquetes_tks_bodega'=>$bodestino,'paquetes_tks_seccion'=>$seccion,'paquetes_tks_detalles'=>$detalles,'paquetes_tks_bodegaorigen'=>$borigen,'paquetes_tks_bodegadestino'=>$bodestino,'paquetes_tks_respborigen'=>$aorigen,'paquetes_tks_fechadellegadaosa'=>$date_caja,'paquetes_tks_respbdestino'=>$adestino,$direccionf=>$direccion,$comunaf=>$comuna,$regionf=>$region,$paisf=>$pais));
                if ($record) {
                    $recordid = $client->getRecordId($record['id']);   
                    $queryp=mysqli_query($link,"SELECT *FROM caja_productos WHERE cajaid='$cajaid' AND recibido>'0'");
                    $nump=mysqli_num_rows($queryp);
                     while ($row = mysqli_fetch_array($queryp)) {  
                        $producto=$row['productid'];
                        $recibido=$row['recibido'];
                        mysqli_query($link,"INSERT INTO caja_productos VALUES('$recordid','$producto','$recibido','0','0','0','0')");
                     }   
                }else{
                    $recordid=$client->lastError();
                    $recordid=$recordid['code'].$recordid['message'];              
                }
            }
        }
    return $nump;
}

 function timezoneuser($url,$usuario){
    $include=includec($url);
    include ($include);
    $query=mysqli_query($link,"SELECT time_zone FROM vtiger_users WHERE id='$usuario'");
    $data=mysqli_fetch_array($query);
    $timezone=$data['time_zone'];

    $fecha=date('Y-m-d H:i:s');
    $tz = new DateTimeZone($timezone);
    $date = new DateTime($fecha);
    $date->setTimezone($tz);
    return $date->format('Y-m-d H:i:s');
    //return $timezone;
 }


 function update_caja_productos($cajaid,$url,$userid){
    $include=includec($url);
    include ($include);
    $query=mysqli_query($link,"UPDATE caja_productos SET estado='2' WHERE cajaid='$cajaid' AND estado='0'");
    //$date=timezoneuser($url,$userid);
    $date=date('Y-m-d');
  mysqli_query($link,"UPDATE vtiger_paquetes SET paquetes_tks_fechadecierre='$date' WHERE paquetesid='$cajaid'");
 }

 function caja_bodegas($cajaid,$OS,$url){
    $include=includec($url);
    include ($include);
    $OS=explode("x",$OS);
    $OS=$OS[1];
    $campo=diccionario($url,'borigen');
    $query=mysqli_query($link,"SELECT  $campo as 'BodegaOrigen', concat(first_name,' ',last_name) as usuario
        FROM vtiger_salesordercf 
        INNER JOIN vtiger_bodegas ON vtiger_bodegas.bodegasid=vtiger_salesordercf.$campo 
        INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_bodegas.bodegasid 
        INNER JOIN vtiger_users ON vtiger_users.id=vtiger_crmentity.smownerid 
        WHERE salesorderid='$OS'");
    $data=mysqli_fetch_array($query);
    $bo=$data['BodegaOrigen'];
    $uo=$data['usuario'];    
    mysqli_query($link,"UPDATE vtiger_paquetes SET paquetes_tks_cuenta='', paquetes_tks_contacto='', paquetes_tks_bodegaorigen='$bo', paquetes_tks_respborigen='$uo' WHERE paquetesid='$cajaid'");

    $campo=diccionario($url,'bodestino');    
    $query=mysqli_query($link,"SELECT $campo as 'BodegaDestino', concat(first_name,' ',last_name) as usuario,bodegas_tks_direccioncomercial,bodegas_tks_comunacomercial,bodegas_tks_regioncomercial,bodegas_tks_pais
        FROM vtiger_salesordercf 
        INNER JOIN vtiger_bodegas ON vtiger_bodegas.bodegasid=vtiger_salesordercf.$campo
        INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_bodegas.bodegasid 
        INNER JOIN vtiger_users ON vtiger_users.id=vtiger_crmentity.smownerid 
        WHERE salesorderid='$OS'");
    $data=mysqli_fetch_array($query);
    $bod=$data['BodegaDestino'];
    $ud=$data['usuario'];   

    $direccion=$data['bodegas_tks_direccioncomercial'];
    $comuna=$data['bodegas_tks_comunacomercial'];
    $region=$data['bodegas_tks_regioncomercial'];
    $pais=$data['bodegas_tks_pais'];
    mysqli_query($link,"UPDATE vtiger_paquetes SET paquetes_tks_cuenta='', paquetes_tks_contacto='', paquetes_tks_bodegadestino='$bod', paquetes_tks_respbdestino='$ud' WHERE paquetesid='$cajaid'");
    $direccionc=diccionario($url,'DirCaja');
    $comunac=diccionario($url,'ComCaja');
    $regionc=diccionario($url,'RegCaja');
    $paisc=diccionario($url,'PaiCaja');        
    mysqli_query($link,"UPDATE vtiger_paquetescf SET ".$direccionc."='$direccion', ".$comunac."='$comuna',".$regionc."='$region', ".$paisc."='$pais'  WHERE paquetesid='$cajaid' ");
$return=$bo."--".$uo."--".$bod."--".$ud;
return $return;

 }


 function CheckProductRel($productid,$slot,$url){
    $productid=explode("x", $productid);
    $product=$productid[1];
    $slote=explode("x", $slot);
    $slot=$slote[1];
    $include=includec($url);
    include ($include);
    $query=mysqli_query($link,"SELECT *FROM vtiger_crmentityrel WHERE crmid='$slot' AND relcrmid='$product'");
    $num=mysqli_num_rows($query);
    if($num<=0){
        mysqli_query($link,"INSERT INTO vtiger_crmentityrel VALUES ('$slot','Slots','$product','Products')");
    }
 }


function salidaconsignacion($recordid,$url){
    $include=includec($url);
    include ($include);
    $MovAsset=diccionario($url,'MovAsset');    
    $Osfield=diccionario($url,'OsCongField');  
    $OsEstatus=diccionario($url,'OsCongEst');    

    $query=mysqli_query($link,"SELECT movimientosid, ".$MovAsset." as 'Asset'
    FROM vtiger_movimientos
    INNER JOIN vtiger_paquetes ON vtiger_paquetes.paquetesid=vtiger_movimientos.movimientos_tks_caja
    INNER JOIN vtiger_salesordercf ON vtiger_salesordercf.salesorderid=vtiger_paquetes.paquetes_tks_ordendesalida
    WHERE movimientosid=$recordid AND ".$Osfield."='$OsEstatus'");
    $num=mysqli_num_rows($query);
    if($num>=1){
        $data=mysqli_fetch_array($query);
        $asset=$data['Asset'];         
        mysqli_query($link,"UPDATE vtiger_assets SET assetstatus='En Consignacion' WHERE assetsid='$asset'");

        $stockconsignacion=diccionario($url,'stockconsignacion');
        $query2=mysqli_query($link,"SELECT $stockconsignacion as consignacion, product FROM vtiger_productcf
        INNER JOIN vtiger_assets ON vtiger_assets.product=vtiger_productcf.productid
        WHERE assetsid='$asset' AND assetstatus='En Consignacion'");
        $num2=mysqli_num_rows($query2);
        if($num2>0){  
            $data2=mysqli_fetch_array($query2);
            $consignacion=$data2['consignacion'];
            $producto=$data2['product'];
            $consignacion=$consignacion+1;
            mysqli_query($link,"UPDATE vtiger_productcf SET ".$stockconsignacion."='$consignacion' WHERE productid='$producto'");
        }  
    }    
}

function entradadevolucion($recordid,$url,$equipoid){
    $include=includec($url);
    include ($include);
    $MovAsset=diccionario($url,'MovAsset');
    $devolucion=diccionario($url,'OCOSDevo');
    $query=mysqli_query($link,"SELECT movimientosid, $MovAsset as 'Asset', smownerid, account,assetstatus
    FROM vtiger_movimientos
    INNER JOIN vtiger_paquetes ON vtiger_paquetes.paquetesid=vtiger_movimientos.movimientos_tks_caja
    INNER JOIN vtiger_purchaseorder ON vtiger_purchaseorder.purchaseorderid=vtiger_paquetes.paquetes_tks_ordendecompra
    INNER JOIN vtiger_purchaseordercf ON vtiger_purchaseorder.purchaseorderid=vtiger_purchaseordercf.purchaseorderid
    INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_movimientos.movimientosid
    INNER JOIN vtiger_assets ON vtiger_assets.assetsid=vtiger_movimientos.$MovAsset
    WHERE $devolucion>'1' AND movimientosid=$recordid");  
    $num=mysqli_num_rows($query);
    if($num>0){  
        $nuevacuenta=diccionario($url,'accountst');
        $data=mysqli_fetch_array($query);
        $asset=$data['Asset'];
        $usuario=$data['smownerid']; 
        $cuenta=$data['account'];
        $status=$data['assetstatus'];
        history($url,$asset,$usuario,$cuenta,$nuevacuenta);
        $query=mysqli_query($link,"UPDATE vtiger_assets SET account='$nuevacuenta' WHERE assetsid='$asset'");

            $stockconsignacion=diccionario($url,'stockconsignacion');

            $query2=mysqli_query($link,"SELECT ".$stockconsignacion." as 'consignacion', product 
            FROM vtiger_productcf
            INNER JOIN vtiger_assets ON vtiger_assets.product=vtiger_productcf.productid
            WHERE assetsid='$asset'");
            $num2=mysqli_num_rows($query2);
            if($num2>0){  
                $data2=mysqli_fetch_array($query2);
                $consignacion=$data2['consignacion'];
                $producto=$data2['product'];
                $consignacion=$consignacion-1;
                error_log("Equipo: ".$asset."Producto: ".$producto."Consignacion: ".$consignacion."Campo: ".$stockconsignacion."\n", 3, "php.log");
                mysqli_query($link,"UPDATE vtiger_productcf SET ".$stockconsignacion."='$consignacion' WHERE productid='$producto'");
            }  
     }
 }

function history($url,$idasset,$usuario, $vanterior,$nuevacuenta){
    $include=includec($url);
    include ($include);
    $date=date('Y-m-d H:i:s');
    $query=mysqli_query($link,"SELECT *FROM vtiger_modtracker_basic_seq");
    $data=mysqli_fetch_array($query);
    $id=$data['id'];
    $id2=$id+1;
    mysqli_query($link,"UPDATE vtiger_modtracker_basic_seq SET id='$id2'");

    //Adiciona registro creacion en componente
    $date=date('Y-m-d H:i:s');
    $query=mysqli_query($link,"SELECT *FROM vtiger_modtracker_basic_seq");
    $data=mysqli_fetch_array($query);
    $id=$data['id'];
    $id2=$id+1;
    mysqli_query($link,"UPDATE vtiger_modtracker_basic_seq SET id='$id2' ");

    $status='0';
    mysqli_query($link, "INSERT INTO vtiger_modtracker_basic (id,crmid,module,whodid,changedon,status) VALUES ('$id2','$idasset','Assets','$usuario','$date','$status')");
    mysqli_query($link,"INSERT INTO vtiger_modtracker_detail (id, fieldname, prevalue, postvalue) VALUES ('$id2','account','$vanterior','$nuevacuenta')");

}     

/**
     * funcion para setear el json q debe ir a la api de android
     * $datos= array multidimensional con la información
     * $op saber si vienen uno o muchos datos: 1= muchos datos
     */

    function setDataJSON($datos, $op=1)
    {
        error_log("set Data Json: op in funcion ".json_encode($op)."\n", 3, "logs_api.log");
        error_log("set Data Json: datos  ".json_encode($datos)."\n", 3, "logs_api.log");

        if(is_array($datos)){
            error_log("set Data Json <- isarray  ".json_encode($datos)."\n", 3, "logs_api.log");
             //gbco@D35@2020$$ [0 => ['Result' => '1']]
             $data=['settings' => ['success' => '1','message' => 'OK','fields' => obtenerFieldname($datos, $op)], 'data' => $datos];
            //$data["settings"]=[['success'=>'1','messages'=>'OK','fields'=>obtenerFieldname($datos, $op)],['data'=>$datos]];
        }else{
            error_log("set Data Json <- no isarray ".json_encode($datos)."\n", 3, "logs_api.log");
            error_log("set Data Json <- no isarray ".json_encode(is_array($datos))."\n", 3, "logs_api.log");
            $data = ['settings'=>['success'=>'0','messages'=>'fail']];
        }
            error_log("set Data Json <- no isarray ".json_encode($data)."\n", 3, "logs_api.log");
        return $data;
    }

    /**
     * $op= bandera para saber si viene varios datos, si e sun array de arrays con info, o para saber si es un solo valor, una consulta de un solo dato
     */
    function obtenerFieldname($datos, $op)
    {
        $datos = $op==1 ? $datos[0]:$datos;
        return array_keys($datos);
    }
  function UpdateModtrackerBy($record, $user, $url){
        
        
    }


    function NumerosNegativo($dato, $producto, $campo, $url){
        $datoori=$dato;
        if($dato<0){
            $dato=0;
        }
        error_log("Stock Negativo URL: ".$url." --  Campo: ".$campo."-- Dato: ".$datoori." -- Producto: ".$producto."\n", 3, "StockNegativo.log");
        return $dato;
    }




    function UpdateEstadoWMS($usuario, $password, $url,$OCOS,$estado, $tipo){
		$include=includec($url);
        include ($include);
        error_log("UPDATE OS/OC: ".$usuario."--".$password."--".$url."--".$OCOS."--".$estado."--".$tipo."\n", 3, "php.log");
        /*if($tipo=="Entrada"){
            $EstadoWMS=diccionario($url,'EstadoWMS_OC');
            $entidad="5x".$OCOS;
            die();
        }else 
        */if($tipo=="Salida"){
            $EstadoWMS=diccionario($url,'EstadoWMS_OS');    
            $entidad="6x".$OCOS;
            date_default_timezone_set('America/Santiago');
            $date=date('Y-m-d H:i:s');
            $dateUTC  = gmdate('Y-m-d H:i:s'); // hora en UTC
            if($estado=="En Preparacion"){
                $campoFecha=diccionario($url,'F_Preparacion');  
            }
            if($estado=="Finalizado Parcial"){
                $campoFecha=diccionario($url,'F_FinalizadParcial');  
            }
            if($estado=="Finalizado"){
                $campoFecha=diccionario($url,'F_Finalizado');  
            }
            if($estado=="Despachado"){
                $campoFecha=diccionario($url,'F_Despachado');  
            }
       
        
        error_log("UPDATE OS/OC: ".$EstadoWMS."--".$entidad."\n", 3, "php.log");
        /*chdir($includenat);           
        include_once 'vtwsclib/Vtiger/WSClient.php';
        $user = "admin";
        $key  = "udqvkv7ht6noeclo";
        $url  = $url;            
        $client = new Vtiger_WSClient($url); 
        $login = $client->doLogin($user, $key);    
        if(!$login) {
            echo json_encode(setDataJSON('Fallo',1));
        }else {             
            error_log("UPDATE OS/OC: LOGIN"."\n", 3, "php.log");
            $recordInfo = $client->doRetrieve($entidad);  
            error_log("UPDATE OS/OC: Record".print_r($recordInfo,true)."--".$recordInfo[$EstadoWMS]."\n", 3, "php.log");
            $recordInfo[$EstadoWMS]=$estado;
        */    
        mysqli_query($link,"UPDATE vtiger_salesordercf SET $EstadoWMS='$estado' WHERE salesorderid='$OCOS'");
        mysqli_query($link,"UPDATE viger_crmentity SET  modifiedtime='$dateUTC' WHERE crmid='$OCOS'");
        }
        if($estado=="Finalizado Parcial" && $tipo=="Salida"){
                //$estadoos="APROBADO";
                //$recordInfo['sostatus']=$estadoos;
                //$recordInfo['assigned_user_id']="19x1";
                mysqli_query($link,"UPDATE vtiger_salesorder SET sostatus='APROBADO' WHERE salesorderid='$OCOS'");
                mysqli_query($link,"UPDATE viger_crmentity SET smownerid='1', modifiedtime='$dateUTC' WHERE crmid='$OCOS'");
        }
        if($tipo=="Salida"){
            //$recordInfo[$campoFecha]=$date;
            mysqli_query($link,"UPDATE vtiger_salesordercf SET $campoFecha='$date' WHERE salesorderid='$OCOS'");
            mysqli_query($link,"UPDATE viger_crmentity SET  modifiedtime='$dateUTC' WHERE crmid='$OCOS'");
        }
        
        
        /*$recordInfo['productid']=$recordInfo['LineItems'][0]['productid'];
            error_log("UPDATE OS/OC: campo".$recordInfo[$EstadoWMS]."--".$estado."\n", 3, "php.log");
            $record = $client->doUpdate($recordInfo);
            if ($record) {
                error_log("UPDATE OS/OC: OK EXISTOSO"."\n", 3, "php.log");
            }else{
                $recordid=$client->lastError();
                error_log("UPDATE OS/OC: ".print_r($recordid,true)."\n", 3, "php.log");
            }   
        
        }*/
                error_log("ACTUALIAR OS DE LA COLA INICIO ".$estado."--".$tipo."--".$usuario."\n", 3, "php.log");
        if(($estado=="Finalizado Parcial" || $estado=="Finalizado") && $tipo=="Salida"){
            $query=mysqli_query($link,"SELECT osid FROM so_queue_wms WHERE userid='$usuario' ORDER BY position DESC Limit 1");
            $data=mysqli_fetch_array($query);
            $os=$data['osid'];
             error_log("ENTRA A IF COLA INICIO ".$os."\n", 3, "php.log");
            $entidad="6x".$os;
            mysqli_query($link,"UPDATE vtiger_salesorder SET sostatus='Crear caja' WHERE salesorderid='$os'");
            mysqli_query($link,"UPDATE viger_crmentity SET  modifiedtime='$dateUTC' WHERE crmid='$os'");
            //mysqli_query($link,"UPDATE vtiger_salesordercf SET $EstadoWMS='Asignado' WHERE salesorderid='$OCOS'");
            /*$recordInfo = $client->doRetrieve($entidad);
             error_log("DATA COLA INICIO ".print_r($recordInfo,true)."\n", 3, "php.log");
            $estadoos="Crear caja";
            $recordInfo[$EstadoWMS]="Asignado";
            $recordInfo['sostatus']=$estadoos;
            $recordInfo['productid']=$recordInfo['LineItems'][0]['productid'];
            $record = $client->doUpdate($recordInfo);
             if ($record) {
                error_log("UPDATE OS/OC QUE VIENE DE COLA: OK EXISTOSO".$os."\n", 3, "php.log");
            }else{
                $recordid=$client->lastError();
                error_log("UPDATE OS/OC QUE VIENE DE COLA: ".print_r($recordid,true)."\n", 3, "php.log");
            } */
        }
    }

    function UpdateAsignadoWMS($usuario, $password, $url,$OCOS){
        error_log("UPDATE OC: ".$usuario."--".$password."--".$url."--".$OCOS."\n", 3, "php.log");
        $entidad="5x".$OCOS;
        error_log("UPDATE OC: Entidad".$entidad."\n", 3, "php.log");
        chdir($includenat);           
        include_once 'vtwsclib/Vtiger/WSClient.php';
        //$user = username($usuario,$url);
        //$key  = $password;
        $user="admin";
        $key="udqvkv7ht6noeclo";
        $url  = $url;            
        $client = new Vtiger_WSClient($url); 
        $login = $client->doLogin($user, $key);    
        if(!$login) {
            echo json_encode(setDataJSON('Fallo',1));
        }else {             
            error_log("UPDATE OC: LOGIN"."\n", 3, "php.log");
            $recordInfo = $client->doRetrieve($entidad);  
            error_log("UPDATE OC: Record".print_r($recordInfo,true)."--".$recordInfo[$EstadoWMS]."\n", 3, "php.log");
            $recordInfo["assigned_user_id"]="19x".$usuario;
            $recordInfo['productid']=$recordInfo['LineItems'][0]['productid'];
            error_log("UPDATE OC: campo".$recordInfo[$EstadoWMS]."--".$estado."\n", 3, "php.log");
            $record = $client->doUpdate($recordInfo);
            if ($record) {
                error_log("UPDATE OC: OK EXISTOSO"."\n", 3, "php.log");
            }else{
                $recordid=$client->lastError();
                error_log("UPDATE OC: ".print_r($recordid,true)."\n", 3, "php.log");
            }   
        
        }
    }    
      
	  function GestionColas($usuario, $password, $url, $osid){
        error_log("UPDATE OS/OC: ".$usuario."--".$password."--".$url."\n", 3, "php.log");
        $include=includec($url);
        include ($include);
        mysqli_query($link,"DELETE FROM so_queue_wms WHERE userid='$usuario' AND osid='$osid'");
        
        $query=mysqli_query($link,"SELECT osid FROM so_queue_wms WHERE userid='$usuario' ORDER BY position DESC Limit 1");
        $data=mysqli_fetch_array($query);
        $os=$data['osid'];
        //mysqli_query($link,"DELETE FROM so_queue_wms WHERE userid='$usuario' AND osid='$os'");
        //UpdateEstadoWMS($usuario, $password, $url,$os,"En Preparacion", "Salida");
        
    }
    function UpdateAsignadoWMSOT($usuario, $password, $url,$OCOS){
        error_log("UPDATE OS/OC: ".$usuario."--".$password."--".$url."--".$OCOS."\n", 3, "php.log");
        $entidad="6x".$OCOS;
        error_log("UPDATE OS/OC: Entidad".$entidad."\n", 3, "php.log");
        chdir($includenat);           
        include_once 'vtwsclib/Vtiger/WSClient.php';
        $user = username($usuario,$url);
        $key  = $password;
        $url  = $url;            
        $client = new Vtiger_WSClient($url); 
        $login = $client->doLogin($user, $key);    
        if(!$login) {
            echo json_encode(setDataJSON('Fallo',1));
        }else {             
            error_log("UPDATE OS/OC: LOGIN"."\n", 3, "php.log");
            $recordInfo = $client->doRetrieve($entidad);  
            error_log("UPDATE OS/OC: Record".print_r($recordInfo,true)."--".$recordInfo[$EstadoWMS]."\n", 3, "php.log");
            $recordInfo["assigned_user_id"]="19x".$usuario;
            $recordInfo['productid']=$recordInfo['LineItems'][0]['productid'];
            error_log("UPDATE OS/OC: campo".$recordInfo[$EstadoWMS]."--".$estado."\n", 3, "php.log");
            $record = $client->doUpdate($recordInfo);
            if ($record) {
                error_log("UPDATE OS/OC: OK EXISTOSO"."\n", 3, "php.log");
            }else{
                $recordid=$client->lastError();
                error_log("UPDATE OS/OC: ".print_r($recordid,true)."\n", 3, "php.log");
            }   
        
        }    
        
    }





?>

