<script>
	function showmessage(text) {
		$('#contenedorint form').remove();
		$('#contenedorint div').html(text);
		$('#contenedorint div').attr('style', 'text-align: center;');
	}
</script>

<?php
	include 'API/customConfig/Constants.php';
	include '../security.php';
	$method = $_SERVER['REQUEST_METHOD'];

	function getRSC($id, $language) {
		$url = '/getRSC';
		$params = array('token' => 'HtDFjQYeyfFb9en9URgFw664ey11WJ9PaGLOKmFh', 'rsc' => $id);
		$resWS = APIWS($url, $params);

		if(strtoupper($language) == 'SPA') $language = 'ESP';
		else if(strtoupper($language) == 'IND') $language = 'IDN';

		return $resWS->result[0]->$language;
	}

	function APIWS($url, $params) {
		$curl = curl_init();
		curl_setopt_array($curl, array(
			CURLOPT_RETURNTRANSFER => 1,
			CURLOPT_URL => CONSTANTS::SERVERAPI . $url,
			CURLOPT_POST => 1,
			CURLOPT_POSTFIELDS => $params,
			CURLOPT_SSL_VERIFYPEER => false
		));
		$resp = curl_exec($curl);
		curl_close($curl);
		return json_decode($resp);
	}

	function GetUserLanguageByEmail($email) {
		$conexion = ConnectDB();
		$country = "";

		$sql = 'select lenguage from cmregisteruserdata where userEmail = ?';
		$sql = $conexion->prepare($sql);
		$sql->bind_param("s", $email);

		$sql->execute();
		$result = $sql->get_result();
		if(!$result) die();

		while($row = $result->fetch_assoc()) {
			$country = $row['lenguage'];
			break;
		}

		if ($country == '') $country = CONSTANTS::MAIN_COUNTRY_ISO;
		DisconnectDB($conexion);

		return $country;
	}

    try {
        if($method == 'GET') {
            $arrayParams = applyAntiXSS($_GET);
            $email = $arrayParams['b'];
            $language = strtoupper($arrayParams['d']);

            $result = "";
            $logEvent = "";
            $profilingMode = CONSTANTS::ENV_PROFILING_ALGORITHM;

            if ($profilingMode == CONSTANTS::PROFILING_TYPE_LEGACY) {
                $url = '/getIfUserPerfila';
                $params = array('token' => 'HtDFjQYeyfFb9e27n9URgFw27b9en9URg11Fw664ey11664ey11WJ9P27aGLOKmFh', 'email' => $email);
                $resWS = APIWS($url, $params);
                $perfila = $resWS->perfila ?? false;

                $logEvent = "getIfUserPerfila";
                if (!$perfila) {
                    $result = 'noperfila';
                }
            }
            elseif ($profilingMode == CONSTANTS::PROFILING_TYPE_DYNAMIC) {
                $url = '/executePerfilationAlgorithm';
                $params = array('token' => 'HtDFjQYeyfFb9e27n9URgFw27b9en9URg11Fw664ey11664ey11WJ9P27aGLOKmFh', 'email' => $email);
                $response = APIWS($url, $params);

                if ($response->status == "OK") {
                    $result = "OK";
                } else {
                    $errorCode = isset($response->error_code) ? intval($response->error_code) : 500;
                    $result = 'noperfila';
                    if ($errorCode==1003) {
                        $result = 'alreadyProfiled';
                    }
                }

                $logEvent = "reprofilingUser";
            }
            
            $url = '/setCMBPLOG';
            $params = array(
                'token' => 'HtDFjQYeyfFb9e27n9URgFw27b9en9URg11Fw664ey11664ey11WJ9P27aGLOKmFh',
                'TypeEvent' => 'clickActivationEmail',
                'CallerEvent' => $email,
                'LogEvent' => $logEvent,
                'SQLQuery' => json_encode($perfila),
                'systemEvent' => '0'
            );
            $resWS = APIWS($url, $params);

            // SETTING PROFILING RESULT
            $textVerificando = getRSC(1007, $language);

            if ($result == 'noperfila') $text = getRSC(1868, $language);
            else {
                $url = '/setUserAsConsejero';
                $params = array('token' => 'HtDFjQYeyfFb9e27n9URgFw27b9en9URg11Fw664ey11664ey11WJ9P27aGLOKmFh', 'email' => $email);
                $resWS = APIWS($url, $params);
                $response = $resWS->status;
                
                if($result == 'alreadyProfiled') $text = getRSC(2758, $language);
                elseif ($response == 'OK') $text = getRSC(1867, $language);
                else $text = getRSC(1040, $language);
            }

            echo '<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>';
            echo('<script language="JavaScript" type="text/javascript">setTimeout(function() { showmessage("' . $text . '"); }, 1000)</script>');
        }
    } catch (Exception $e) {
        // Manejo de excepciones para capturar cualquier error inesperado
        var_dump('Error: ' . $e->getMessage());
        die('An error occurred while processing your request.');
    }
?>

<!DOCTYPE html>
<html lang="es">
	<head>
		<title>Social Labs</title>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
		<?php echo '<title>' . $GLOBALS['title'] . '</title>'; ?>
		<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
	</head>

	<body style="background: #e9e9ea;color:#818183;font-family:sans-serif;font-size: 18px;">
		<div id="contenedor" style="margin:auto;max-width:970px;width: 100%;height:auto;background: #fff;padding-bottom: 3%;">
			<?php
				$url = '/getCMBPConfig';
				$params = array('token' => 'HtDFjQYeyfFb9en9URgFw664ey11WJ9PaGLOKmFh');
				$resWS = APIWS($url, $params);
				$arrayAPIConfig = $resWS->result[0];

				$mailingImageVisible = $arrayAPIConfig->mailingImageVisible;
				$mailingImagePosition = $arrayAPIConfig->mailingImagePosition;
				$URLLogoEmail = $arrayAPIConfig->URLLogoEmail;

				if($mailingImageVisible == '1' && $mailingImagePosition == '0') echo '<div class="fila2" style="margin:auto;max-width:80.61%;height:auto;margin-top:30px;padding-top: 20px;text-align:right">';
				else if($mailingImageVisible == '1' && $mailingImagePosition == '1') echo '<div class="fila2" style="margin:auto;max-width:80.61%;height:auto;margin-top:30px;padding-top: 20px;">';

				echo '<img style="height:80px;" src="' . $URLLogoEmail . '">';
				echo '</div>';
			?>
			<div id="contenedorint" class="padtop" style="margin:auto;width:76.80%;height:170px;margin-top:-82px;margin-top: 50px !important;">
				<?php
                    echo '
                        <div style="text-align: center">' . $textVerificando . '
                            <br><br>
                            <i class="fa fa-spinner fa-spin" style="font-size:3em"></i>
                        </div>
                    ';
				?>
			</div>
		</div>
	</body>
</html>
