<?php

/**
 * A function that checks the session status.
 *
 * @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_check_session_status($params, $smarty)
{
  /**
   * showstopper
   */
  # if, for some odd reason, we don't have CMSMSExt, don't do anything
  $mod = cms_utils::get_module('CMSMSExt');
  
  if(!$mod) { return ''; }
  
  /**
   * parameters defaults
   */
  $countdown_string       = 'Time left';
  $countdown_units_string = 'seconds';
  $use_toast              = 1;
  $use_custom_html        = 0;
  $use_custom_css         = 0;
  $counter_id             = 'session_status_countdown';
  $counter_class          = 'session_status_countdown';
  $counter_span_id        = 'session_status_countdown_span';
  $counter_span_class     = 'session_status_countdown_span';
  $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 refresh the page 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;
    z-index: 9999;
  }
</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>
";
  
  $countdown_css_default = "
 <style>
  #$counter_id {
    background-color: #f0f0f0; /* Background color (gray shade) */
    border: 1px solid #ccc; /* 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 */
}

  #$counter_span_id {
    font-weight: bold;
    font-size: 18px;
    margin-left: 5px;
    width: 60px; /* Fixed width for 6 digits */
    display: inline-block; /* Ensures fixed width doesn't overflow */
    text-align: right; /* Right-align the text within the fixed width */
    }
</style>
";
  $countdown_html_default = "
  <div id='$counter_id' class='$counter_class'>$countdown_string: <span id='$counter_span_id' class='$counter_span_class'>0</span> $countdown_units_string</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;
  $duration               = ini_get('session.gc_maxlifetime');
  // $duration               = 30;
  
  /**
   * 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;
  $counter_id          = $params['counter_id'] ?? $counter_id;
  $counter_class       = $params['counter_class'] ?? $counter_class;
  $counter_span_id     = $params['counter_span_id'] ?? $counter_span_id;
  $counter_span_class  = $params['counter_span_class'] ?? $counter_span_class;
  $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
  $smanager             =  \CMSMSExt\session\Manager::getInstance();
  $ajax_url             = $smanager->getFileUrl();
  
  $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 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--;
    
          // Check session timestamp every 60 seconds
          if (remainingTime % 60 === 0)
          {
            getSessionStartTime(function (sessionStartTime)
            {
              remainingTime = calculateRemainingTime(sessionStartTime, sessionDuration);
            });
          }
        }
        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;
}
?>