<?php if(!defined("security")): exit; endif; 


header("Access-Control-Allow-Origin: *");

header("Access-Control-Allow-Origin: https://br.vertismed.com");

// Permitir métodos específicos (se necessário)
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");

// Permitir cabeçalhos específicos (se necessário)
header("Access-Control-Allow-Headers: Content-Type, Authorization");


function getFullUrl() {
    // Verifica se a conexão é HTTPS ou HTTP
    $ssl = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on');
    $sp = strtolower($_SERVER['SERVER_PROTOCOL']);
    $protocol = substr($sp, 0, strpos($sp, '/')) . (($ssl) ? 's' : '');

    // Nome do servidor
    $port = $_SERVER['SERVER_PORT'];
    $port = ((!$ssl && $port=='80') || ($ssl && $port=='443')) ? '' : ':'.$port;
    $host = $_SERVER['SERVER_NAME'] . $port;

    // Uri da requisição
    $uri = $_SERVER['REQUEST_URI'];

    // Combinando para formar a URL completa
    $url = $protocol . '://' . $host . $uri;

    return $url;
}


if(isset($_GET['jstrack'])){
	
    //Cabeçalho para indicar que o conteúdo é JavaScript
    header('Content-Type: application/javascript; charset=utf-8');
	include('jstrack/index.php');
	exit;
	
}


if (isset($_POST['inserttrack'])) {
    
    $select_db       = $parametros_response['select_db'];

    $email_original  = $_POST['email'];
    $email           = $email_original;
    $emailtemp       = $_POST['emailtemp'];
    $url             = $_POST['url'];
    $nome            = $_POST['nome'];
    $crm             = $_POST['crm'];
    $uf              = $_POST['uf'];
    $checkinC        = $_POST['checkinC'];
    $evento          = $_POST['evento'];
    $optin           = $_POST['optin'];
    $celular         = $_POST['celular'];
    $especialidade   = $_POST['especialidade'];
    
    $checkin         = $_POST['checkin'];
    $formtype        = $_POST['formtype'];
    
    $u   = explode('?', $url);
    $url =  $url;
    
    $data_full   = date("Y-m-d H:i:s");
    $data_filter = date("Y-m-d");
    $datatime    = date("Ymd");
    
    $createTrack = new Core_create;
    $updateTrack = new Core_update();
    
    $updateUser  = new Core_update();
    $createuser  = new Core_create;
    
   // Usar parse_url para obter o esquema (http ou https) e o host (domínio)
   $parsed_url = parse_url($url);

   // Construir o domínio base
   $base_url = $parsed_url['scheme'] . '://' . $parsed_url['host'];

   $select_db->ExeRead("*",  'pd_script', "WHERE script_origem = :s", "s={$base_url}");
    
    if (!$select_db->getResult()){
    exit;
    }
    
        // Usar email temporário caso o email esteja vazio ou inválido
    if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $email = $emailtemp;
    }
    
      //UPDATE TIME PAGE LAST
    $tempo_last  = $_POST['tempo_last'];
    $last_page   = $_POST['last_page'];
    
	$select_db->ExeRead("*",  'pd_track', "WHERE (email = :o || email = :e) AND url = :u AND (timeSpent = 0 AND up = 0)", "o={$email_original}&e={$emailtemp}&u={$last_page}");
    
    if ($select_db->getResult()){
    
    // Atualização no banco de dados
    $update_data = ['timeSpent' => $tempo_last,
    'up' => 1];
    
    $updateTrack->ExeUpdate('pd_track', $update_data, "WHERE (email = :o || email = :e) AND (url = :u AND timeSpent = 0 AND up = 0)", "o={$email_original}&e={$emailtemp}&u={$last_page}");

    }
    
    
