<?php
define('BOT_TOKEN', '5020655002:AAEVXzhz2QnZFKrmoNlOWCatqX2hEiZq2ec'); // place bot token of your bot here
// include_once("header.php");
include_once("../include/db_login.php");
include_once("../include/db_functions_cls.php");
function checkTelegramAuthorization($auth_data) {
  $check_hash = $auth_data['hash'];
  unset($auth_data['hash']);
  $data_check_arr = [];
  foreach ($auth_data as $key => $value) {
    $data_check_arr[] = $key . '=' . $value;
  }
  sort($data_check_arr);
  $data_check_string = implode("\n", $data_check_arr);
  $secret_key = hash('sha256', BOT_TOKEN, true);
  $hash = hash_hmac('sha256', $data_check_string, $secret_key);
  if (strcmp($hash, $check_hash) !== 0) {
    throw new Exception('Data is NOT from Telegram');
  }
  if ((time() - $auth_data['auth_date']) > 86400) {
    throw new Exception('Data is outdated');
  }
  return $auth_data;
}

function saveTelegramUserData($auth_data) {
  $auth_data_json = json_encode($auth_data);
  setcookie('tg_user', $auth_data_json);
}

try {
  session_cache_limiter ('private, must-revalidate'); //tb edit
  if(session_status() === PHP_SESSION_NONE) session_start();
  $auth_data = checkTelegramAuthorization($_GET);
  saveTelegramUserData($auth_data);
  $db_functions = New db_functions;
  $tg_user = json_decode($_COOKIE["tg_user"]);
  $resultDb = $db_functions->get_tguser($tg_user->id);
  	if ($resultDb){
		$_SESSION['user_name_admin'] = $resultDb->user_name;
		$_SESSION['user_id_admin'] = $resultDb->user_id;
		$_SESSION['group_id_admin'] = $resultDb->user_group_id;
		$_SESSION['user_gedcom'] = $resultDb->user_gedcomnbr;
		
		$sql="INSERT INTO humo_user_log SET
			log_date='".date("Y-m-d H:i")."',
			log_username='".$resultDb->user_name."',
			log_ip_address='".$_SERVER['REMOTE_ADDR']."',
			log_user_admin='admin',
			log_status='success'";
		$dbh->query($sql);
  	}
 
} catch (Exception $e) {
  die ($e->getMessage());
}

if (isset($_SESSION['user_name_admin'])) {
    header('Location: ' . 'index.php');
}
else {
    setcookie('tg_user', '');
    header('Location: login.php');
}
?>