<?php

	class qa_html_theme_layer extends qa_html_theme_base {
		
		var $plugin_url_onsitenotifications;


		
		function head_script(){
			qa_html_theme_base::head_script();
			if(qa_opt('kingm_onsitenotifications_enabled')) {
				$this->output('<script type="text/javascript">
						var eventnotifyAjaxURL = "'.qa_path_html('eventnotify').'";
					</script>');  
				$this->output('<script type="text/javascript" src="'. QA_HTML_THEME_LAYER_URLTOROOT .'script.js"></script>');
			}
		}
		
		function userpanel() {
			
			qa_html_theme_base::userpanel();
			/* The following code originates from q2a plugin "History" by NoahY and has been modified by kingm.com
			 * It is licensed under GPLv3 http://www.gnu.org/licenses/gpl.html
			 * Link to plugin: https://github.com/NoahY/q2a-history
			 */
			$userid = qa_get_logged_in_userid();
			if(qa_opt('kingm_onsitenotifications_enabled') && $userid) {

				$last_visit = qa_db_read_one_value(
					qa_db_query_sub(
						'SELECT UNIX_TIMESTAMP(meta_value) FROM ^usermeta WHERE user_id=# AND meta_key=$',
						$userid, 'visited_profile'
					),
					true
				);

				// first time visitor, we set the last visit manually in the past
				if(is_null($last_visit)) {
					$last_visit = '1981-03-31 06:25:00';
				}
				
				// select and count all in_eventcount that are newer as last visit
				$eventcount = qa_db_read_one_value(
					qa_db_query_sub(
						'SELECT COUNT(event) FROM ^eventlog 
								WHERE FROM_UNIXTIME(#) <= datetime 
								AND DATE_SUB(CURDATE(),INTERVAL # DAY) <= datetime 
								AND (
								(userid=# AND event LIKE "in_%")
								OR ((event LIKE "u_message" OR event LIKE "u_wall_post") AND params LIKE "userid=#\t%")
								)
								',
								$last_visit,
								qa_opt('kingm_onsitenotifications_maxage'), 
								$userid, 
								$userid
					)
				);
				
				$tooltip = qa_lang('kingm_onsitenotifications_lang/show_notifications');
				if($eventcount) {
					$tooltip = $eventcount.' '.qa_lang('kingm_onsitenotifications_lang/x_notifications');
					// only one event
					if($eventcount==1) {
						$tooltip = qa_lang('kingm_onsitenotifications_lang/one_notification');
					}

					$this->output('<li> <a class="king-history-new-event-link" title="'.$tooltip.'"><span class="notifybub ntfy-event-nill"><span class="notifybub ntfy-event-new">'.$eventcount.'</span><i class="far fa-bell fa-lg"></i></span></a></li>');
				}
				else {
					// add notify bubble to user navigation
					$this->output('<li> <a class="king-history-new-event-link" title="'.$tooltip.'"><span class="notifybub ntfy-event-nill"><i class="far fa-bell fa-lg"></i></span></a></li>');
				}
				
			}
			
			
		}

	} // end qa_html_theme_layer		
	

/*
	Omit PHP closing tag to help avoid accidental output
*/