<?php 

/* SAIR */
if(isset($get['admin-logout'])){

$_SESSION['fideliza_logado-admin'] = null;
sleep(1);
header('Location: ' . dominio);
exit;
	
}

function current_data_mysql($date, $hora = false){
			
	//Converter a data MySQL em um objeto DateTime
    $dataHoraMySQL = $date;
	
	if($hora == false){
	return   date("d/m/Y", strtotime($dataHoraMySQL));
	}else{
	return date("d/m/Y H:i:s", strtotime($dataHoraMySQL));	
	}
			
}

$select_db = $parametros_response['select_db'];

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

//Deletar CLIENTE
if(isset($get['script_del']) && isset($_SESSION['fideliza_logado-admin'])){
	
    header('Content-Type: application/json');
	
	$id = $get['script_del'];
	
	$Delete = new Core_delete;
    $Delete->ExeDelete('pd_script', "WHERE id = :i", "i={$id}");	
		
	if($Delete->getResult()){
		
$resultados = array('result'  => 'success', 
'msg' => 'Instância Deletado com Sucesso!');
echo json_encode($resultados);
exit;
		
	}else{
		
$resultados = array('result'  => 'error', 
'msg' => 'Erro ao tentar deletar Instância!');
echo json_encode($resultados);
exit;

	}
	
}


//UPDATE SCRIPT MODE PAGE
if( isset($_POST['updatescript'])){
    
$config_id    = $_POST['id_update'] ?: '';  
    
$config_script_name    = $_POST['config_script_name'] ?: '';
$config_script_origem  = $_POST['config_script_origem'] ?: '';

// Usar parse_url para obter o esquema (http ou https) e o host (domínio)
$parsed_url = parse_url($config_script_origem);

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

$bt_id    = $_POST['bt_action_id'] ?: '';
$bt_class = $_POST['bt_action_class'] ?: '';

$config_nome_id        = $_POST['config_nome_id'] ?: '';
$config_nome_class     = $_POST['config_nome_class'] ?: '';

$config_email_id       = $_POST['config_email_id'] ?: '';
$config_email_class    = $_POST['config_email_class'] ?: '';

$config_crm_id         = $_POST['config_crm_id'] ?: '';
$config_crm_class      = $_POST['config_crm_class'] ?: '';

$config_uf_id          = $_POST['config_uf_id'] ?: '';
$config_uf_class       = $_POST['config_uf_class'] ?: '';

$form_id                         = $_POST['config_form_id'] ?: 'track_form_id';
$form_class                      = $_POST['config_form_class'] ?: 'track_form_class';

$novo_dado = '{
  "insert": "trackform",
  "id": {
    "nome": "'.$config_nome_id.'",
    "email": "'.$config_email_id.'",
    "crm": "'.$config_crm_id.'",
    "uf": "'.$config_uf_id.'"
  },
  "class": {
    "nome": "'.$config_nome_class.'",
    "email": "'.$config_email_class.'",
    "crm": "'.$config_crm_class.'",
    "uf": "'.$config_uf_class.'"
  },
  "buttom": {
    "id": "'.$bt_id.'",
    "class": "'.$bt_class.'"
  },
  "form": {
    "id": "'.$form_id.'",
    "class": "'.$form_class.'"
  }
}';

 $prepared_insert_array = [
    'script_name'      => $config_script_name,
    'script_origem'    => $base_url,
    'script_parametro' => $novo_dado
    ];
            
$updateScript  = new Core_update(); 
$updateScript->ExeUpdate('pd_script', $prepared_insert_array, "WHERE id = :id", "id={$config_id}");

if ($updateScript->getResult()){
    
    echo 'sucesso';
    
}else{
    
    echo 'error';
}

  exit;  
    
}


// INSERT SCRIPT MODE PAGE
if( isset($_POST['addscript'])){
	
$config_script_name    = $_POST['config_script_name'] ?: exit;
$config_script_origem  = $_POST['config_script_origem'] ?: exit;

// Usar parse_url para obter o esquema (http ou https) e o host (domínio)
$parsed_url = parse_url($config_script_origem);

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

$bt_id    = $_POST['bt_action_id'] ?: '';
$bt_class = $_POST['bt_action_class'] ?: '';

$config_nome_id        = $_POST['config_nome_id'] ?: '';
$config_nome_class     = $_POST['config_nome_class'] ?: '';

$config_email_id       = $_POST['config_email_id'] ?: '';
$config_email_class    = $_POST['config_email_class'] ?: '';

$config_crm_id         = $_POST['config_crm_id'] ?: '';
$config_crm_class      = $_POST['config_crm_class'] ?: '';

$config_uf_id          = $_POST['config_uf_id'] ?: '';
$config_uf_class       = $_POST['config_uf_class'] ?: '';

$form_id                         = $_POST['config_form_id'] ?: 'track_form_id';
$form_class                      = $_POST['config_form_class'] ?: 'track_form_class';

$novo_dado = '{
  "insert": "trackform",
  "id": {
    "nome": "'.$config_nome_id.'",
    "email": "'.$config_email_id.'",
    "crm": "'.$config_crm_id.'",
    "uf": "'.$config_uf_id.'"
  },
  "class": {
    "nome": "'.$config_nome_class.'",
    "email": "'.$config_email_class.'",
    "crm": "'.$config_crm_class.'",
    "uf": "'.$config_uf_class.'"
  },
  "buttom": {
    "id": "'.$bt_id.'",
    "class": "'.$bt_class.'"
  },
  "form": {
    "id": "'.$form_id.'",
    "class": "'.$form_class.'"
  }
}';

 $unique_id = uniqid();

 $prepared_insert_array = [
    'script_name'      => $config_script_name,
    'script_origem'    => $base_url,
    'script_id'        => $unique_id,
    'script_parametro' => $novo_dado
    ];
            
    $createSiteViews = new Core_create;
    $createSiteViews->ExeCreate('pd_script', $prepared_insert_array);

echo $unique_id;

  exit;
  
}