if($formtype == 1 && $checkin == 1){
    
   	$select_db->ExeRead("*",  'pd_track', "WHERE (email = :o || email = :e) AND (type = 1 AND eventname='$evento' AND checkinC = 1 AND checkin = 0) ", "o={$email_original}&e={$emailtemp}");
    
    if ($select_db->getResult()){ 
      
    $update_data = ['checkin' => 1,
    'up' => 1];
    
    $updateTrack->ExeUpdate('pd_track', $update_data, "WHERE (email = :o || email = :e) AND (type = 1 AND eventname='$evento' AND checkinC = 1 AND checkin = 0) ", "o={$email_original}&e={$emailtemp}");
        
    }else{
        
    $select_db->ExeRead("*",  'pd_track', "WHERE (email = :o || email = :e) AND url = :u AND (type = 1 AND checkin=1) ", "o={$email_original}&e={$emailtemp}");
    
    if (!$select_db->getResult()){ 
     
    //Inserir novo registro de página visitada
    $insert_track = [
        'email'      => $email,
        'url'        => $url,
        'date'       => $data_full,
        'origem'     => $base_url,
        'datatime'   => $datatime,
        'checkin'    => $checkin,
        'type'       => $formtype,
        'eventname'  => $evento,
        'checkinC'   => $checkinC
    ];
    
    $createTrack->ExeCreate('pd_track', $insert_track);  
        
    }
        
  }
    
}else if($formtype == 1 && $checkin == 0){
    
   	$select_db->ExeRead("*",  'pd_track', "WHERE (email = :o || email = :e) AND (type = 1 AND eventname='$evento' AND checkinC = 1) ", "o={$email_original}&e={$emailtemp}");
    
    if (!$select_db->getResult()){ 
      
         // Inserir novo registro de página visitada
    $insert_track = [
        'email'      => $email,
        'url'        => $url,
        'date'       => $data_full,
        'origem'     => $base_url,
        'datatime'   => $datatime,
        'checkin'    => $checkin,
        'type'       => $formtype,
        'eventname'  => $evento,
        'checkinC'   => $checkinC
    ];
    
    $createTrack->ExeCreate('pd_track', $insert_track);  
        
    }
    
}else{
    
    // Inserir novo registro de página visitada
    $insert_track = [
        'email'      => $email,
        'url'        => $url,
        'date'       => $data_full,
        'origem'     => $base_url,
        'datatime'   => $datatime,
        'checkin'    => 0,
        'type'       => 0,
        'eventname'  => '',
        'checkinC'   => 0
    ];
    
    $createTrack->ExeCreate('pd_track', $insert_track);
    
}
    
    //UPDATE ALL EMAIL TEMP
    if($email_original == $email){
        
    $update_data = ['email' => $email_original];
    
    $updateTrack->ExeUpdate('pd_track', $update_data, "WHERE email = :e", "e={$emailtemp}");
    
    $update_user = [
            'user_name'  => $nome,
            'user_cod'   => $crm,
            'user_uf'    => $uf,
            'user_email' => $email,
            'user_celular' => $celular,
            'user_especialidade' => $especialidade,
            'user_optin' => $optin
        ];
        
    $updateUser->ExeUpdate('pd_users', $update_user, "WHERE user_email = :e ", "e={$emailtemp}");
    
    }else{
    
      	$insert_data = [
            'user_name'  => $nome,
            'user_cod'   => $crm,
            'user_uf'    => $uf,
            'user_email' => $email,
            'user_celular' => $celular,
            'user_especialidade' => $especialidade,
            'user_optin' => $optin,
            'user_data'  => $data_full,
            'origem'     => $base_url
        ];
        
        
        $createuser->ExeCreate('pd_users', $insert_data);   
        
    }

exit;
    
}


if(isset($_SESSION['fideliza_logado-admin'])){
	
	if($parametros_get_page['pag_name'] == 'Home'){
	    
	    header('Location: ' . dominio . 'admin-dashboard');
	    
	}else{
	
	    $a[] = '{footer_insert_admin}';
	    $b[] = '<script src="'.base.'assets/js/jquery.min.js"></script> 
	    <script src="'.dominio.'pd-plugins/fidelizaweb/jsclasses/TerminalAdmin.js?ver=1.2" ></script>
	    <script type="text/javascript" src="'.base.'assets/scripts/main.d810cf0ae7f39f28f336.js?ver=3.05"></script>';
		
	    include('include-admin.php');
	    
	}
	
}else{
	
/* GET AJAX ADMIN LOGAR */
if(isset($get['logar-admin-email'])){
		
	$email = $get['logar-admin-email'];	 
	$senha = md5($get['logar-admin-senha']);
	
    $select_db = $parametros_response['select_db'];
	$select_db->ExeRead("*",  'fd_admin', "WHERE ( ad_login = :l AND ad_senha = :s )", "l={$email}&s={$senha}");

    if ($select_db->getResult()){
			
		$_SESSION['fideliza_logado-admin']   = 	json_encode($select_db->getResult()[0]);
		$_SESSION['fideliza_cliente_logado'] = NULL;
		echo utf8_encode('success');			
		exit;
		
	}else{
		
		echo 'Login invalido!';
		exit;
		 
    }
	
  }

}

if(!isset($_SESSION['fideliza_logado-admin']) && dominio != getFullUrl()){
    header('Location: ' . dominio);
    exit;
}

?>