<?php
/**   ------------------------------------------------------------
		CREA UN CLIENTE EN NAVISION
	  ------------------------------------------------------------
*/ 
error_reporting(E_ALL);
ini_set('display_errors', 1);
date_default_timezone_set('Europe/Madrid');

$discord_channel = "1281539966144483338";

// Parametros
$serverName 	= "localhost";
$connectionInfo = array( "Database"=>"ICF", "UID"=>"VAIO", "PWD"=>"VAIO");

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


$response=[];
$responseErrors=[];
// Conexion con Navision
$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 json_encode(["result"=>-1 , "text"=>"No se pudo conectar con Navision"]);
	  die;
}

$lines 		= [];
$json = file_get_contents('php://input');
$data = json_decode($json, true);

if (json_last_error() !== JSON_ERROR_NONE) {
    // JSON no es valido
	echo json_encode(["result"=>-2 , "text"=>"Los datos enviados no son validos. Error:".json_last_error()]);
	die;
}

// Comprobar lo datos
if (!isset($data['code']) || $data['code']==''){
	echo json_encode(["result"=>-3 , "text"=>"No se ha enviado codigo de cliente o no es valido"]);
	die;
}
if (!isset($data['name']) || $data['name']==''){
	echo json_encode(["result"=>-4 , "text"=>"No se ha enviado el nombre del cliente o es vacio"]);
	die;
}	
if (!isset($data['vat']) || $data['vat']==''){
	echo json_encode(["result"=>-5 , "text"=>"No se ha enviado el CIF/NIF del cliente o es vacio"]);
	die;
}
if (!isset($data['address']) || $data['address']==''){
	echo json_encode(["result"=>-6 , "text"=>"No se ha enviado la direccion del cliente o es vacia"]);
	die;
}		
if (!isset($data['postcode']) || $data['postcode']==''){
	echo json_encode(["result"=>-7 , "text"=>"No se ha enviado el codigo postal del cliente o es vacio"]);
	die;
}
if (!isset($data['state']) || $data['state']==''){
	echo json_encode(["result"=>-9 , "text"=>"No se ha enviado la provincia del cliente o es vacia"]);
	die;
}
if (!isset($data['town']) || $data['town']==''){
	echo json_encode(["result"=>-10 , "text"=>"No se ha enviado la localidad del cliente o es vacia"]);
	die;
}

$data = array_map(function($value) {
    return iconv("UTF-8", "Windows-1252",mb_strtoupper(mssql_escape($value), "UTF-8"));
}, $data);

// Comprobar que no exista
$sql = "SELECT count(*) as ncount from  ".'[Ind. Campollano Ferretería S.L$Customer]'." WHERE [No.]='".$data['code']."'";
$stmt = sqlsrv_query( $connNavision, $sql );
if( $stmt !== false) {
	if($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)){
		$ncustomer=$row['ncount']*1;
		if ($ncustomer>0){
			echo json_encode(["result"=>-11, "text"=>"El cliente: ".$data['code']." ya esta existe en Navision"]);
			die;
		}
	}
}