//UPDATE SCRIPT MODE EVENT
if( isset($_POST['event-updatescript'])){
    
$config_id    = $_POST['id_update'] ?: '';  
    
$config_script_name    = $_POST['config_script_name'] ?: '';
$config_script_origem  = $_POST['config_script_origem'] ?: '';

// Usar parse_url para obter o esquema (http ou https) e o host (domínio)
$parsed_url = parse_url($config_script_origem);

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

$bt_id    = $_POST['bt_action_id'] ?: '';
$bt_class = $_POST['bt_action_class'] ?: '';

$config_nome_id        = $_POST['config_nome_id'] ?: '';
$config_nome_class     = $_POST['config_nome_class'] ?: '';

$config_email_id       = $_POST['config_email_id'] ?: '';
$config_email_class    = $_POST['config_email_class'] ?: '';

$config_crm_id         = $_POST['config_crm_id'] ?: '';
$config_crm_class      = $_POST['config_crm_class'] ?: '';

$config_uf_id          = $_POST['config_uf_id'] ?: '';
$config_uf_class       = $_POST['config_uf_class'] ?: '';

$evento_id             = $_POST['config_eventname_id'] ?: '';
$evento_class          = $_POST['config_eventname_class'] ?: '';

$config_celular_id               = $_POST['config_celular_id'] ?: '';
$config_celular_class            = $_POST['config_celular_class'] ?: '';

$config_especialidade_id         = $_POST['config_especialidade_id'] ?: '';
$config_especialidade_class      = $_POST['config_especialidade_class'] ?: '';

$config_optin_id                 = $_POST['config_optin_id'] ?: '';
$config_optin_class              = $_POST['config_optin_class'] ?: '';

$form_id                         = $_POST['config_form_id'] ?: 'event_adtrack_form_id';
$form_class                      = $_POST['config_form_class'] ?: 'event_adtrack_form_class';

$checkin           = $_POST['check_checkin'] ?: false;

$novo_dado = '{
  "insert": "trackform",
  "id": {
    "nome": "'.$config_nome_id.'",
    "email": "'.$config_email_id.'",
    "crm": "'.$config_crm_id.'",
    "uf": "'.$config_uf_id.'",
    "celular": "'.$config_celular_id.'",
    "especialidade": "'.$config_especialidade_id.'",
    "optin": "'.$config_optin_id.'"
  },
  "class": {
    "nome": "'.$config_nome_class.'",
    "email": "'.$config_email_class.'",
    "crm": "'.$config_crm_class.'",
    "uf": "'.$config_uf_class.'",
    "celular": "'.$config_celular_class.'",
    "especialidade": "'.$config_especialidade_class.'",
    "optin": "'.$config_optin_class.'"
  },
  "buttom": {
    "id": "'.$bt_id.'",
    "class": "'.$bt_class.'"
  },
  "form": {
    "id": "'.$form_id.'",
    "class": "'.$form_class.'"
  },
  "evento": {
    "id": "'.$evento_id.'",
    "class": "'.$evento_class.'"
  },
  "checkin": {
    "active": "'.$checkin.'"
  }
}';

 $prepared_insert_array = [
    'script_name'      => $config_script_name,
    'script_origem'    => $base_url,
    'script_parametro' => $novo_dado
    ];
            
$updateScript  = new Core_update(); 
$updateScript->ExeUpdate('pd_script', $prepared_insert_array, "WHERE id = :id", "id={$config_id}");

if ($updateScript->getResult()){
    
    echo 'sucesso';
    
}else{
    
    echo 'error';
}

  exit;  
    
}


//INSERT SCRIPT MODE EVENT
if( isset($_POST['event-addscript'])){
	
$config_script_name    = $_POST['config_script_name'] ?: exit;
$config_script_origem  = $_POST['config_script_origem'] ?: exit;

// Usar parse_url para obter o esquema (http ou https) e o host (domínio)
$parsed_url = parse_url($config_script_origem);

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

$bt_id    = $_POST['bt_action_id'] ?: '';
$bt_class = $_POST['bt_action_class'] ?: '';

$config_nome_id        = $_POST['config_nome_id'] ?: '';
$config_nome_class     = $_POST['config_nome_class'] ?: '';

$config_email_id       = $_POST['config_email_id'] ?: '';
$config_email_class    = $_POST['config_email_class'] ?: '';

$config_crm_id         = $_POST['config_crm_id'] ?: '';
$config_crm_class      = $_POST['config_crm_class'] ?: '';

$config_uf_id          = $_POST['config_uf_id'] ?: '';
$config_uf_class       = $_POST['config_uf_class'] ?: '';

$evento_id             = $_POST['config_eventname_id'] ?: '';
$evento_class          = $_POST['config_eventname_class'] ?: '';

$config_celular_id               = $_POST['config_celular_id'] ?: '';
$config_celular_class            = $_POST['config_celular_class'] ?: '';

$config_especialidade_id         = $_POST['config_especialidade_id'] ?: '';
$config_especialidade_class      = $_POST['config_especialidade_class'] ?: '';

$config_optin_id                 = $_POST['config_optin_id'] ?: '';
$config_optin_class              = $_POST['config_optin_class'] ?: '';

$form_id                 = $_POST['config_form_id'] ?: 'event_adtrack_form_id';
$form_class              = $_POST['config_form_class'] ?: 'event_adtrack_form_class';

$checkin           = $_POST['check_checkin'] ?: false;

$novo_dado = '{
  "insert": "trackform",
  "id": {
    "nome": "'.$config_nome_id.'",
    "email": "'.$config_email_id.'",
    "crm": "'.$config_crm_id.'",
    "uf": "'.$config_uf_id.'",
    "celular": "'.$config_celular_id.'",
    "especialidade": "'.$config_especialidade_id.'",
    "optin": "'.$config_optin_id.'"
  },
  "class": {
    "nome": "'.$config_nome_class.'",
    "email": "'.$config_email_class.'",
    "crm": "'.$config_crm_class.'",
    "uf": "'.$config_uf_class.'",
    "celular": "'.$config_celular_class.'",
    "especialidade": "'.$config_especialidade_class.'",
    "optin": "'.$config_optin_class.'"
  },
  "buttom": {
    "id": "'.$bt_id.'",
    "class": "'.$bt_class.'"
  },
  "form": {
    "id": "'.$form_id.'",
    "class": "'.$form_class.'"
  },
  "evento": {
    "id": "'.$evento_id.'",
    "class": "'.$evento_class.'"
  },
  "checkin": {
    "active": "'.$checkin.'"
  }
}';

 $unique_id = uniqid();

 $prepared_insert_array = [
    'script_name'      => $config_script_name,
    'script_origem'    => $base_url,
    'script_id'        => $unique_id,
    'script_parametro' => $novo_dado,
    'script_type'      => 1
    ];
            
    $createSiteViews = new Core_create;
    $createSiteViews->ExeCreate('pd_script', $prepared_insert_array);

echo $unique_id;

  exit;
  
}



