<?php

/**
 * A function that checks the user logged in status in MAMS.
 *
 * @param array $params An array of parameters.
 * @param object $smarty An instance of the Smarty template engine.
 * @return string The function comment.
 */
function smarty_function_mams_check_logged_in_status($params, $smarty)
{
  /**
   * showstopper
   */
  # if, for some odd reason, we don't have MAMS, don't do anything
  $mod = cms_utils::get_module('MAMS');
  
  if(!$mod) { return ''; }
  
  /**
   * parameters defaults
   */

  $use_toast              = 1;
  $use_custom_html        = 0;
  $use_custom_css         = 0;
  $toast_id               = 'session_status_toast';
  $toast_class            = 'session_status_toast';
  $notification_id        = 'session_status_expired_alert';
  $notification_class     = 'session_status_alert';
  $alert_message_id       = 'alert_message';
  $end_session_message    = 'Your session has expired. Please login to continue.';
  $custom_callback        = '';
  
  $toast_css_default = "
<style>
  .$toast_class {
    position: fixed;
    bottom: 20px;
    right: 20px;
    background-color: #333;
    color: #fff;
    padding: 10px 20px;
    border-radius: 5px;
    display: none;
  }
</style>
  ";
  
  $toast_html_default = "
<div id='$toast_id' class='$toast_class'></div>
";
  
  $notification_css_default = "
<style>
  .$notification_class {
    background-color: #f44336; /* Red color for error */
    border: 1px solid #c03627; /* Border style */
    border-radius: 5px; /* Rounded corners */
    padding: 10px; /* Padding inside the box */
    text-align: center; /* Center the text horizontally */
    box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.3); /* Box shadow for a subtle elevation effect */
    color: white;
    margin-top: 5px;
    z-index: 9999; /* Ensure it's on top of other content */
}

.close-button {
    color: #c03627;
    float: left; /* Align to the left */
    cursor: pointer; /* Change cursor to pointer on hover */
    margin-right: 5px; /* Add some spacing to the right of the button */
}

/* Style for hover state */
.close-button:hover {
    color: grey; /* Change text color on hover (optional) */
}
</style>
";
  
  $notification_html_default = "
<div id='$notification_id' class='$notification_class' style='display: none;'>
 <span id='dismiss-button' class='close-button' onclick='dismissAlert()'>×</span>
  <span id='alert_message'></span>
</div>
";
  
  /**
   * initialize a few variables
   */
  # get the session check interval
  $session_check_interval = (string)($params['session_check_interval'] ?? 1) * 1000;
  # get the toast display interval
  $toast_display_interval = (string)($params['$toast_display_interval'] ?? 10) * 1000;
  
  /**
   * grab the parameters
   */
  $use_toast           = $params['use_toast'] ?? $use_toast;
  $use_custom_html     = $params['use_custom_html'] ?? $use_custom_html;
  $use_custom_css      = $params['use_custom_css'] ?? $use_custom_css;
  $toast_id            = $params['toast_id'] ?? $toast_id;
  $toast_class         = $params['toast_class'] ?? $toast_class;
  $notification_id     = $params['notification_id'] ?? $notification_id;
  $notification_class  = $params['notification_class'] ?? $notification_class;
  $alert_message_id    = $params['alert_message_id'] ?? $alert_message_id;
  $toast_css           = $params['toast_css'] ?? $toast_css_default;
  $toast_html          = $params['toast_html'] ?? $toast_html_default;
  $notification_css    = $params['notification_css'] ?? $notification_css_default;
  $notification_html   = $params['notification_html'] ?? $notification_html_default;
  $countdown_css       = $params['countdown_css'] ?? $countdown_css_default;
  $countdown_html      = $params['countdown_html'] ?? $countdown_html_default;
  $end_session_message = $params['end_session_message'] ?? $end_session_message;
  $custom_callback     = $params['custom_callback'] ?? $custom_callback;
  
  # non parameters
  $config             = $mod->GetExtendedConfig();
  $ajax_url           = str_replace('cache', '', $config['public_cache_url']) . 'cmsmsext/session_status_' .
                        \getmypid() . '_' . session_id() . '.dat';
  
  $html               = $use_custom_css ? '' : $toast_css . $countdown_css . $notification_css;
  
  $script_html = "
<script>
var sessionDuration = $duration;
var remainingTime = 0;
var useToast = $use_toast;
var ajaxUrl = '$ajax_url';
var counterSpanId = '$counter_span_id';
var notificationId = '$notification_id';
var toastId = '$toast_id';
var session_check_interval = $session_check_interval;
var toast_display_interval = $toast_display_interval;
var end_session_message = '$end_session_message';
var customCallback = '$custom_callback';

