<?php 

Events::addListener('udash:ajax', function() {

	if( $_POST['route'] != 'uss-helpdesk' ) return;
	
	new class {

		protected $user;
		protected $secured;
		protected $portal;
		protected $sudo;

		public function __construct() {

			$this->user = Uss::$global['user'];
			$this->secured = Uss::nonce( $_SESSION['uss_session_id'], ($_POST['nonce'] ?? null) );
			$this->portal = $_GET['portal'] ?? null;
			$this->sudo = Roles::user( $this->user['id'] )::hasPermission( 'manage-ticket' );

			if( $this->secured ) {
				$this->getUpdate();
			}

		}

		public function getUpdate() {

			$query = $this->getQuery( DB_TABLE_PREFIX );

			$result = $this->getResult( $query['terms'], DB_TABLE_PREFIX );
			
			if( !$result->num_rows ) {
				Uss::exit( '', false );
			} else {
				Uss::exit( sprintf( $query['message'], $result->num_rows ), true );
			};

		}

		protected function getQuery( string $prefix ) {

			if( $this->portal == UADMIN_ROUTE && $this->sudo ) {
				
				$TERMS = "
					{$prefix}_ticket_replies.viewpoint = 'client'
					AND {$prefix}_ticket_replies.seen = 0
				";
				
				$Message = "You have unread messages from %s support ticket(s)";
				
			} else {
				
				$userid = Uss::$global['user']['id'];
				
				$TERMS = "
					{$prefix}_tickets.userid = {$userid}
					AND {$prefix}_ticket_replies.viewpoint = 'admin'
					AND {$prefix}_ticket_replies.seen = 0
				";
				
				$Message = "New reply for %s support ticket(s)" ;
				
			};

			return [ 
				'terms' => $TERMS, 
				'message' => $Message
			];

		}

		protected function getResult( string $TERMS, string $prefix ) {

			$SQL = "
				SELECT
					COUNT({$prefix}_ticket_replies.seen) AS unseen
				FROM {$prefix}_ticket_replies
				INNER JOIN {$prefix}_tickets
					ON {$prefix}_ticket_replies.ticket_id = {$prefix}_tickets.id
				WHERE {$prefix}_tickets.status = 'open'
					AND {$TERMS}
				GROUP BY {$prefix}_tickets.id
			";

			$result = Uss::$global['mysqli']->query( $SQL );

			return $result;

		}

	};

}, 'ticket-scan');