// PAGINA SETTINGS PAGE
if($parametros_get_page['pag_name'] == 'Admin Settings' && isset($_SESSION['fideliza_logado-admin'])){

    $select_db = $parametros_response['select_db'];
	$select_db->ExeRead("*",  'pd_script ', "WHERE script_type = 0 ORDER BY id desc", "");

	$tr = '';
	
for($i=0;$i<count($select_db->getResult());$i++){
	
	$tr .= '<tr id="tr'.$select_db->getResult()[$i]['id'].'">
	<td>'.$select_db->getResult()[$i]['script_origem'].'</td>
	<td>'.$select_db->getResult()[$i]['script_name'].'</td>
	<td><button class="btn-shadow btn-pill btn-wide btn btn-success clipboard-trigger" data-clipboard-text="'.$select_db->getResult()[$i]['script_id'].'">'.$select_db->getResult()[$i]['script_id'].'</button></td>
	<td><button class="mr-2 btn-icon btn-icon-only btn btn-outline-danger btn-sm deleteButton" data-id="'.$select_db->getResult()[$i]['id'].'"><i class="pe-7s-trash" style="font-size: 20px;"></i></button>
	<button class="mr-2 btn-icon btn-icon-only btn btn-outline-warning btn-sm EditButton" data-id="'.$select_db->getResult()[$i]['id'].'"><i class="fa fa-fw" aria-hidden="true" title="Copy to use edit" style="font-size: 20px;"></i></button></td>
	<td>
<div class="page-title-icon">
<a href="javascript:void(0)" data-toggle="modal" data-target=".bd-example-modal-lg" class="ModalConfig" data-id="'.$select_db->getResult()[$i]['script_id'].'"><i class="pe-7s-config" style="font-size: 23px;"> </i></a>
</div>
	</tr>';
}

$a[] = '{instancias}';   $b[]  = $tr;

}


// PAGINA SETTINGS EVENTS
if($parametros_get_page['pag_name'] == 'Admin Settings Events' && isset($_SESSION['fideliza_logado-admin'])){

    $select_db = $parametros_response['select_db'];
	$select_db->ExeRead("*",  'pd_script ', "WHERE script_type = 1 ORDER BY id desc", "");

	$tr = '';
	
for($i=0;$i<count($select_db->getResult());$i++){
	
	$tr .= '<tr id="tr'.$select_db->getResult()[$i]['id'].'">
	<td>'.$select_db->getResult()[$i]['script_origem'].'</td>
	<td>'.$select_db->getResult()[$i]['script_name'].'</td>
	<td><button class="btn-shadow btn-pill btn-wide btn btn-success clipboard-trigger" data-clipboard-text="'.$select_db->getResult()[$i]['script_id'].'">'.$select_db->getResult()[$i]['script_id'].'</button></td>
	<td><button class="mr-2 btn-icon btn-icon-only btn btn-outline-danger btn-sm deleteButton" data-id="'.$select_db->getResult()[$i]['id'].'"><i class="pe-7s-trash" style="font-size: 20px;"></i></button>
	<button class="mr-2 btn-icon btn-icon-only btn btn-outline-warning btn-sm EditButton" data-id="'.$select_db->getResult()[$i]['id'].'"><i class="fa fa-fw" aria-hidden="true" title="Copy to use edit" style="font-size: 20px;"></i></button></td>
	<td>
<div class="page-title-icon">
<a href="javascript:void(0)" data-toggle="modal" data-target=".bd-example-modal-lg" class="ModalConfig" data-id="'.$select_db->getResult()[$i]['script_id'].'"><i class="pe-7s-config" style="font-size: 23px;"> </i></a>
</div>
	</tr>';
}

$a[] = '{instancias_eventos}';   $b[]  = $tr;

}