function getSessionStartTime(callback)
{
  var xhr = new XMLHttpRequest();
  // Append the cache-buster to the URL
  var urlWithCacheBuster = ajaxUrl + (ajaxUrl.indexOf('?') === -1 ? '?' : '&') + 'cache=' + new Date().getTime();
  
  xhr.open('GET', urlWithCacheBuster, true);
  xhr.responseType = 'text';

  xhr.onload = function()
  {
    if (xhr.status === 200)
    {
      var sessionStartTime = parseInt(xhr.responseText, 10);
      callback(sessionStartTime);
    }
  };

  xhr.send();
}

function getLoggedInStatus()
{
  // Define the URL for the AJAX request
  var url = 'your_php_script.php';
  
  // Create a new XMLHttpRequest object
  var xhr = new XMLHttpRequest();
  
  // Prepare the parameters for the request
  var params = {
    fnc: 'your_function_name',
    cache: new Date().getTime();
    // Add additional parameters here if needed
  };
  
  // Encode the parameters as a query string
  var queryString = Object.keys(params).map(function(key) {
    return key + '=' + encodeURIComponent(params[key]);
  }).join('&');
  
  // Open a GET request to the URL with the parameters
  xhr.open('GET', url + '?' + queryString, true);
  
  // Set the callback function to handle the response
  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4) {
      if (xhr.status === 200) {
        // Parse the JSON response
        var response = JSON.parse(xhr.responseText);
  
        // Access the properties in the JSON response
        var msg = response.msg;
        var error = response.error;
        var content = response.content;
        var type = response.type;
        var params = response.params;
  
        // Do something with the data
        console.log('Message:', msg);
        console.log('Error Code:', error);
        console.log('Content:', content);
        console.log('Type:', type);
        console.log('Parameters:', params);
      } else {
        // Handle the error (e.g., show an error message)
        console.error('Error:', xhr.statusText);
      }
    }
  };
  
  // Send the AJAX request
  xhr.send();
}



function calculateRemainingTime(sessionStartTime, sessionDuration)
{
  var currentTime = Math.floor(Date.now() / 1000); // Convert to seconds
  var elapsedTime = currentTime - sessionStartTime;
  var remainingTime = sessionDuration - elapsedTime;
 
  return remainingTime > 0 ? remainingTime : 0;
}

function updateTimerDisplay(timeLeft)
{
  var timerElement = document.getElementById(counterSpanId);
  timerElement.textContent = timeLeft;
}

function displaySessionExpiredAlert(message)
{
  var sessionExpiredAlert = document.getElementById(notificationId);
  var sessionExpiredAlertMessage = document.getElementById('$alert_message_id');
  sessionExpiredAlertMessage.textContent = message;
  sessionExpiredAlert.style.display = 'block';
}

function dismissAlert()
{
  var alertElement = document.getElementById('$notification_id');
  alertElement.style.display = 'none';
}

function displaySessionExpiredToast(message)
{
    var toast = document.getElementById(toastId);
    toast.textContent = message;
    toast.style.display = 'block';
  
    setTimeout(function()
    {
        toast.style.display = 'none';
    }, toast_display_interval); // Display for $toast_display_interval seconds, adjust as needed
}

function startCountdown(remainingTime)
{
    var intervalId = setInterval(function()
    {
        if (remainingTime > 0)
        {
            updateTimerDisplay(remainingTime);
            remainingTime--;
        }
        else
        {
            clearInterval(intervalId);
            updateTimerDisplay(0);
            var message = end_session_message;
  
            if (useToast)
            {
              displaySessionExpiredToast(message);
            }
            else
            {
              displaySessionExpiredAlert(message);
            }
            
            if (typeof window[customCallback] === 'function')
            {
              // Call the custom callback function by its name
              window[customCallback]();
            }

        }
    }, session_check_interval); // Update every $session_check_interval milliseconds
}

// Get session start time and start the countdown
getSessionStartTime(function(sessionStartTime)
{
  remainingTime = calculateRemainingTime(sessionStartTime, sessionDuration);
  updateTimerDisplay(remainingTime);
  startCountdown(remainingTime);
});

</script>
";
  
  $html .=  $use_custom_html ? $script_html : $countdown_html . $toast_html . $notification_html .  $script_html;

  return $html;
}
?>