// Crear el cliente
$sql = "
INSERT INTO ".'[Ind. Campollano Ferretería S.L$Customer]'."
([No.], Name, [Search Name], [Name 2], 
Address, [Address 2], City, 
Contact, [Phone No.], [Telex No.], [Our Account No.], [Territory Code], 
[Global Dimension 1 Code], [Global Dimension 2 Code], [Chain Name], [Budgeted Amount], [Credit Limit (LCY)], 
[Customer Posting Group], [Currency Code], [Customer Price Group], [Language Code], [Statistics Group], 
[Payment Terms Code], [Fin. Charge Terms Code], [Salesperson Code], [Shipment Method Code], [Shipping Agent Code], 
[Place of Export], [Invoice Disc. Code], [Customer Disc. Group], [Country_Region Code], [Collection Method], 
Amount, Blocked, [Invoice Copies], [Last Statement No.], [Print Statements], 
[Bill-to Customer No.], Priority, [Payment Method Code], [Last Date Modified], [Application Method], 
[Prices Including VAT], [Location Code], [Fax No.], [Telex Answer Back], [VAT Registration No.], 
[Combine Shipments], [Gen. Bus. Posting Group], Picture, [Post Code], County, 
[E-Mail], [Home Page], [Reminder Terms Code], [No. Series], [Tax Area Code], 
[Tax Liable], [VAT Bus. Posting Group], Reserve, [Block Payment Tolerance], [IC Partner Code], 
[Prepayment %], [Primary Contact No.], [Responsibility Center], [Shipping Advice], [Shipping Time], 
[Shipping Agent Service Code], [Service Zone Code], [Allow Line Disc.], [Base Calendar Code], [Copy Sell-to Addr. to Qte From], 
[Payment Days Code], [Non-Paymt. Periods Code], [Cod. Zona], [Cod. Mercado], [Cod. Sector], 
[Forma facturacion], [Cod. Banco domic.], [Importe pago en metalico], [Año mas antiguo pago met.], [Clave operacion tiques], 
[Tipo Facturas (349)], [Liq. Payment Terms Code], [Default Bank Acc. Code], [Cuenta bancaria], [Mensajeria instantanea], 
[Aplicacion de mensajeria], [Codigo proveedor en Cliente], [Albaran de un solo pedido], [Un pedido por factura], [Un albaran por factura], 
[Obligatorio numero de pedido], [Entrega completa del articulo], [Fianza de alquiler], [Dia de facturacion especial], [Envio facturas por E-mail], 
[Abierto por el comercial], [Detalle en impresion albaran], [Control personas autorizadas], [Sales type], [Shipment Copies],
[Invoice Contact No.], SalesManager, Agent, SubAgent, [Route code], 
[Activity code], [Subactivity code], [Automatic Credit Memo], [Minimum invoice amount], [Block exceed credit limit], 
[Control margen beneficio], TipoResidencia, TipoPersona, NombreFisico, PrimerApellido, 
SegundoApellido, CodINE, CodigoCNAE, CodOficinaContable, CodOrganoGestor, 
CodUdTramitadora, [Fichero XML], ClienteWEB, CodOrganoPrepotente)
VALUES(
'".$data['code']."', '".substr($data['name'],0,50)."', '".substr($data['name'],0,50)."', '', 
'".substr($data['address'],0,50)."', '', '".substr($data['town'],0,30)."', 
'', '', '', '', '', 
'', '', '', 0, 0, 
'NAC', '', 'TARIFA1', '', 0, 
'00C', '', '', '', '', 
'', '".$data['code']."', 'GDTO3', 'ES', '0',
0, 0, 1, 0, 0, 
'', 0, 'CONTADO', '".date('Y-d-m')." 00:00:00.000', 0, 
0, '', '', '', '".substr($data['vat'],0,20)."', 
1, 'NACIONAL', NULL, '".substr($data['postcode'],0,20)."', '".substr($data['state'],0,30)."', 
'', '', '', '', '', 
0, 'NAC', 1, 0, '', 
0, '', '', 0, '', 
'', '', 1, '', 0, 
'', '', '', '', '', 
0, '', 0, '', 0,
0, '', '', '', '',
'', '', 1, 0, 0, 
0, 0, 1, 0, 0, 
0, 0, 0, 1, 1, 
'', '', '', '', '', 
'', '', 0, 0, 0, 
0, 0, 0, '', '', 
'', '', '', '', '', 
'', 0, 0, '')
";

$stmt = sqlsrv_query( $connNavision, $sql);	
if(sqlsrv_errors(SQLSRV_ERR_ERRORS)!==NULL) {
	echo json_encode(["result"=>-12, "text"=>"Ocurrio un error al insertar el cliente ".$data['code']." en Navision. ".print_r(sqlsrv_errors(SQLSRV_ERR_ERRORS),true)]);
	die;
}

// Resultado
echo json_encode(["result"=>1, "text"=>"El cliente ".$data['code']." se ha creado correctamente en Navision"], JSON_UNESCAPED_UNICODE);
?>