if(isset($_GET['event_script_edit'])){
  
    $id = $_GET['event_script_edit'];
    
    $select_db = $parametros_response['select_db'];
    $select_db->ExeRead("*", 'pd_script', "WHERE id = :e", "e={$id}");

 if ($select_db->getResult()) { 

$data = json_decode($select_db->getResult()[0]['script_parametro'], true);

$origem    = $select_db->getResult()[0]['script_origem'];
$instancia = $select_db->getResult()[0]['script_name'];

// Definir os campos para IDs, usando um valor padrão se o campo estiver vazio
$nome_id     = !empty($data['id']['nome']) ? htmlspecialchars($data['id']['nome'], ENT_QUOTES, 'UTF-8') : 'ev_track_nome';
$email_id    = !empty($data['id']['email']) ? htmlspecialchars($data['id']['email'], ENT_QUOTES, 'UTF-8') : 'ev_track_email';
$crm_id      = !empty($data['id']['crm']) ? htmlspecialchars($data['id']['crm'], ENT_QUOTES, 'UTF-8') : 'ev_track_crm';
$uf_id       = !empty($data['id']['uf']) ? htmlspecialchars($data['id']['uf'], ENT_QUOTES, 'UTF-8') : 'ev_track_uf';

$celular_id           = !empty($data['id']['celular']) ? htmlspecialchars($data['id']['celular'], ENT_QUOTES, 'UTF-8') : 'ev_track_celular';
$especialidade_id     = !empty($data['id']['especialidade']) ? htmlspecialchars($data['id']['especialidade'], ENT_QUOTES, 'UTF-8') : 'ev_track_especialidade';
$optin_id             = !empty($data['id']['optin']) ? htmlspecialchars($data['id']['optin'], ENT_QUOTES, 'UTF-8') : 'ev_track_optin';

// Definir os campos para classes, usando um valor padrão se o campo estiver vazio
$nome_class     = !empty($data['class']['nome']) ?  htmlspecialchars($data['class']['nome'], ENT_QUOTES, 'UTF-8') : 'ev_track_nome';
$email_class    = !empty($data['class']['email']) ? htmlspecialchars($data['class']['email'], ENT_QUOTES, 'UTF-8') : 'ev_track_email';
$crm_class      = !empty($data['class']['crm']) ? htmlspecialchars($data['class']['crm'], ENT_QUOTES, 'UTF-8') : 'ev_track_crm';
$uf_class       = !empty($data['class']['uf']) ?  htmlspecialchars($data['class']['uf'], ENT_QUOTES, 'UTF-8') : 'ev_track_uf';

$celular_class           = !empty($data['class']['celular']) ? htmlspecialchars($data['class']['celular'], ENT_QUOTES, 'UTF-8') : 'ev_track_celular';
$especialidade_class     = !empty($data['class']['especialidade']) ? htmlspecialchars($data['class']['especialidade'], ENT_QUOTES, 'UTF-8') : 'ev_track_especialidade';
$optin_class             = !empty($data['class']['optin']) ? htmlspecialchars($data['class']['optin'], ENT_QUOTES, 'UTF-8') : 'ev_track_optin';

// Definir botão, usando valor padrão se o campo estiver vazio
$bt_id       = !empty($data['buttom']['id']) ? htmlspecialchars($data['buttom']['id'], ENT_QUOTES, 'UTF-8') : 'ev_adtrack';
$bt_class    = !empty($data['buttom']['class']) ? htmlspecialchars($data['buttom']['class'], ENT_QUOTES, 'UTF-8') : 'ev_adtrack';

// Definir se o formulário está ativo
$form_id    = $data['form']['id'];
$form_class = $data['form']['class'];

// Definir se o formulário está ativo
$evento_id    = $data['evento']['id'];
$evento_class = $data['evento']['class'];

// Definir se o formulário está ativo
if($data['checkin']['active'] == 'true'){
$checkin   = 'checked';
}else{
$checkin   = '';
}

   
$a[] = '{event_id_update}';                $b[]  = $id;
$a[] = '{event_checkin}';                  $b[]  = $checkin;

$a[] = '{event_form_id}';                  $b[]  = $form_id;
$a[] = '{event_form_class}';               $b[]  = $form_class;

$a[] = '{event_instancia}';                $b[]  = $instancia;
$a[] = '{event_origem}';                   $b[]  = $origem;

$a[] = '{event_bt_id}';                    $b[]  = $bt_id;
$a[] = '{event_bt_class}';                 $b[]  = $bt_class;

$a[] = '{event_especialidade_id}';         $b[]  = $especialidade_id;
$a[] = '{event_especialidade_class}';      $b[]  = $especialidade_class;

$a[] = '{event_celular_id}';               $b[]  = $celular_id;
$a[] = '{event_celular_class}';            $b[]  = $celular_class;

$a[] = '{event_uf_id}';                    $b[]  = $uf_id;
$a[] = '{event_uf_class}';                 $b[]  = $uf_class;

$a[] = '{event_crm_id}';                   $b[]  = $crm_id;
$a[] = '{event_crm_class}';                $b[]  = $crm_class;

$a[] = '{event_email_class}';              $b[]  = $email_class;
$a[] = '{event_email_id}';                 $b[]  = $email_id;

$a[] = '{event_nome_class}';               $b[]  = $nome_class;
$a[] = '{event_nome_id}';                  $b[]  = $nome_id;

$a[] = '{event_eventname_id}';             $b[]  = $evento_id;
$a[] = '{event_eventname_class}';          $b[]  = $evento_class;

$a[] = '{event_optin_id}';                 $b[]  = 'event_optin_id';
$a[] = '{event_optin_class}';              $b[]  = 'event_optin_class';

}else{
    
$a[] = '{event_id_update}';                $b[]  = '';
$a[] = '{event_form_id}';                  $b[]  = 'event_adtrack_form';
$a[] = '{event_form_class}';               $b[]  = 'event_adtrack_form';
$a[] = '{event_checkin}';                  $b[]  = '';
$a[] = '{event_bt_class}';                 $b[]  = 'event_bt';
$a[] = '{event_bt_id}';                    $b[]  = 'event_bt';
$a[] = '{event_especialidade_class}';      $b[]  = 'event_especialidade';
$a[] = '{event_especialidade_id}';         $b[]  = 'event_especialidade';
$a[] = '{event_celular_class}';            $b[]  = 'event_celular';
$a[] = '{event_celular_id}';               $b[]  = 'event_celular';
$a[] = '{event_uf_class}';                 $b[]  = 'event_uf';
$a[] = '{event_uf_id}';                    $b[]  = 'event_uf';
$a[] = '{event_crm_class}';                $b[]  = 'event_crm';
$a[] = '{event_crm_id}';                   $b[]  = 'event_crm';
$a[] = '{event_email_class}';              $b[]  = 'event_email';
$a[] = '{event_email_id}';                 $b[]  = 'event_email';
$a[] = '{event_nome_class}';               $b[]  = 'event_nome';
$a[] = '{event_nome_id}';                  $b[]  = 'event_nome';
$a[] = '{event_optin_id}';                 $b[]  = 'event_optin_id';
$a[] = '{event_optin_class}';              $b[]  = 'event_optin_class';
$a[] = '{event_eventname_id}';             $b[]  = 'event_eventname_id';
$a[] = '{event_eventname_class}';          $b[]  = 'event_eventname_class';


$a[] = '{event_instancia}';                $b[]  = '';
$a[] = '{event_origem}';                   $b[]  = '';
    
}
    
    
}else{
    
$a[] = '{event_id_update}';                $b[]  = '';
$a[] = '{event_form_id}';                  $b[]  = 'event_adtrack_form';
$a[] = '{event_form_class}';               $b[]  = 'event_adtrack_form';
$a[] = '{event_checkin}';                  $b[]  = '';
$a[] = '{event_bt_class}';                 $b[]  = 'event_bt';
$a[] = '{event_bt_id}';                    $b[]  = 'event_bt';
$a[] = '{event_especialidade_class}';      $b[]  = 'event_especialidade';
$a[] = '{event_especialidade_id}';         $b[]  = 'event_especialidade';
$a[] = '{event_celular_class}';            $b[]  = 'event_celular';
$a[] = '{event_celular_id}';               $b[]  = 'event_celular';
$a[] = '{event_uf_class}';                 $b[]  = 'event_uf';
$a[] = '{event_uf_id}';                    $b[]  = 'event_uf';
$a[] = '{event_crm_class}';                $b[]  = 'event_crm';
$a[] = '{event_crm_id}';                   $b[]  = 'event_crm';
$a[] = '{event_email_class}';              $b[]  = 'event_email';
$a[] = '{event_email_id}';                 $b[]  = 'event_email';
$a[] = '{event_nome_class}';               $b[]  = 'event_nome';
$a[] = '{event_nome_id}';                  $b[]  = 'event_nome';
$a[] = '{event_optin_id}';                 $b[]  = 'event_optin_id';
$a[] = '{event_optin_class}';              $b[]  = 'event_optin_class';
$a[] = '{event_eventname_id}';             $b[]  = 'event_eventname_id';
$a[] = '{event_eventname_class}';          $b[]  = 'event_eventname_class';
$a[] = '{event_optin_id}';                 $b[] =  'event_optin_id';
$a[] = '{event_optin_class}';              $b[] =  'event_optin_class';

$a[] = '{event_instancia}';                $b[]  = '';
$a[] = '{event_origem}';                   $b[]  = '';
    
}




