<?php 

require __DIR__ . '/index.php';

/*

*/

if( $_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['nonce']) || !uss::$global['user'] ) exit;

if( $_POST['nonce'] !== uss::nonce( $_SESSION['uss_session_id'] ) ) exit;


$prefix = DB_TABLE_PREFIX;


/*

*/

$portal = $_GET['portal'] ?? null;

$isTicketManager = roles::user( uss::$global['user']['id'] )::hasPermission( 'manage-ticket' );

if( $isTicketManager && $portal === 'admin' ) {
	
	$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)" ;
	
};


/*

*/

$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 );

/*

*/

if( !$result->num_rows ) uss::stop( false );

else {
	uss::stop( true, sprintf( $message, $result->num_rows ) );
};