<?php
require_once 'ApiGlobalFunctions.php';

$usuario=$_POST['uid'];
$password=$_POST['key'];
$url=$_POST['url'];
$estado=$_POST['estado'];

//0=crear paquete
//1=paquete creado

$include=includec($url);
include $include;
$validate=loginkey($usuario,$password,$url);
if($validate==1){
    
    mysqli_set_charset($link, "utf8");
    $campo=diccionario($url,'completadooc');
    $campo2=diccionario($url,'cuentaoc');
	$osDev=diccionario($url,'OCOSDevo');   
   if($estado==1){
       
        /*if (strpos($url, 'solucorp') !== false) {
            $query=mysqli_query($link, "SELECT vtiger_purchaseorder.purchaseorderid, subject, purchaseorder_no,vtiger_crmentity.createdtime,postatus,concat(first_name,' ',last_name) as asignado,accountname,
            concat(firstname,' ',lastname) as contacto,
            vtiger_accountshipads.ship_street as direccion,vtiger_accountshipads.ship_city as comuna,vtiger_accountshipads.ship_state as region,vtiger_accountshipads.ship_country as pais,
            vtiger_crmentity.description  as descripcion, vendorname, ".$osDev." as devolucion
            FROM vtiger_purchaseorder 
            INNER JOIN vtiger_purchaseordercf ON vtiger_purchaseordercf.purchaseorderid=vtiger_purchaseorder.purchaseorderid 
            INNER JOIN vtiger_inventoryproductrel ON vtiger_inventoryproductrel.id=vtiger_purchaseorder.purchaseorderid
            INNER JOIN vtiger_products ON vtiger_products.productid=vtiger_inventoryproductrel.productid
            INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_purchaseorder.purchaseorderid
            INNER JOIN vtiger_users ON vtiger_users.id=vtiger_crmentity.smownerid 
            LEFT JOIN vtiger_account ON vtiger_account.accountid=vtiger_purchaseordercf.$campo2
            LEFT JOIN vtiger_accountshipads ON vtiger_accountshipads.accountaddressid=vtiger_account.accountid 
            LEFT JOIN vtiger_contactdetails ON vtiger_contactdetails.contactid=vtiger_purchaseorder.contactid
            INNER JOIN vtiger_paquetes ON vtiger_paquetes.paquetes_tks_ordendecompra=vtiger_purchaseorder.purchaseorderid
            INNER JOIN vtiger_crmentity CRM2 ON CRM2.crmid=vtiger_paquetes.paquetesid
            INNER JOIN vtiger_vendor ON vtiger_vendor.vendorid=vtiger_purchaseorder.vendorid
            WHERE vtiger_crmentity.deleted='0' AND CRM2.deleted='0'  AND ".$campo."='1' AND vtiger_crmentity.smownerid='$usuario' GROUP BY vtiger_purchaseorder.purchaseorderid ORDER BY createdtime DESC LIMIT 10");
            
        }else{*/   
        	$query=mysqli_query($link, "SELECT vtiger_purchaseorder.purchaseorderid, subject, purchaseorder_no,vtiger_crmentity.createdtime,postatus,concat(first_name,' ',last_name) as asignado,accountname,
        concat(firstname,' ',lastname) as contacto,
        vtiger_accountshipads.ship_street as direccion,vtiger_accountshipads.ship_city as comuna,vtiger_accountshipads.ship_state as region,vtiger_accountshipads.ship_country as pais,
        vtiger_crmentity.description  as descripcion, vendorname, ".$osDev." as devolucion
        FROM vtiger_purchaseorder 
        INNER JOIN vtiger_purchaseordercf ON vtiger_purchaseordercf.purchaseorderid=vtiger_purchaseorder.purchaseorderid 
        INNER JOIN vtiger_inventoryproductrel ON vtiger_inventoryproductrel.id=vtiger_purchaseorder.purchaseorderid
        INNER JOIN vtiger_products ON vtiger_products.productid=vtiger_inventoryproductrel.productid
        INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_purchaseorder.purchaseorderid
        INNER JOIN vtiger_users ON vtiger_users.id=vtiger_crmentity.smownerid 
        LEFT JOIN vtiger_account ON vtiger_account.accountid=vtiger_purchaseordercf.$campo2
        LEFT JOIN vtiger_accountshipads ON vtiger_accountshipads.accountaddressid=vtiger_account.accountid 
        LEFT JOIN vtiger_contactdetails ON vtiger_contactdetails.contactid=vtiger_purchaseorder.contactid
        INNER JOIN vtiger_paquetes ON vtiger_paquetes.paquetes_tks_ordendecompra=vtiger_purchaseorder.purchaseorderid
        INNER JOIN vtiger_crmentity CRM2 ON CRM2.crmid=vtiger_paquetes.paquetesid
        INNER JOIN vtiger_vendor ON vtiger_vendor.vendorid=vtiger_purchaseorder.vendorid
        WHERE vtiger_crmentity.deleted='0' AND CRM2.deleted='0'  AND ".$campo."='1' GROUP BY vtiger_purchaseorder.purchaseorderid ORDER BY createdtime DESC");
    	//}
	}

   if($estado==0){
		if (strpos($url, 'solucorp') !== false) {
            //$query=mysqli_query($link,"CALL ObtenerOrdenesDeCompraCero('$usuario')");
            $query=mysqli_query($link,"CALL ObtenerOrdenesDeCompraCero()");
        }else{
        	$query=mysqli_query($link,"CALL ObtenerOrdenesDeCompraCero()");
   		}
	//Limpiar todos los resultados del CALL
        do {
            if ($res = mysqli_store_result($link)) {
                mysqli_free_result($res);
            }
        } while (mysqli_more_results($link) && mysqli_next_result($link));
    }
    
	$num=mysqli_num_rows($query);  
    $z=0;
	$docs[$z]=array('ocid'=>$osid,'asuntoOC'=>'','OCNum'=>'','FechaOC'=>'','EstadOC'=>'','ocUser'=>'','ocCuenta'=>'','ocContacto'=>'','ocDirEnvio'=>'','ocComuna'=>'','ocRegion'=>'','ocPais'=>'','ocDescripcion'=>'','Proveedor'=>'');             
    //print_r(mysqli_fetch_array($query));
	if($num>0){
    while ($row = mysqli_fetch_array($query)) {           
        $osid=$row['purchaseorderid'];
         $queryc=mysqli_query($link,"SELECT * 
            FROM vtiger_paquetes 
            INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_paquetes.paquetesid 
            WHERE deleted='0' AND paquetes_tks_ordendecompra='$osid' AND paquetes_tks_estado IN ('Almacenada','Nueva')");
        $numc=mysqli_num_rows($queryc);
         error_log(" LIST OS CAJAS?: ".$osid."--".$numc."\n", 3, "php.log");
        if($numc<=0){
            $asunto=$row['subject'];
            $osnum=$row['purchaseorder_no'];
            $fecha=$row['createdtime'];
            $fecha=explode(" ",$fecha);
            $fecha=$fecha[0]; 
            $status=$row['postatus'];
            $asignado=$row['asignado']; 
            $cuenta=$row['accountname'];
            $contacto=$row['contacto']; 
            $direccion=$row['direccion']; 
            $comuna=$row['comuna']; 
            $region=$row['region']; 
            $pais=$row['pais']; 
            $descripcion=$row['descripcion']; 
            $Proveedor=$row['vendorname'];
            $devolucion=$row['devolucion'];
        
        $docs[$z]=array('ocid'=>$osid,'asuntoOC'=>$asunto,'OCNum'=>$osnum,'FechaOC'=>$fecha,'EstadOC'=>$status,'ocUser'=>$asignado,'ocCuenta'=>$cuenta,'ocContacto'=>$contacto,'ocDirEnvio'=>$direccion,'ocComuna'=>$comuna,'ocRegion'=>$region,'ocPais'=>$pais,'ocDescripcion'=>$descripcion,'Proveedor'=>$Proveedor,'OSDevolucion'=>$devolucion);
        	$z++;            
        	}
		}
    }else{
        $docs[]=array();
    }    
     echo json_encode(setDataJSON($docs,1));
}