if(isset($_GET['script_edit'])){
    
    $id = $_GET['script_edit'];
    
    $select_db = $parametros_response['select_db'];
    $select_db->ExeRead("*", 'pd_script', "WHERE id = :e", "e={$id}");

 if ($select_db->getResult()) {
        
$data = json_decode($select_db->getResult()[0]['script_parametro'], true);

$origem    = $select_db->getResult()[0]['script_origem'];
$instancia = $select_db->getResult()[0]['script_name'];

// Definir os campos para IDs, usando um valor padrão se o campo estiver vazio
$nome_id     = !empty($data['id']['nome']) ? htmlspecialchars($data['id']['nome'], ENT_QUOTES, 'UTF-8') : 'track_nome';
$email_id    = !empty($data['id']['email']) ? htmlspecialchars($data['id']['email'], ENT_QUOTES, 'UTF-8') : 'track_email';
$crm_id      = !empty($data['id']['crm']) ? htmlspecialchars($data['id']['crm'], ENT_QUOTES, 'UTF-8') : 'track_crm';
$uf_id       = !empty($data['id']['uf']) ? htmlspecialchars($data['id']['uf'], ENT_QUOTES, 'UTF-8') : 'track_uf';

// Definir os campos para classes, usando um valor padrão se o campo estiver vazio
$nome_class     = !empty($data['class']['nome']) ?  htmlspecialchars($data['class']['nome'], ENT_QUOTES, 'UTF-8') : 'track_nome';
$email_class    = !empty($data['class']['email']) ? htmlspecialchars($data['class']['email'], ENT_QUOTES, 'UTF-8') : 'track_email';
$crm_class      = !empty($data['class']['crm']) ? htmlspecialchars($data['class']['crm'], ENT_QUOTES, 'UTF-8') : 'track_crm';
$uf_class       = !empty($data['class']['uf']) ?  htmlspecialchars($data['class']['uf'], ENT_QUOTES, 'UTF-8') : 'track_uf';

// Definir botão, usando valor padrão se o campo estiver vazio
$bt_id       = !empty($data['buttom']['id']) ? htmlspecialchars($data['buttom']['id'], ENT_QUOTES, 'UTF-8') : 'adtrack';
$bt_class    = !empty($data['buttom']['class']) ? htmlspecialchars($data['buttom']['class'], ENT_QUOTES, 'UTF-8') : 'adtrack';

// Definir se o formulário está ativo
$form_id    = $data['form']['id'];
$form_class = $data['form']['class'];



   $a[] = '{set_origem}';        $b[]  = $origem;
   $a[] = '{set_instancia}';     $b[]  = $instancia;
   $a[] = '{set_nome_id}';       $b[]  = $nome_id;
   $a[] = '{set_nome_class}';    $b[]  = $nome_class;
   $a[] = '{set_email_id}';      $b[]  = $email_id;
   $a[] = '{set_email_class}';   $b[]  = $email_class;
   $a[] = '{set_crm_id}';        $b[]  = $crm_id;
   $a[] = '{set_crm_class}';     $b[]  = $crm_class;
   $a[] = '{set_uf_id}';         $b[]  = $uf_id;
   $a[] = '{set_uf_class}';      $b[]  = $uf_class;
   $a[] = '{set_bt_id}';         $b[]  = $bt_id;
   $a[] = '{set_bt_class}';      $b[]  = $bt_class;
   $a[] = '{set_form_id}';       $b[]  = $form_id;
   $a[] = '{set_form_class}';    $b[]  = $form_class;
   $a[] = '{set_id_update}';     $b[]  = $id;
   
   
 }else{
     
    
   $a[] = '{set_origem}';        $b[]  = '';
   $a[] = '{set_instancia}';     $b[]  = '';
   $a[] = '{set_nome_id}';       $b[]  = 'track_nome';
   $a[] = '{set_nome_class}';    $b[]  = 'track_nome';
   $a[] = '{set_email_id}';      $b[]  = 'track_email';
   $a[] = '{set_email_class}';   $b[]  = 'track_email';
   $a[] = '{set_crm_id}';        $b[]  = 'track_crm';
   $a[] = '{set_crm_class}';     $b[]  = 'track_crm';
   $a[] = '{set_uf_id}';         $b[]  = 'track_uf';
   $a[] = '{set_uf_class}';      $b[]  = 'track_uf';
   $a[] = '{set_bt_id}';         $b[]  = 'adtrack';
   $a[] = '{set_bt_class}';      $b[]  = 'adtrack';
   $a[] = '{set_form_id}';       $b[]  = 'adtrack_form';
   $a[] = '{set_form_class}';    $b[]  = 'adtrack_form';
   $a[] = '{set_id_update}';     $b[]  = '';
   
 }

}else{
    
    
   $a[] = '{set_origem}';        $b[]  = '';
   $a[] = '{set_instancia}';     $b[]  = '';
   $a[] = '{set_nome_id}';       $b[]  = 'track_nome';
   $a[] = '{set_nome_class}';    $b[]  = 'track_nome';
   $a[] = '{set_email_id}';      $b[]  = 'track_email';
   $a[] = '{set_email_class}';   $b[]  = 'track_email';
   $a[] = '{set_crm_id}';        $b[]  = 'track_crm';
   $a[] = '{set_crm_class}';     $b[]  = 'track_crm';
   $a[] = '{set_uf_id}';         $b[]  = 'track_uf';
   $a[] = '{set_uf_class}';      $b[]  = 'track_uf';
   $a[] = '{set_bt_id}';         $b[]  = 'adtrack';
   $a[] = '{set_bt_class}';      $b[]  = 'adtrack';
   $a[] = '{set_form_id}';       $b[]  = 'adtrack_form';
   $a[] = '{set_form_class}';    $b[]  = 'adtrack_form';
   $a[] = '{set_id_update}';     $b[]  = '';
   $a[] = '{set_id_update}';     $b[]  = '';
}



