<?php
include_once("utiles.php");

date_default_timezone_set("America/Panama");
error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);

if (!$connection = connectDb()) {
	die("err db");
} else {
	$connection->query("SET NAMES 'utf8';");
}
header('content-type: application/json');

session_start();
$_SESSION['database'] = $_POST['database'];
$_SESSION['tipo_cte'] = $_POST['tipo_cte'];
$_SESSION['ins_data'] = $_POST['ins_data'];
$_SESSION['ced_ruc'] = $_POST['ced_ruc'];

$cDatabase = $_SESSION['database'];
$cTipo_Cte = $_SESSION['tipo_cte'];
$cSave_data = $_SESSION['ins_data'];
$cCedul_Ruc = $_SESSION['ced_ruc'];

$url = "https://api-sap.rctechsoftware.com/cliente/$cCedul_Ruc";

$options = array(
	CURLOPT_RETURNTRANSFER => true,
	CURLOPT_HEADER         => false,
	CURLOPT_FOLLOWLOCATION => true,
	CURLOPT_ENCODING       => "",
	CURLOPT_USERAGENT      => "spider",
	CURLOPT_AUTOREFERER    => true,
	CURLOPT_CONNECTTIMEOUT => 120,
	CURLOPT_TIMEOUT        => 120,
	CURLOPT_MAXREDIRS      => 10,
	CURLOPT_SSL_VERIFYPEER => false
);

$ch = curl_init($url);
curl_setopt_array($ch, $options);
$Json_Resp = curl_exec($ch);
//echo ($Json_Resp);
curl_close($ch);

$Arr_Resp = json_decode($Json_Resp, true);

if ($Arr_Resp['INDICADOR'] == 0) {
	/*
	//-----BUSCA LA SECUENCIA PROPIA DE RCTECH-INTEGRACION SAP----// 
	$url = $_SERVER["HTTP_HOST"] . '/rest/v96/trans/cte_corre_get_save.php';

	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_POST, true);
	curl_setopt($ch, CURLOPT_POSTFIELDS, "database=$cDatabase&tipoc=$cTipo_Cte&valor=0&guardar=$cSave_data");
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	$Json_Sec = curl_exec($ch);
	//echo ($Json_Sec);
	curl_close($ch);

	$Arr_Sec = json_decode($Json_Sec, true);
	$Cte_Sec = $Arr_Sec['value'];
	//-----------------------------------------------------------// 
	*/

	$hoynow = getdate();
	$timeStamp = $hoynow["year"] . "-" . $hoynow["mon"] . "-" . $hoynow["mday"];

	$Cte_Cod = $Arr_Resp['PARTNER'];
	$Cte_Nom = $Arr_Resp['NOMBRE1'];
	$Cte_Dir = $Arr_Resp['STREET'];
	$Cte_Tel = $Arr_Resp['TEL_NUMBER'];
	$Cte_mai = $Arr_Resp['SMTP_ADDR'];

	//$CteCedF = trim($Arr_Resp['STCD3']);
	//$Pos_Ced = strpos(trim(strtoupper($CteCedF)),"DV");
	//$Cte_Ced = substr(trim($CteCedF),0, $Pos_Ced);
	//$Cte_Dvx = trim(substr($CteCedF, $Pos_Ced,10));

	$Cte_Ced = trim($Arr_Resp['STCD3']);
	$Cte_Dvx = trim($Arr_Resp['STCD6']);
	$Tip_Doc = $Arr_Resp['TIPODOC'];
	$Cte_Sub = $Arr_Resp['KNRZE'];
	$Cte_Imp = ($Arr_Resp['TAXKD'] == '1' ? '1' : '4');

	/*
	{"INDICADOR":"0",
		"PARTNER":"0070001875",
		"TYPE":"2",
		"NOMBRE1":"Cuenta central cliente credito almacenes",
		"STREET":"panama",
		"CITY1":"Ciudad de panama",
		"LAND1":"PA",
		"TEL_NUMBER":"555-5555",
		"SMTP_ADDR":"correo@gmail.com",
		"STCD3":"16-281-457-000DV03",
		"TIPODOC":"R",
		"KNRZE":"",
		"TAXKD":"1","success":1}
*/

	$SQL_Insert = "INSERT IGNORE INTO $cDatabase.clientes (
	c_id			, c_descripcion	, pa_id,
	ciu_id			, c_idfiscal	, 
	c_telefono		, c_credito		, c_dias_credito,
	c_limite_credito, c_vendedor	, id_contribuyente	,
	c_correo		, c_exclusiv_cont,	c_creacion,
	c_apart			, c_activo		, suc_id,
	c_ref2			, usermodify	, useroption, 
	c_direccion		, c_club		, c_u_id_crea,
	c_precio		,c_desc			,c_acumpuntos,
	cliente_pre_pago,cat_id			,c_afiliado,
	c_dv        	,c_tipo_documento,cod_subsidiaria  ,
	c_tipo_persona	,tipo_calculo	,c_recarg_mora)  VALUES  (
	'$Cte_Cod',
	'$Cte_Nom',
	'1',
	'1',
	'$Cte_Ced',
	'$Cte_Tel',
	'00',
	'30',
	'00',
	'0',
	'$Cte_Imp',
	'$Cte_mai',
	'0',
	'$timeStamp',
	'0',
	'1',
	'1',
	'',0,0,
	'$Cte_Dir',
	'0',
	'SAP',
	'0',
	'0',
	'1',
	'0',
	'1',
	'0',
	'$Cte_Dvx',
	'$Tip_Doc',
	'$Cte_Sub',
	'1',	
	'1',
	'0')";
	//var_dump($SQL_Insert);

	if ($connection->query($SQL_Insert) == TRUE) {
		$msg = array("success" => "true", "detalle" => "CLIENTE AGREGADO");
	} else {
		$msg = array("success" => "false", "detalle" => "ERROR");
		echo "<br>Error: " . $SQL_Insert . "<br>" . $connection->error;
	}
} else
	$msg = array("success" => "false", "detalle" => "CLIENTE NO EXISTE");

print_r(json_encode($msg));

@mysqli_close($connection);
