<?php 

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

	if( $_POST['route'] !== 'uss-helpdesk-delete-chat' ) return;

	new class {

		protected $user;

		public function __construct() {

			$this->user = Uss::$global['user'];

			$this->secure();

			$this->processDelete();


		}

		protected function secure() {

			$secure = Uss::nonce( $_SESSION['uss_session_id'], $_POST['nonce'] ?? null );

			if( !$secure ) {

				Uss::exit( "<i class='bi b9-shield-exclamation me-1'></i> Security Check Failed" , false);

			} else if( !$this->user ) {

				Uss::exit( "<i class='bi bi-person-fill-slash me-1'></i> Your account is not signed in <br/> Please reload and try again" , false);
				
			};

		}

		protected function processDelete() {
			
			events::addListener('admin.support-ticket-chat::delete', function() {
				
				$permitted = Roles::user( $this->user['id'] )::hasPermission('manage-ticket');
				
				if( !$permitted ) {
					Uss::exit( "You do not have permission to remove the message" , false);
				};
				
				$_POST['id'] = Uss::$global['mysqli']->real_escape_string( $_POST['id'] );
				
				$prefix = DB_TABLE_PREFIX;

				$SQL = "
					DELETE FROM {$prefix}_ticket_replies
					WHERE id = '{$_POST['id']}'
				";
				
				$status = Uss::$global['mysqli']->query( $SQL );
				
				Uss::exit( $status ? "Message deleted" : "Message not deleted" , $status);
				
			});

			events::exec( 'admin.support-ticket-chat::delete', Uss::$global['user'] );

		}

	};

}, 'ajax:helpdesk-delete-chat');