if (isset($_GET['exportev'])) {
    
error_reporting(0); // Desativa a notificação de todos os erros
ini_set('display_errors', 0); // Não exibe erros na tela

    require 'vendor/autoload.php'; // Certifique-se de ajustar o caminho conforme necessário

    $ajaxtable = $_GET['exportev'];
    $origem    = $_GET['origem'];
    $evento    = $_GET['evento'];

    // Dividir a string para separar as datas de início e fim
    list($datastart, $dataend) = explode(' - ', $ajaxtable);

    // Criar objetos DateTime e formatá-los como 'yyyymmdd'
    $datastart = DateTime::createFromFormat('m/d/Y', $datastart)->format('Ymd');
    $dataend = DateTime::createFromFormat('m/d/Y', $dataend)->format('Ymd');

    // Realizar a consulta no banco de dados
$select_db->ExeRead(
    "t.date, t.email, t.type, t.origem, t.checkinC, t.checkin, t.eventname, u.user_name, u.user_email, u.user_celular, u.user_optin, u.user_especialidade, u.origem, u.user_cod, u.user_uf, 
    t.timeSpent, 
    t.url",
    "pd_track t 
    LEFT JOIN pd_users u ON t.email = u.user_email",
    "WHERE t.type = 1 AND t.datatime >= '{$datastart}' AND t.datatime <= '{$dataend}' 
    AND t.eventname = '$evento' AND t.origem = '$origem' 
    ORDER BY t.id DESC 
    LIMIT 0, 3000",
    ""
);

    $results = $select_db->getResult();

    // Criar um novo objeto PHPExcel
    $objPHPExcel = new \PHPExcel();
    $objPHPExcel->setActiveSheetIndex(0);

    // Definir cabeçalhos
    $objPHPExcel->getActiveSheet()->setCellValue('A1', 'NOME');
    $objPHPExcel->getActiveSheet()->setCellValue('B1', 'EMAIL');
    $objPHPExcel->getActiveSheet()->setCellValue('C1', 'CRM');
    $objPHPExcel->getActiveSheet()->setCellValue('D1', 'UF');
    $objPHPExcel->getActiveSheet()->setCellValue('E1', 'CELULAR');
    $objPHPExcel->getActiveSheet()->setCellValue('F1', 'ESPECIALIDADE');
    $objPHPExcel->getActiveSheet()->setCellValue('G1', 'EVENTO');
    $objPHPExcel->getActiveSheet()->setCellValue('H1', 'ORIGEM');
    $objPHPExcel->getActiveSheet()->setCellValue('I1', 'CAD');
    $objPHPExcel->getActiveSheet()->setCellValue('J1', 'CHE');
    $objPHPExcel->getActiveSheet()->setCellValue('K1', 'OPTIN');
    $objPHPExcel->getActiveSheet()->setCellValue('L1', 'DATE');

    // Preencher dados
    $rowNumber = 2; // Começar na segunda linha
    
    foreach ($results as $row) {
        /*  
        echo 'Nome: ' . $row['user_name'] . '<br>';
        echo 'Email: ' . $row['user_email'] . '<br>';
        echo 'CRM: ' . $row['user_cod'] . '<br>';
        echo 'UF: ' . $row['user_uf'] . '<br>';
        echo 'CELULAR: ' . $row['user_celular']. '<br>';
        echo 'ESPECIALISTA: ' . $row['user_especialidade']. '<br>';
        echo 'EVENTO: ' . $evento . '<br>';
        echo 'ORIGEM: ' . $origem. '<br>';
        echo 'CAD: ' . $row['checkinC']. '<br>';
        echo 'CHE: ' . $row['checkin']. '<br>';
        echo 'OPTIN: ' . $row['user_optin']. '<br>';
        echo 'DATA: ' . $row['date']. '<br>';
        
 */
    
        $objPHPExcel->getActiveSheet()->setCellValue('A' . $rowNumber, $row['user_name']);
        $objPHPExcel->getActiveSheet()->setCellValue('B' . $rowNumber, $row['user_email']);
        $objPHPExcel->getActiveSheet()->setCellValue('C' . $rowNumber, $row['user_cod']);
        $objPHPExcel->getActiveSheet()->setCellValue('D' . $rowNumber, $row['user_uf']);
        $objPHPExcel->getActiveSheet()->setCellValue('E' . $rowNumber, $row['user_celular']);
        $objPHPExcel->getActiveSheet()->setCellValue('F' . $rowNumber, $row['user_especialidade']);
        $objPHPExcel->getActiveSheet()->setCellValue('G' . $rowNumber, $evento);
        $objPHPExcel->getActiveSheet()->setCellValue('H' . $rowNumber, $origem);
        $objPHPExcel->getActiveSheet()->setCellValue('I' . $rowNumber, $row['checkinC']);
        $objPHPExcel->getActiveSheet()->setCellValue('J' . $rowNumber, $row['checkin']);
        $objPHPExcel->getActiveSheet()->setCellValue('K' . $rowNumber, $row['user_optin']);
        $objPHPExcel->getActiveSheet()->setCellValue('L' . $rowNumber, $row['date']);

        $rowNumber++;
    }



    // Definir o nome do arquivo
    $fileName = "tracking_data_" . date('Y-m-d_H-i-s') . ".xlsx";

    // Configurar cabeçalhos HTTP para download do arquivo Excel
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="' . $fileName . '"');
    header('Cache-Control: max-age=0');

    // Salvar o arquivo Excel para o output
    $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    $objWriter->save('php://output');
    
   

}




if (isset($_GET['export'])) {

    require 'vendor/autoload.php'; // Certifique-se de ajustar o caminho conforme necessário

    $ajaxtable = $_GET['export'];

    // Dividir a string para separar as datas de início e fim
    list($datastart, $dataend) = explode(' - ', $ajaxtable);

    // Criar objetos DateTime e formatá-los como 'yyyymmdd'
    $datastart = DateTime::createFromFormat('m/d/Y', $datastart)->format('Ymd');
    $dataend = DateTime::createFromFormat('m/d/Y', $dataend)->format('Ymd');

    // Realizar a consulta no banco de dados
    $select_db->ExeRead(
        "t.url, t.date, t.timeSpent, u.user_email, u.user_name, u.user_cod",
        "pd_track t INNER JOIN pd_users u ON t.email = u.user_email",
        "WHERE t.datatime >= '{$datastart}' AND t.datatime <= '{$dataend}'"
    );
    $results = $select_db->getResult();

    // Criar um novo objeto PHPExcel
    $objPHPExcel = new \PHPExcel();
    $objPHPExcel->setActiveSheetIndex(0);

    // Definir cabeçalhos
    $objPHPExcel->getActiveSheet()->setCellValue('A1', 'EMAIL');
    $objPHPExcel->getActiveSheet()->setCellValue('B1', 'NOME');
    $objPHPExcel->getActiveSheet()->setCellValue('C1', 'CRM');
    $objPHPExcel->getActiveSheet()->setCellValue('D1', 'URL');
    $objPHPExcel->getActiveSheet()->setCellValue('E1', 'TEMPO MEDIO');
    $objPHPExcel->getActiveSheet()->setCellValue('F1', 'DATE');

    // Preencher dados
    $rowNumber = 2; // Começar na segunda linha
    foreach ($results as $row) {
        $formatted_time = sprintf('%02d:%02d', floor($row['timeSpent'] / 60), $row['timeSpent'] % 60); // Convert time to minutes and seconds

        $objPHPExcel->getActiveSheet()->setCellValue('A' . $rowNumber, $row['user_email']);
        $objPHPExcel->getActiveSheet()->setCellValue('B' . $rowNumber, $row['user_name']);
        $objPHPExcel->getActiveSheet()->setCellValue('C' . $rowNumber, $row['user_cod']);
        $objPHPExcel->getActiveSheet()->setCellValue('D' . $rowNumber, $row['url']);
        $objPHPExcel->getActiveSheet()->setCellValue('E' . $rowNumber, $formatted_time);
        $objPHPExcel->getActiveSheet()->setCellValue('F' . $rowNumber, $row['date']);

        $rowNumber++;
    }

    // Definir o nome do arquivo
    $fileName = "tracking_data_" . date('Y-m-d_H-i-s') . ".xlsx";

    // Configurar cabeçalhos HTTP para download do arquivo Excel
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="' . $fileName . '"');
    header('Cache-Control: max-age=0');

    // Salvar o arquivo Excel para o output
    $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    $objWriter->save('php://output');
    exit;
}



if (isset($_GET['trackpages'])) {

    $html = '';
    $email = $_GET['trackpages'] ?? '';
    $data = $_GET['trackdate'] ?? date("Y-m-d");

    // Executa a consulta no banco de dados
    $select_db->ExeRead("url, date, timeSpent", "pd_track", "WHERE email = :em AND up = 1 AND type = 0 AND date LIKE '%' :d '%'", "em={$email}&d={$data}");
    $results = $select_db->getResult();


    foreach ($results as $row) {
        $url = $row['url'];
        $formatted_date = date('d/m/Y H:i:s', strtotime($row['date']));
        $timeSpent = $row['timeSpent'];

        $formatted_time = sprintf('%02d:%02d', floor($row['timeSpent'] / 60), $row['timeSpent'] % 60);  // Converte o tempo para minutos e segundos

        $html .= "<tr>
                    <td>{$url}</td>
                    <td>{$row['date']}</td>
                    <td>{$formatted_time}</td>
                  </tr>";
    }

    echo $html;
    exit;
}


