<?php 

defined( 'ADMIN_MOD_DIR' ) OR DIE;


if( $_SERVER['REQUEST_METHOD'] == 'POST' && uss::$global['user'] ) {
	
	if( $_POST['nonce'] !== uss::nonce('helpdesk') ) {
		
		uss::console( ':alert', "<i class='mdi mdi-shield-off'></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 ) {
						dashboard::notify(array(
							"userid" => $manager_id,
							"message" => $notification,
							"model" => "ticket",
							"origin" => uss::$global['user']['id'],
							"redirect" => core::url( ROOT_DIR . '/' . ADMIN_FOCUS_URI . "/ticket/{$data['uniqid']}" )
						));
					};
					
				};
				
				$message = array(
					'success' => "<i class='mdi mdi-check-circle-outline'></i> Your ticket was successfully created",
					'danger' => "<i class='mdi mdi-alert-circle-outline'></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_FLOAT);
				
			};
			
			
			// Prevent Browser from resubmitting the form on reload;
			
			dashboard::call('form:prevent-resubmit');
			
			
			// AutoFill the input fields;
			
			if( !$status  ) {
				dashboard::config('_POST.subject', $_POST['subject']);
				dashboard::config('_POST.description', $_POST['description']);
			};
			
		});
		
		events::exec( 'dashboard.support-ticket-new::POST' );
		
	};

};

