<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('memory_limit', '-1');
set_time_limit(0);
date_default_timezone_set('Europe/Madrid');
//include("conexion.php");
if(isset($_REQUEST["code"])) //Formato linux timestamp
	$search=$_REQUEST["code"]; else $search='';
if(isset($_REQUEST["newcode"])) //Formato linux timestamp
	$newcode=$_REQUEST["newcode"]; else $newcode='';
if(isset($_REQUEST["supplier"])) //Formato linux timestamp
	$supplier=$_REQUEST["supplier"]; else $supplier='';

$search=preg_replace("/[^A-Za-z0-9]/", '', $search);
//$from=date('d/m/Y', $from);
$from=0;
$resultProducts=[];

function mssql_escape($str)
{
    if(get_magic_quotes_gpc())
    {
        $str= stripslashes($str);
    }
    return str_replace("'", "''", $str);
}

$serverName = "localhost";
$connectionInfo = array( "Database"=>"ICF", "UID"=>"VAIO", "PWD"=>"VAIO", "ConnectionPooling" => "1", "MultipleActiveResultSets"=>'1');

$connNavision=false;
$retries=0;
while(!$connNavision && $retries<3){
	$connNavision = sqlsrv_connect( $serverName, $connectionInfo);
	$retries++;
}


	if( $connNavision ) {
		 //echo "Conexion establecida con Navision.\r\n";
	}else{
		 //echo "Conexion no se pudo establecer con Navision.\r\n";
		 die( print_r( sqlsrv_errors(), true));
	}

		$objects=[];
		$collection=[];
		$maxtimestamp=0;

		
		$sql = 'SELECT h.[No.] code, h.[Buy-from Vendor No.] supplier,
		 userauthor.[E-Mail] author,
		 FORMAT(h.[Document Date],\'dd/MM/yyyy\') date
		 FROM [ICF].[dbo].[Ind. Campollano Ferreterķa S.L$Purch. Rcpt. Header] h
		 LEFT JOIN [ICF].[dbo].[Ind. Campollano Ferreterķa S.L$User Setup] userauthor ON userauthor.[User ID]=h.[User ID]
		 LEFT JOIN [ICF].[dbo].[Ind. Campollano Ferreterķa S.L$User Setup] usersaleperson ON usersaleperson.[Salespers._Purch. Code]=h.[Purchaser Code]
		 LEFT JOIN [ICF].[dbo].[Ind. Campollano Ferreterķa S.L$Purch. Rcpt. Line] l ON l.[Document No.]=h.[No.]
		 LEFT JOIN [ICF].[dbo].[Ind. Campollano Ferreterķa S.L$Vendor] c ON c.[No.]=h.[Buy-from Vendor No.]
		 WHERE h.[Buy-from Vendor No.]=\''.$supplier.'\' AND (dbo.fn_StripCharacters(h.[No.], \'^a-z0-9\') LIKE \''.$search.'\') AND
		 CAST(h.TIMESTAMP AS BIGINT)>0 
		 GROUP BY h.TIMESTAMP, h.[No.], h.[Buy-from Vendor No.], h.[Buy-from Vendor Name], h.[Buy-from Vendor Name 2], h.[Buy-from Address], h.[Buy-from Address 2], h.[Buy-from Post Code], h.[Buy-from City], h.[Buy-from County],
					 h.[Ship-to Name], h.[Ship-to Address], h.[Ship-to Name 2], h.[Ship-to Address 2], h.[Ship-to Post Code], h.[Ship-to City], h.[Ship-to County], h.[Location Code], h.[Vendor Shipment No.],
		 			 h.[VAT Registration No.], h.[Document Date], userauthor.[E-Mail], 
					 usersaleperson.[E-Mail]
		ORDER BY h.[No.] DESC;';
		
		
		//echo utf8_encode($sql);
		
		
		$stmt = sqlsrv_query( $connNavision, $sql);
		if( $stmt !== false) {
			while($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)){
				
				$temp=[];
				foreach($row as $key=>$object){
					$temp_object[$key]=!is_object($object)?utf8_encode($object):$object;
				}
    			$objects=$temp_object;
			}
		}
		if($objects!=null){
            $sql = 'UPDATE [ICF].[dbo].[Ind. Campollano Ferreterķa S.L$Purch. Rcpt. Header] SET [Vendor Shipment No.] = \''.$newcode.'\' WHERE [Buy-from Vendor No.]=\''.$supplier.'\' AND (dbo.fn_StripCharacters([No.], \'^a-z0-9\') = \''.$search.'\');';
            $stmt = sqlsrv_query( $connNavision, $sql);
            if(sqlsrv_errors(SQLSRV_ERR_ERRORS)!==NULL) {
                $result["result"]=-1;
            }else{
                $sql = 'UPDATE [ICF].[dbo].[Ind. Campollano Ferreterķa S.L$Purchase Header] SET [Vendor Shipment No.] = \''.$newcode.'\' WHERE (dbo.fn_StripCharacters([Last Receiving No.], \'^a-z0-9\') = \''.$search.'\');';
                $stmt = sqlsrv_query( $connNavision, $sql);
                if(sqlsrv_errors(SQLSRV_ERR_ERRORS)!==NULL) {
                    $result["result"]=-2;
                }else{
                    $result["result"]=1;
                    $result["data"]=$objects;
                }
            }
        }else $result["result"]=-3;
  
		//var_dump($result);
		
header('Content-Type: application/json');
echo json_encode($result, JSON_PRETTY_PRINT);

?>
