<?php 

defined( 'UADMIN_DIR' ) OR DIE;


if( $_SERVER['REQUEST_METHOD'] == 'POST' && Uss::$global['user'] ) {
	
	if( !Uss::nonce('helpdesk', $_POST['nonce']) ) {
		
		Uss::console( '@alert', "<i class='bi bi-shield-exclamation'></i> Security check failed!" );
		
	} else {
		
		events::addListener('dashboard.support-ticket-new::POST', function() {
			
			$_POST = array_map('trim', $_POST);
			
			if( empty($_POST['subject']) || empty($_POST['description']) ) {
				
				$status = false;
				Uss::console('@alert', "Please fill up all required fields");
				
			} else {
					
				//! Remove javascript tags if exists;
				
				$regexp = "/\<(\/?)script(?:[^>]*?)\>/";
				$_POST['description'] = preg_replace( $regexp, '<!-- $1[script] -->', $_POST['description'] );
				
				$data = array(
					'uniqid' => core::keygen(10),
					'userid' => Uss::$global['user']['id'],
					'subject' => $_POST['subject'],
					'description' => $_POST['description']
				);
				
				
				//! Create Database Query;
				
				$prefix = DB_TABLE_PREFIX;
				
				$data = array_map( array(Uss::$global['mysqli'], 'real_escape_string'), $data );
				
				$SQL = sQuery::insert( "{$prefix}_tickets", $data );
				
				
				//! Add the ticket to database;
				
				$status = Uss::$global['mysqli']->query( $SQL );
				
				if( $status ) {
					
					$notification = "**New Support Ticket:** {$data['subject']}";
					
					$ticket_managers = roles::get_permitted_users( 'manage-ticket' );
					
					foreach( $ticket_managers as $manager_id ) {
						udash::notify(array(
							"userid" => $manager_id,
							"message" => $notification,
							"model" => "ticket",
							"origin" => Uss::$global['user']['id'],
							"redirect" => core::url( ROOT_DIR . '/' . UADMIN_ROUTE . "/ticket/{$data['uniqid']}" )
						));
					};
					
				};
				
				$message = array(
					'success' => "<i class='bi bi-check-circle'></i> Your ticket was successfully created",
					'danger' => "<i class='bi bi-exclamation-circle'></i> The ticket could not be created"
				);
				
				
				// Display the response message;
				
				events::addListener('dashboard.support-ticket-form::input', function() use($message, $status) {
					$key = $status ? 'success' : 'danger';
					$MSG = $message[ $key ];
					echo "
						<div class='alert alert-{$key} text-center'>
							{$MSG}
						</div>
					";
				}, EVENT_ID);
				
			};
			
			
			// Prevent Browser from resubmitting the form on reload;
			
			Uss::console('@RE-POST', false);
			
			
			// AutoFill the input fields;
			
			if( !$status  ) {
				udash::config('_POST.subject', $_POST['subject']);
				udash::config('_POST.description', $_POST['description']);
			};
			
		});
		
		events::exec( 'dashboard.support-ticket-new::POST' );
		
	};

};