$data_filter_dia = date("Y-m-d");
$data_filter_mes = date("Y-m");

$select_db->ExeRead(
    "COUNT(DISTINCT email) AS unique_emails, COUNT(url) AS total_pages", 
    'pd_track', 
    "WHERE date LIKE '%' :d '%' AND up = 1 AND email LIKE '%@%' AND type = 0", 
    "d={$data_filter_dia}"
);

$result_dia = $select_db->getResult();

$select_db->ExeRead(
    "COUNT(DISTINCT email) AS unique_emails, COUNT(url) AS total_pages", 
    'pd_track', 
    "WHERE date LIKE '%' :d '%' AND up = 1 AND email LIKE '%@%' AND type = 0", 
    "d={$data_filter_mes}"
);

$result_mes = $select_db->getResult();



// GET EVENTS NAME AJAX
if (isset($_GET['geteventname'])){
    
   $ajaxtablename = $_GET['geteventname'];
   $ajaxtable     = $_GET['geteventnamedata'];
    
   // Dividir a string para separar as datas de início e fim
list($datastart, $dataend) = explode(' - ', $ajaxtable);

// Criar objetos DateTime e formatá-los como 'yyyymmdd'
$datastart = DateTime::createFromFormat('m/d/Y', $datastart)->format('Ymd');
$dataend = DateTime::createFromFormat('m/d/Y', $dataend)->format('Ymd');

    $select_db->ExeRead(
        "DISTINCT eventname",
        'pd_track',
        "WHERE eventname LIKE '%$ajaxtablename%' AND type = 1 AND type = 1 AND datatime >= '{$datastart}' AND datatime <= '{$dataend}'",
        ""
    );

    $result = $select_db->getResult(); 
    
    for($e = 0; $e < count($result); $e++){
       
      echo '<a class="bt_ajax" href="javascript:void(0)" onclick="jQuery(\'#search-box\').fadeOut();jQuery(\'#search-event\').val(\''. htmlspecialchars($result[$e]['eventname'], ENT_QUOTES) .'\')">' . htmlspecialchars($result[$e]['eventname'], ENT_QUOTES) . '</a><br>';

        
    }
    
    exit;
}

// GET EVENTS ORIGE AJAX
if(isset($_GET['getorigem'])){
    
    $or = $_GET['getorigem'];
    
        $select_db->ExeRead(
        "DISTINCT script_origem",
        'pd_script',
        "WHERE script_origem LIKE '%$or%'",
        "");
        
         $result = $select_db->getResult(); 
    
    for($e = 0; $e < count($result); $e++){
       
      echo '<a class="bt_ajax" href="javascript:void(0)" onclick="jQuery(\'#search-box2\').fadeOut();jQuery(\'#search-event2\').val(\''. htmlspecialchars($result[$e]['script_origem'], ENT_QUOTES) .'\')">' . htmlspecialchars($result[$e]['script_origem'], ENT_QUOTES) . '</a><br>';

        
    }   
    
   exit;
   
}


if (isset($_GET['ajaxtable'])){

$ajaxtable = $_GET['ajaxtable'];

// Dividir a string para separar as datas de início e fim
list($datastart, $dataend) = explode(' - ', $ajaxtable);

// Criar objetos DateTime e formatá-los como 'yyyymmdd'
$datastart = DateTime::createFromFormat('m/d/Y', $datastart)->format('Ymd');
$dataend = DateTime::createFromFormat('m/d/Y', $dataend)->format('Ymd');

if ($datastart && $dataend) {
    $select_db->ExeRead(
        "t.date, t.email, u.user_cod, u.user_uf, u.origem, SUM(t.timeSpent) AS total_time_spent, COUNT(t.url) AS page_views",
        'pd_track t LEFT JOIN pd_users u ON t.email = u.user_email',
        "WHERE (t.type = 0 AND t.up = 1) AND t.email = u.user_email AND t.datatime >= '{$datastart}' AND t.datatime <= '{$dataend}' GROUP BY t.email",
        ""
    );

    $result_dia_table = $select_db->getResult();

 $data_replace = explode(' - ', $_GET['ajaxtable']);
 $a[] = '{datastart}';   $b[]  = $data_replace[0];
 $a[] = '{dataend}';   $b[]  = $data_replace[1];

} else {
    
 $select_db->ExeRead(
    "t.date, t.email, u.user_cod, u.origem, u.user_uf, SUM(t.timeSpent) AS total_time_spent, COUNT(t.url) AS page_views",
    'pd_track t LEFT JOIN pd_users u ON t.email = u.user_email',
    "WHERE (t.type = 0 AND t.up = 1)  AND t.email = u.user_email GROUP BY t.email, DATE(t.date) LIMIT 0, 3000",
    ""
);

$result_dia_table = $select_db->getResult();

}


}else{


// Data inicial (30 dias atrás)
$dataInicial = date('m/d/Y', strtotime('-30 days'));
// Data atual
$dataAtual = date('m/d/Y');

// Converter para o formato Ymd
$datastart = DateTime::createFromFormat('m/d/Y', $dataInicial)->format('Ymd');
$dataend = DateTime::createFromFormat('m/d/Y', $dataAtual)->format('Ymd');

 $a[] = '{datastart}';   $b[]  = $dataInicial;
 $a[] = '{dataend}';     $b[]  = $dataAtual;
 
$select_db->ExeRead(
    "t.date, 
    t.email, 
    t.origem, 
    u.origem, 
    u.user_cod, 
    u.user_uf, 
    SUM(t.timeSpent) AS total_time_spent, 
    COUNT(t.url) AS page_views",
    "pd_track t 
    LEFT JOIN pd_users u ON t.email = u.user_email",
    "WHERE (t.type = 0 AND t.up = 1) 
    AND t.datatime >= '{$datastart}' 
    AND t.datatime <= '{$dataend}' 
    ORDER BY t.id DESC 
    LIMIT 0, 3000",
    ""
);

}

$list_table = '';
$total_pages = 0;
$total_spe = 0;
$total_time_spent = 0;

