<?
include("ApiGlobalFunctions.php");

$usuario=isset($_POST['uid']) ? $_POST['uid'] : $_GET['uid'];
$password=isset($_POST['key']) ? $_POST['key'] : $_GET['key'];
$url=isset($_POST['url']) ? $_POST['url'] : $_GET['url'];
$slotID=$_POST['slotID'];
$tipo=$_POST['tipo'];
$producID=$_POST['productCode'];
$cajaID=$_POST['cajaID'];
$os_on_ID=$_POST['os_on_ID'];
$qty=$_POST['qty'];
$serieBI=$_POST['NSerie'];
$operacion=$_POST['Flag'];
$tipoLote=isset($_POST['tipoLote']) ? $_POST['tipoLote']:'';
$valueNuevoReservado=isset($_POST['nuevaReserva']) ? $_POST['nuevaReserva']:'';
$estadoAsset=diccionario($url,'EstadoAsset');  

$caso4='1';

$username=username($usuario,$url);

$include=includec($url);
include ($include);
$lote=diccionario($url,'LoteB');
$cantasset=diccionario($url,'QtyAsset');
$fingreso=diccionario($url,'FIngresoB');
$BodAsset=diccionario($url,'BodAsset');
$SlotAsset=diccionario($url,'SlotAsset');
$SeccAsset=diccionario($url,'SeccAsset');
$RackAsset=diccionario($url,'RackAsset');
$MovAsset=diccionario($url,'MovAsset');
$changeresv=diccionario($url,'ChnReserva');
$reservado=0;