if($select_db->getResult()){
    
$result_dia_table = $select_db->getResult();    
    
for($i = 0; $i < count($result_dia_table); $i++){
    
    $formatted_date   = date('d/m/Y', strtotime($result_dia_table[$i]['date']));
    $total_time_spent = $result_dia_table[$i]['total_time_spent'];
    $page_views       = $result_dia_table[$i]['page_views'];  // Contagem de páginas visualizadas

    $total_spe += $total_time_spent;

    // Converter tempo total em minutos e segundos
    $minutes = floor($total_time_spent / 60);
    $seconds = $total_time_spent % 60;
    $formatted_time_spent = sprintf('%02d:%02d', $minutes, $seconds);

    $filterdata = explode(' ', $result_dia_table[$i]['date']);
    $total_pages += $page_views;

    $list_table .= '
    <tr>
	<td>' . htmlspecialchars($result_dia_table[$i]['origem']) . '</td>
    <td>' . htmlspecialchars($result_dia_table[$i]['email']) . '</td>
    <td>' . htmlspecialchars($result_dia_table[$i]['user_cod']) . '</td>
    <td>' . htmlspecialchars($result_dia_table[$i]['user_uf']) . '</td>
    <td>' . $page_views . '</td>
    <td>' . $formatted_time_spent . '</td>
    <td>' . $formatted_date . '</td>
    <td><a href="javascript:void(0)" onclick="abrir_modal(\'' . addslashes($result_dia_table[$i]['email']) . '\', \'' . addslashes($filterdata[0]) . '\')" data-toggle="modal" data-target=".bd-track-list-lg"><i class="pe-7s-plus" style="font-size: 18px;"></i></a></td>
    </tr> ';

}

    // Converter tempo total em minutos e segundos
    $minutes = floor($total_spe / 60);
    $seconds = $total_time_spent % 60;
    $formatted_time_spent = sprintf('%02d:%02d', $minutes, $seconds);

$list_table .= "

<script>
function abrir_modal(email,filter){
   
   jQuery('#header-email').html(email)
   
   query = 'trackpages=' + email + '&trackdate=' + filter;
   
        $.ajax({
            type: 'GET',
            url: '".dominio."admin-dashboard', // Ajuste BASE_URL conforme necessário
            data: query,
            success: function(data) {
                $('#track_list_content').html(data);
            }
        });
    
}

window.setTimeout(function(){

jQuery('#total_paginas').html('".$total_pages."')
jQuery('#total_tempo').html('".$formatted_time_spent."')

}, 1000);

</script> 

";

}


if(isset($_GET['ajaxtableevento'])){
    
    $a[] = '{active_form_page}'; $b[] = '';
    $a[] = '{active_form_eventos}'; $b[] = 'active';
    
$ajaxtable = $_GET['ajaxtableevento'];

// Dividir a string para separar as datas de início e fim
list($datastart, $dataend) = explode(' - ', $ajaxtable);

// Criar objetos DateTime e formatá-los como 'yyyymmdd'
$datastart = DateTime::createFromFormat('m/d/Y', $datastart)->format('Ymd');
$dataend = DateTime::createFromFormat('m/d/Y', $dataend)->format('Ymd');   
    
  $select_db->ExeRead(
    "t.date, t.email, t.type, t.origem, t.checkinC, t.checkin, t.eventname, u.user_celular, u.user_optin, u.user_especialidade, u.origem, u.user_cod, u.user_uf, 
    t.timeSpent, 
    t.url",
    "pd_track t 
    LEFT JOIN pd_users u ON t.email = u.user_email",
    "WHERE t.type = 1 AND t.datatime >= '{$datastart}' AND t.datatime <= '{$dataend}' 
    AND t.checkin = 1 
    ORDER BY t.id DESC 
    LIMIT 0, 3000",
    ""
);  
    
}else{

    $a[] = '{active_form_page}'; $b[] = 'active';
    $a[] = '{active_form_eventos}'; $b[] = '';

$select_db->ExeRead(
    "t.date, t.email, t.type, t.origem, t.checkinC, t.checkin, t.eventname, u.user_celular, u.user_optin, u.user_especialidade, u.origem, u.user_cod, u.user_uf, 
    t.timeSpent, 
    t.url",
    "pd_track t 
    LEFT JOIN pd_users u ON t.email = u.user_email",
    "WHERE t.type = 1 AND t.datatime >= '{$datastart}' AND t.datatime <= '{$dataend}' 
    AND t.checkin = 1 
    ORDER BY t.id DESC 
    LIMIT 0, 3000",
    ""
);

}

$list_table2 = '';
$total_eventos_confirmado     = 0;
$total_eventos_nao_confirmado = 0;

if($select_db->getResult()){
    
$result_dia_table2 = $select_db->getResult();

for($e = 0; $e < count($result_dia_table2); $e++){
   
   if($result_dia_table2[$e]['checkin']==0){
    $total_eventos_nao_confirmado++; 
   }else{
    $total_eventos_confirmado++;
   }
   
    $sta = array(1, 0);
    $stb = array('<i class="lnr-thumbs-up"> </i>', '<i class="lnr-thumbs-down"> </i>');
    
    $formatted_date = date('d/m/Y', strtotime($result_dia_table2[$e]['date']));

    $list_table2 .= '
    <tr>
	<td>' . htmlspecialchars($result_dia_table2[$e]['origem']) . '</td>
	<td>' . htmlspecialchars($result_dia_table2[$e]['eventname']) . '</td>
    <td>' . htmlspecialchars($result_dia_table2[$e]['email']) . '</td>
    <td>' . htmlspecialchars($result_dia_table2[$e]['user_cod']) . '</td>
    <td>' . htmlspecialchars($result_dia_table2[$e]['user_uf']) . '</td>
    <td>' . htmlspecialchars($result_dia_table2[$e]['user_celular']) . '</td>
    <td>' . htmlspecialchars($result_dia_table2[$e]['user_optin']) . '</td>
    <td>' . htmlspecialchars($result_dia_table2[$e]['user_especialidade']) . '</td>
    <td>' . $formatted_date . '</td>
    <td>' . str_replace($sta, $stb, $result_dia_table2[$e]['checkinC']) . ' - ' . $result_dia_table2[$e]['checkinC'] . '</td>
    <td>' . str_replace($sta, $stb, $result_dia_table2[$e]['checkin']) . ' - ' . $result_dia_table2[$e]['checkin'] . '</td>
    </tr> ';

}

}

    $a[] = '{dia_logados}';   $b[]  = $result_dia[0]['unique_emails'];
    $a[] = '{dia_paginas}';   $b[]  = $result_dia[0]['total_pages'];	
    $a[] = '{mes_logados}';   $b[]  = $result_mes[0]['unique_emails'];		
    $a[] = '{mes_pagina}';   $b[]  = $result_mes[0]['total_pages'];
    $a[] = '{track_list}';   $b[]  = $list_table;
    $a[] = '{get_url}';      $b[] = getFullUrl();
    $a[] = '{dia_checkin_true}';    $b[]   = $total_eventos_confirmado;
    $a[] = '{dia_checkin_false}';   $b[]  = $total_eventos_nao_confirmado;
    $a[] = '{track_list_event}'; $b[]  = $list_table2;
  

?>