error_log("SLOTINOUT Usuario: ".$usuario."Password: ".$password." URL: ".$url." slotID: ".$slotID." Tipo: ".$tipo." producto: ".$producID." Caja: ".$cajaID." OS: ".$os_on_ID." qty: ".$qty." SerieBI: ".$serieBI." Operacion ".$operacion."-- ESTADO: ".$estadoAsset."-tipoLote--".$tipoLote."--".$valueNuevoReservado."\n", 3, "php.log");
if($valueNuevoReservado!=''){
    cambiarReservas($valueNuevoReservado,$os_on_ID, $url); //cambiar el reservado con alguno ya existente.
}
$query=mysqli_query($link,"SELECT *
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='$slotID'");
$num=mysqli_num_rows($query);
//error_log("SLOTINOUT CHECK SLOT: ".$num."\n", 3, "php.log");
if($num<=0){
    $docs[0]=array('Result'=>'4', 'id'=>$slotID);
    echo json_encode(setDataJSON($docs,1));
}else{
    $asignado="19x".$usuario;
    $query=mysqli_query($link,"SELECT slotsid,slots_tks_codigo, bodegas_tks_nombre, seccionesid, secciones_tks_seccion, racks_tks_rack
    FROM vtiger_slots 
    INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_slots.slotsid  
    INNER JOIN vtiger_bodegas ON vtiger_bodegas.bodegasid=vtiger_slots.slots_tks_bodega
    INNER JOIN vtiger_racks ON vtiger_racks.racksid=vtiger_slots.slots_tks_rack
    INNER JOIN vtiger_secciones ON vtiger_secciones.seccionesid=vtiger_slots.slots_tks_seccion
    WHERE deleted='0' AND slots_tks_codigo='$slotID'");
    $data=mysqli_fetch_array($query);
//    error_log("SLOTINOUT CHECK SLOT V2: ".print_r($data,true)."\n", 3, "php.log");
    $idslot=$data['slotsid'];
    $bodega=$data['bodegas_tks_nombre'];
    $rack=$data['racks_tks_rack'];
    $seccion=$data['seccionesid'];
    $nomseccion=$data['secciones_tks_seccion'];
    $slotcodigo=$data['slots_tks_codigo'];
    $slotID=diccionario($url,"Slots").$data['slotsid'];
    $idcaja=$cajaID;
    $cajaID=diccionario($url,"Paquetes").$cajaID;
    $query=mysqli_query($link,"SELECT *FROM vtiger_crmentity WHERE crmid='$os_on_ID'");
    $data=mysqli_fetch_array($query);  
    $type=$data['setype'];
    if($type=="SalesOrder"){
        $OS="6x".$os_on_ID;
        $OC=NULL;
    }    
    if($type=="PurchaseOrder"){
        $OC="5x".$os_on_ID;
        $OS=NULL;
    }
    $AssetOc=diccionario($url,'AssetOc');
    $campo=diccionario($url,'codproduct');
    
    $query=mysqli_query($link,"SELECT vtiger_products.productid, productname, ".$campo." as codprod,productcategory
    FROM vtiger_products 
    INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_products.productid 
    INNER JOIN vtiger_productcf ON vtiger_products.productid=vtiger_productcf.productid 
    WHERE deleted='0' AND ".$campo."='$producID'");
    $data=mysqli_fetch_array($query);      
//error_log("SLOTINOUT CHECK  PRODUCT:".print_r($data,true)."\n", 3, "php.log");
    $idproducto=$data['productid']; 
    $productid="14x".$data['productid'];   
    $productname=$data['productname'];
    $productcategory=$data['productcategory'];
    $codprod=$data['codprod'];

    $includenat=includenative($usuario,$password,$url);    
    chdir($includenat);   
    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) {
//  error_log("SLOTINOUT  FALLO WS"."\n", 3, "php.log");
    //  echo 'Fallo';
    }else {    
//  error_log("SLOTINOUT  EXITOSO WS".$tipo."--".$operacion."\n", 3, "php.log");
        if($tipo=="Entrada"){
            if (strpos($url, 'hoser') !== false) {
                $query = mysqli_query($link, "SELECT * FROM vtiger_purchaseordercf p WHERE p.purchaseorderid = '$os_on_ID' ");
                $data=mysqli_fetch_array($query);
                $DestinadoA = $data['cf_2813'];
            } 

/*            $query=mysqli_query($link,"SELECT slots_tks_producto,slots_tks_cantidad
            FROM vtiger_slots 
            INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_slots.slotsid  
            WHERE deleted='0' AND slotsid='$idslot'");   
            $data=mysqli_fetch_array($query);
            $producto=$data['slots_tks_producto'];
            $cantidad=$data['slots_tks_cantidad'];            */
            $ingreso=date('Y-m-d');
//      error_log("SLOTINOUT CHECK ENRTADA: ".$tipo."-".$operacion."\n", 3, "php.log");

            if ($operacion==1){
                if(empty($serieBI)){
                   $serieBI="X";                    
                }
               
                if (strpos($url, 'hoser') !== false) {
                    //$record=$client->doCreate('Assets',array('assetname'=>$productname,'serialnumber'=>$serieBI,'assetstatus'=>$estadoAsset,'product'=>$productid,'assigned_user_id'=>$asignado,$lote=>'Individual',$cantasset=>'0',$fingreso=>$ingreso,$BodAsset=>$bodega,$SlotAsset=>$slotcodigo,$SeccAsset=>$nomseccion,$RackAsset=>$rack,'account'=>'11x354'));                                   
                    $record=$client->doCreate('Assets',array('assetname'=>$productname,'serialnumber'=>$serieBI,'assetstatus'=>$estadoAsset,'product'=>$productid,'assigned_user_id'=>$asignado,$lote=>'Individual',$cantasset=>'0',$fingreso=>$ingreso,$BodAsset=>$bodega,$SlotAsset=>$slotcodigo,$SeccAsset=>$nomseccion,$RackAsset=>$rack,'account'=>'11x354','cf_1935'=>'1',$AssetOc=>$OC,'cf_1943'=>$producID,'cf_2274'=>'SOC.DE INGENIERIA HOGG Y SERRANO LTDA'));                                   
                }
                if (strpos($url, 'siromax') !== false) {                    
                    $record=$client->doCreate('Assets',array('assetname'=>$productname,'serialnumber'=>$serieBI,'assetstatus'=>$estadoAsset,'product'=>$productid,'assigned_user_id'=>$asignado,$lote=>'Individual',$cantasset=>'0',$fingreso=>$ingreso,$BodAsset=>$bodega,$SlotAsset=>$slotcodigo,$SeccAsset=>$nomseccion,$RackAsset=>$rack,'account'=>'11x292','contact'=>'12x113248','cf_864'=>$productcategory,'cf_870'=>'3 Meses','cf_2070'=>'1',$AssetOc=>$OC,'cf_2074'=>$producID));
                }
		if (strpos($url, 'opfdemo') !== false) {
			$record=$client->doCreate('Assets',array('assetname'=>$productname,'serialnumber'=>$serieBI,'assetstatus'=>$estadoAsset,'product'=>$productid,'assigned_user_id'=>$asignado,$lote=>'Individual',$cantasset=>'0',$fingreso=>$ingreso,$BodAsset=>$bodega,$SlotAsset=>$slotcodigo,$SeccAsset=>$nomseccion,$RackAsset=>$rack,'account'=>'11x354',$AssetOc=>$OC,'cf_2074'=>$producID));
		}	
                if ($record){                    
                    $assetid = $client->getRecordId($record['id']);
                    if($serieBI=="X"){
                        $serieBI='E'.$assetid;
                        mysqli_query($link,"UPDATE vtiger_assets SET serialnumber='$serieBI' WHERE assetsid='$assetid'");                  
                    }
                }else{
                    $recordid=$client->lastError();
                    $recordid=$recordid['code'].$recordid['message'];              
                    echo $recordid;                 
                }
                                
            } 
            error_log("SERIE: ".$serieBI." -- RECORD: ".$assetid."-- ERROR: ".$recordid."\n", 3, "php.log");
            if ($operacion==2){
                
                if(empty($serieBI)){
                     $serieBI="X";
                }
                $productname="SET ".$productname;

                if (strpos($url, 'hoser') !== false) {
                    $record=$client->doCreate('Assets',array('assetname'=>$productname,'serialnumber'=>$serieBI,'assetstatus'=>$estadoAsset,'product'=>$productid,'assigned_user_id'=>$asignado,$lote=>'Set',$fingreso=>$ingreso,$BodAsset=>$bodega,$SlotAsset=>$slotcodigo,$SeccAsset=>$nomseccion, $RackAsset=>$rack,'account'=>'11x354','cf_1935'=>'1',$AssetOc=>$OC,'cf_1943'=>$producID,'cf_2274'=>'SOC.DE INGENIERIA HOGG Y SERRANO LTDA'));    
                }
                if (strpos($url, 'siromax') !== false) {
                    $record=$client->doCreate('Assets',array('assetname'=>$productname,'serialnumber'=>$serieBI,'assetstatus'=>$estadoAsset,'product'=>$productid,'assigned_user_id'=>$asignado,$lote=>'Set',$fingreso=>$ingreso,$BodAsset=>$bodega,$SlotAsset=>$slotcodigo,$SeccAsset=>$nomseccion, $RackAsset=>$rack,"account"=>"11x292","contact"=>"12x113248","cf_864"=>$productcategory,"cf_870"=>"3 Meses",'cf_2070'=>'1',$AssetOc=>$OC,'cf_2074'=>$producID));
                }     
               if (strpos($url, 'opfdemo') !== false) {
                        $record=$client->doCreate('Assets',array('assetname'=>$productname,'serialnumber'=>$serieBI,'assetstatus'=>$estadoAsset,'product'=>$productid,'assigned_user_id'=>$asignado,$lote=>'Set',$cantasset=>'0',$fingreso=>$ingreso,$BodAsset=>$bodega,$SlotAsset=>$slotcodigo,$SeccAsset=>$nomseccion,$RackAsset=>$rack,'account'=>'11x354',$AssetOc=>$OC,'cf_2074'=>$producID));
                } 
                //$record=$client->doCreate('Assets',$resultadoArray);        
                if ($record) {
                    $assetid = $client->getRecordId($record['id']);                      
                    if($serieBI=="X"){
                        $serieBI='E'.$assetid;
                        mysqli_query($link,"UPDATE vtiger_assets SET serialnumber='$serieBI' WHERE assetsid='$assetid'");                  
                    }  
                }else{
                    $recordid=$client->lastError();
                    $recordid=$recordid['code'].$recordid['message'];              
                    echo $recordid;
                }
            }
            
            if($operacion==3){
                //echo "PRUEBA".$serieBI;
                $sqla=mysqli_query($link,"SELECT vtiger_assets.assetsid
                    FROM vtiger_assets                     
                INNER JOIN vtiger_assetscf ON vtiger_assetscf.assetsid=vtiger_assets.assetsid
                INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_assets.assetsid
                WHERE serialnumber='$serieBI' AND deleted='0'");
                $data=mysqli_fetch_array($sqla); 
                //print_r($data);
                //$qtya=$data['cf_1892'];
                $assetid=$data['assetsid'];        
                //$qtyn=$qtya+$qty;          
                //$qtyn=$qtya;
                //echo $assetid."--".$qtya."--".$qtyn."--".$ingreso."--".$bodega."--".$slotcodigo;                      
                mysqli_query($link,"UPDATE vtiger_assetscf SET /*cf_1892='$qtyn',*/ ".$fingreso."='$ingreso', ".$lote."='Set', ".$BodAsset."='$bodega', ".$SlotAsset."='$slotcodigo',".$SeccAsset."='$nomseccion',".$RackAsset."='$rack' WHERE assetsid='$assetid'");
                mysqli_query($link,"UPDATE vtiger_assets SET assetstatus='".$estadoAsset."' WHERE assetsid='$assetid'");
                
            }

            //error_log("Operacion: ".$operacion."\n", 3, "php.log");
            if($operacion==4){
                //$caso4=0;
            //error_log("Operacion: ".$operacion."\n", 3, "php.log");
                $query1=mysqli_query($link,"SELECT *
                        FROM vtiger_paquetes
                        INNER JOIN vtiger_paquetescf ON vtiger_paquetes.paquetesid=vtiger_paquetescf.paquetesid
                        INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_paquetes.paquetesid
                        WHERE deleted='0' AND vtiger_paquetes.paquetesid='$idcaja'");
                $data1=mysqli_fetch_array($query1);                 
                $OScaja1=$data1['paquetes_tks_ordendesalida'];
    //  error_log("SLOTINOUT: ".$OScaja1."\n", 3, "php.log");
                $query4=mysqli_query($link,"SELECT assetsid
                        FROM vtiger_paquetes
                        INNER JOIN vtiger_paquetescf ON vtiger_paquetes.paquetesid=vtiger_paquetescf.paquetesid
                        INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_paquetes.paquetesid
                        INNER JOIN vtiger_movimientos ON vtiger_movimientos.movimientos_tks_caja=vtiger_paquetes.paquetesid
                        INNER JOIN vtiger_assets ON vtiger_assets.assetsid=vtiger_movimientos.".$MovAsset."
                        WHERE deleted='0' AND vtiger_paquetes.paquetes_tks_ordendesalida='$OScaja1' AND serialnumber='$serieBI'");
                $num4=mysqli_num_rows($query4);
    //   error_log("SLOTINOUT: ".$num4." -".$OScaja1."-".$serieBI."\n", 3, "php.log");
                if($num4>=1){
            
                    $data4=mysqli_fetch_array($query4);                     
                    $assetid=$data4['assetsid'];  
                    $caso4='4';                    
                    mysqli_query($link,"UPDATE vtiger_assetscf SET ".$fingreso."='$ingreso', ".$BodAsset."='$bodega', ".$SlotAsset."='$slotcodigo',".$SeccAsset."='$nomseccion',".$RackAsset."='$rack' WHERE assetsid='$assetid'");
                    mysqli_query($link,"UPDATE vtiger_assets SET assetstatus='".$estadoAsset."' WHERE assetsid='$assetid'");
                }else{
                    $caso4='0';
                    
                }
          //      error_log("Operacion: ".$operacion." OSCAJA: ".$OScaja1." Validacion: ".$num4." Asset: ".$assetsid." CASO: ".$caso4."\n", 3, "php.log");
            }
if($operacion==5){
                
                if(empty($serieBI)){
                    $serieBI="X";
                    $productname="PALLET ".$productname; 
                  
                    if (strpos($url, 'hoser') !== false) {
                    $record=$client->doCreate('Assets',array('assetname'=>$productname,'serialnumber'=>$serieBI,'assetstatus'=>$estadoAsset,'product'=>$productid,'assigned_user_id'=>$asignado,$lote=>'Pallet',$fingreso=>$ingreso,$BodAsset=>$bodega,$SlotAsset=>$slotcodigo,$SeccAsset=>$nomseccion, $RackAsset=>$rack,'account'=>'11x354','cf_1935'=>'1',$AssetOc=>$OC,'cf_1943'=>$producID,$cantasset=>$qtyn,'cf_2274'=>'SOC.DE INGENIERIA HOGG Y SERRANO LTDA'));
                }
                if (strpos($url, 'siromax') !== false) {
                    $record=$client->doCreate('Assets',array('assetname'=>$productname,'serialnumber'=>$serieBI,'assetstatus'=>$estadoAsset,'product'=>$productid,'assigned_user_id'=>$asignado,$lote=>'Pallet',$fingreso=>$ingreso,$BodAsset=>$bodega,$SlotAsset=>$slotcodigo,$SeccAsset=>$nomseccion, $RackAsset=>$rack,"account"=>"11x292","contact"=>"12x113248","cf_864"=>$productcategory,"cf_870"=>"3 Meses",'cf_2070'=>'1',$AssetOc=>$OC,$cantasset=>$qtyn,'cf_2074'=>$producID));
                }
                if (strpos($url, 'opfdemo') !== false) {
                        $record=$client->doCreate('Assets',array('assetname'=>$productname,'serialnumber'=>$serieBI,'assetstatus'=>$estadoAsset,'product'=>$productid,'assigned_user_id'=>$asignado,$lote=>'Pallet',$cantasset=>'0',$fingreso=>$ingreso,$BodAsset=>$bodega,$SlotAsset=>$slotcodigo,$SeccAsset=>$nomseccion,$RackAsset=>$rack,'account'=>'11x354',$AssetOc=>$OC,'cf_2074'=>$producID));
                } 
                    if ($record) {
                      $assetid = $client->getRecordId($record['id']);
                      if($serieBI=="X"){
                        $serieBI='E'.$assetid;
                        mysqli_query($link,"UPDATE vtiger_assets SET serialnumber='$serieBI' WHERE assetsid='$assetid'");
                      }
                    }else{
                      $recordid=$client->lastError();
                      $recordid=$recordid['code'].$recordid['message'];
                      echo $recordid;
                    }
                
                }else{
                    $sqla=mysqli_query($link,"SELECT vtiger_assets.assetsid
                    FROM vtiger_assets                     
                    INNER JOIN vtiger_assetscf ON vtiger_assetscf.assetsid=vtiger_assets.assetsid
                    INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_assets.assetsid
                    WHERE serialnumber='$serieBI' AND deleted='0'");
                    $data=mysqli_fetch_array($sqla); 
                    $assetid=$data['assetsid'];        
                    mysqli_query($link,"UPDATE vtiger_assetscf SET ".$cantasset."='$qtyn', ".$fingreso."='$ingreso', ".$lote."='Pallet', ".$BodAsset."='$bodega', ".$SlotAsset."='$slotcodigo',".$SeccAsset."='$nomseccion',".$RackAsset."='$rack' WHERE assetsid='$assetid'");
                    mysqli_query($link,"UPDATE vtiger_assets SET assetstatus='".$estadoAsset."' WHERE assetsid='$assetid'");
               } 
            }
            if($caso4>='1'){

                $sqla=mysqli_query($link,"SELECT vtiger_assets.assetsid
                    FROM vtiger_assets                     
                INNER JOIN vtiger_assetscf ON vtiger_assetscf.assetsid=vtiger_assets.assetsid
                INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_assets.assetsid
                WHERE serialnumber='$serieBI' AND deleted='0'");
                $data=mysqli_fetch_array($sqla); 
                $assetid=$data['assetsid'];        
                $equipoid=$assetid;
                $assetid="28x".$assetid;

                error_log("Operacion: ".$operacion." -- ASSET: ".$assetid."\n", 3, "php.log");
                $record=$client->doCreate('Movimientos',array('movimientos_tks_tipo'=>$tipo,'movimientos_tks_cantidad'=>$qty,'movimientos_tks_slot'=>$slotID,'movimientos_tks_producto'=>$producID,'movimientos_tks_ordendecompra'=>$OC,'movimientos_tks_ordendesalida'=>$OS,'movimientos_tks_caja'=>$cajaID,'assigned_user_id'=>$asignado,$MovAsset=>$assetid));               
                if ($record) {
                    $recordid = $client->getRecordId($record['id']);        
                    $docs[0]=array('Result'=>'1', 'id'=>$recordid);
                    //error_log("url: ".$url." Caja: ".$idcaja." Product: ".$productid." Cantidad: ".$qty."\n", 3, "php.log");
                    
                    $query=mysqli_query($link,"SELECT ".$cantasset." As cantasset
                    FROM vtiger_assets                     
                    INNER JOIN vtiger_assetscf ON vtiger_assetscf.assetsid=vtiger_assets.assetsid
                    WHERE vtiger_assets.assetsid='$equipoid'");                    
                    $data= mysqli_fetch_array($query);   
                    $qtyslot=$data['cantasset'];           
                    $qtyasset=$qtyslot+$qty;
                    mysqli_query($link,"UPDATE vtiger_assetscf SET ".$cantasset."='$qtyasset' WHERE assetsid='$equipoid'");
                    
                    if($operacion==1 || $operacion==2){
                        //enviaremailasset($usuario,$url,$equipoid);
                    }

                    mysqli_query($link,"INSERT INTO vtiger_crmentityrel VALUES('$idslot','Slots','$equipoid','Assets')");
                    mysqli_query($link,"INSERT INTO vtiger_crmentityrel VALUES('$recordid','Movimientos','$equipoid','Assets')");
                    //CheckProductRel($idproducto,$slotID,$url);
                    cajarecibeproductos($url,$usuario,$idcaja,$idproducto,$qty,$equipoid);
                    contabilizastock($recordid,$reservado,$url);
                    entradadevolucion($recordid,$url,$equipoid);
					if (strpos($url, 'hoser') !== false) { //estos -- -- -- -- updates son solo para hoser.
                        mysqli_query($link,"UPDATE vtiger_assetscf SET cf_1931='".$DestinadoA."' WHERE assetsid='$equipoid'");
                    }
                    echo json_encode(setDataJSON($docs,1));          
                }else{
                    $recordid=$client->lastError();
                    $docs[0]=array('Result'=>'0', 'id'=>$recordid);
                    echo json_encode(setDataJSON($docs,1));     
                }
            }else{
                $docs[0]=array('Result'=>'5', 'id'=>'NSerie no pertenece a cajaID o os_on_ID');
                    echo json_encode(setDataJSON($docs,1));     
            } 
        }
        if($tipo=="Salida"){
           // echo "SALIDA".$idslot."--".$productid."--".$serieBI;
            $producto=explode("x",$productid);
            $producto=$producto[1];
            $query=mysqli_query($link,"SELECT * FROM vtiger_assets WHERE product='$producto' AND serialnumber='$serieBI'");
            $num=mysqli_num_rows($query);
            if($num>=1){
            $bandera=0;
            $AssetResv=diccionario($url,'AssetResv');
            $EstadoAsset=diccionario($url,'EstadoAsset');
	        $osbi=diccionario($url,'OsBi');
            $OS2=explode("x",$OS);
            if (strpos($url, 'hoser') !== false) { //estos updates son solo para Hoser.
                $queryOS=mysqli_query($link,"SELECT cf_1660 as 'tipoOS' FROM vtiger_salesordercf s INNER JOIN vtiger_crmentity c on c.crmid = s.salesorderid WHERE s.salesorderid='$os_on_ID'");
                $dataOS=mysqli_fetch_array($queryOS);
                $tipoOS=$dataOS['tipoOS'];
                error_log("salidas - OS info -  ".json_encode($queryOS)."\n", 3, "SlotInOut.log");
                error_log("salidas - OS info -  ".json_encode($tipoOS)."\n", 3, "SlotInOut.log");
            }
            $queryresv=mysqli_query($link,"SELECT ".$AssetResv." as 'reserva'
                    FROM vtiger_assets 
                    INNER JOIN vtiger_assetscf ON vtiger_assetscf.assetsid=vtiger_assets.assetsid 
                    INNER JOIN vtiger_crmentity CRM1 ON CRM1.crmid=vtiger_assets.assetsid
                    INNER JOIN vtiger_salesorder ON vtiger_salesorder.salesorderid=vtiger_assetscf.$AssetResv
                    INNER JOIN vtiger_crmentity CRM2 ON CRM2.crmid=vtiger_salesorder.salesorderid
                    WHERE CRM1.deleted='0' AND product='$producto' AND serialnumber='$serieBI' AND CRM2.deleted='0'");
                    $numresv=mysqli_num_rows($queryresv);
echo "num: ".$numresv;
                    if($numresv>0){
                        $data=mysqli_fetch_array($queryresv);
                        //$osreserveada=$data['reserva'];
			if(empty($data['reserva'])){
                              $osreserveada=0;
                        }else{
                           $osreserveada=$data['reserva'];
                          }  
                        error_log("CHECK RESERVAS - NUM: ".$numresv."-- OSRESEV: ".$osreserveada."-- OSCAJA: ".$OS2[1]."-- BANDERA: ".$bandera."\n", 3, "php.log");
			echo "--".$osreserveada."--".$OS2[1];
                     }   
           if($osreserveada>1){
            if($osreserveada==$OS2[1]){
                            $numresv2=1;
	                    $reservado=1;
                        }else{
                            $numresv2=0;
                        }
           }else{
            $querySoAsset=mysqli_query($link,"SELECT *
            FROM vtiger_assets 
                    INNER JOIN vtiger_assetscf ON vtiger_assetscf.assetsid=vtiger_assets.assetsid 
                    INNER JOIN vtiger_crmentity CRM1 ON CRM1.crmid=vtiger_assets.assetsid
                    WHERE CRM1.deleted='0' AND ".$AssetResv."='$OS2[1]' AND assetstatus='$EstadoAsset' AND product = '$producto'");   

		echo "SELECT *
            FROM vtiger_assets 
                    INNER JOIN vtiger_assetscf ON vtiger_assetscf.assetsid=vtiger_assets.assetsid 
                    INNER JOIN vtiger_crmentity CRM1 ON CRM1.crmid=vtiger_assets.assetsid
                    WHERE CRM1.deleted='0' AND ".$AssetResv."='$OS2[1]' AND assetstatus='$EstadoAsset' AND product = '$producto'";
            $numsoAsset=mysqli_num_rows($querySoAsset);
            if($numsoAsset>=1){
                $numresv2=0;
            }else{
                $numresv2=1;
            }
           }
         error_log("CHECK RESERVAS - CONTADOR: ".$numresv2."\n", 3, "php.log");
                    if($numresv2==0){
                        $docs[0]=array('Result'=>'5', 'id'=>'ReservaError');
                        echo json_encode(setDataJSON($docs,1));     
            $bandera=1; 
                    }else{
                        $bandera=0;
            //$reservado=1;
                }
        error_log("CHECK RESERVAS - CONTADOR2: ".$bandera."\n", 3, "php.log");
                if($bandera==0){
                    $query=mysqli_query($link,"SELECT vtiger_assets.assetsid,".$cantasset." as cantasset
                    FROM vtiger_slots 
                    INNER JOIN vtiger_slotscf ON vtiger_slotscf.slotsid=vtiger_slots.slotsid
                    INNER JOIN vtiger_crmentityrel ON vtiger_crmentityrel.crmid=vtiger_slots.slotsid
                    INNER JOIN vtiger_assets ON vtiger_assets.assetsid=vtiger_crmentityrel.relcrmid
                    INNER JOIN vtiger_assetscf ON vtiger_assetscf.assetsid=vtiger_assets.assetsid
                    WHERE vtiger_slots.slotsid='$idslot' AND serialnumber='$serieBI' AND assetstatus='$estadoAsset'");
                    $num=mysqli_num_rows($query);
                    $data= mysqli_fetch_array($query);              
                    if($num>0){
                        $qtyslot=$data['cantasset'];
                        if($qty>$qtyslot){
                           $docs[0]=array('Result'=>'2', 'id'=>'ProductError');
                    echo json_encode(setDataJSON($docs,1));            
                        }else{
                            $assetid="28x".$data['assetsid'];
                            $IDAsset=$data['assetsid'];
                            $record=$client->doCreate('Movimientos',array('movimientos_tks_tipo'=>$tipo,'movimientos_tks_cantidad'=>$qty,'movimientos_tks_slot'=>$slotID,'movimientos_tks_producto'=>$producID,'movimientos_tks_ordendecompra'=>$OC,'movimientos_tks_ordendesalida'=>$OS,'movimientos_tks_caja'=>$cajaID,'assigned_user_id'=>$asignado,$MovAsset=>$assetid));
                            if ($record) {
                                $recordid = $client->getRecordId($record['id']);        
                            mysqli_query($link,"DELETE FROM  vtiger_crmentityrel WHERE crmid='$idslot' AND relcrmid='$IDAsset'");
                                $product=$idproducto;
                                mysqli_query($link,"INSERT INTO vtiger_crmentityrel VALUES('$recordid','Movimientos','$IDAsset','Assets')");
                                $qtyasset=$qtyslot-$qty;                        
                                mysqli_query($link,"UPDATE vtiger_assetscf SET ".$cantasset."='$qtyasset' WHERE assetsid='$IDAsset'");
                                mysqli_query($link,"UPDATE vtiger_assets SET assetstatus='In Service' WHERE assetsid='$IDAsset'");
				if($osbi!=''){
					mysqli_query($link,"UPDATE vtiger_assetscf SET ".$osbi."='$OS2[1]' WHERE assetsid='$IDAsset'");
				}
                                $docs[0]=array('Result'=>'1', 'id'=>$recordid);
                                error_log("url: ".$url." Caja: ".$idcaja." Product: ".$productid." Cantidad: ".$qty."\n", 3, "php.log");
                                cajarecibeproductos($url,$usuario,$idcaja,$product,$qty,$IDAsset);
                                contabilizastock($recordid,$reservado,$url);
                                salidaconsignacion($recordid,$url);
                                error_log("PRODUCTO: ".$idproducto." -- ASSET: ".$IDAsset." -- CAJA:".$idcaja."\n", 3, "php.log");
                                if (strpos($url, 'hoser') !== false) { //estos updates son solo para Hoser.
                                    $Propiedad =  in_array(strtoupper($tipoOS), ['ARRIENDO','PRESTAMO','DEMO'])!==false ? 'SOC.DE INGENIERIA HOGG Y SERRANO LTDA':'Vendido';
                                    mysqli_query($link,"UPDATE vtiger_assetscf SET cf_2272='".$tipoOS."', cf_2274='".$Propiedad."' WHERE assetsid='$IDAsset'");
                                    //cf_2272 modalidad ;;;; cf_1931 => //Destinado a <;;;;-;;;;-;;;;>  //cf_2274 => //Propiedad
                                }
                                echo json_encode(setDataJSON($docs,1));             
                            }else{
                                $recordid=$client->lastError();
                                $docs[0]=array('Result'=>'0', 'id'=>$recordid);
                    echo json_encode(setDataJSON($docs,1));     
                            }
                        }
                    }else{
                        $docs[0]=array('Result'=>'3', 'id'=>'ProductError');
                    echo json_encode(setDataJSON($docs,1));     
                    }
           } }else{
                $docs[0]=array('Result'=>'3', 'id'=>'ProductError');
                    echo json_encode(setDataJSON($docs,1));     
            }    
        }
    }
}


/**
*recibe un string de assetsid, el assetid q se eligio como sustituo reservado
* osid recibe el id de la OS
*/
function cambiarReservas($assets, $osNew, $url)
{
    $cf_reserva = diccionario($url, 'AssetResv');
    $include=includec($url);
    include ($include);
    $query=mysqli_query($link,"SELECT * from vtiger_assetscf WHERE $cf_reserva = '$osNew' LIMIT 1");
    $num=mysqli_num_rows($query); //si hay para modificar
    if($num>0){
        $data=mysqli_fetch_array($query);
        $assetsid = $data['assetsid'];
        $query=mysqli_query($link,"UPDATE vtiger_assetscf set $cf_reserva = '' WHERE assetsid = '$assetsid'");
    }
    //$query=mysqli_query($link,"UPDATE vtiger_assetscf set $cf_reserva = '$osNew' WHERE assetsid = '$assets'");
	$query=mysqli_query($link,"UPDATE vtiger_assetscf INNER JOIN vtiger_assets on vtiger_assets.assetsid = vtiger_assetscf.assetsid SET $cf_reserva = '$osNew' WHERE serialnumber = '$assets'");
}
?>
