<?php 

defined( 'DASHBOARD_MOD_DIR' ) OR DIE;

//! 

if( $_SERVER['REQUEST_METHOD'] == 'POST' && !empty($ticket) ) {
	
	if( ($_POST['nonce'] ?? null) !== uss::nonce('chat') || !isset($_POST['type']) )
		
		uss::console( ':alert', "<i class='mdi mdi-shield-off'></i> Security Check Failed!" );
		
	else {
		
		events::addListener('util.support-ticket::POST', function() use($ticket) {
			
			$prefix = DB_TABLE_PREFIX;
			
			switch( $_POST['type'] ) {
				
				case 'reply':
					
					if( !empty($_POST['parent_id']) ) {
						
						$_POST['parent_id'] = uss::$global['mysqli']->real_escape_string( $_POST['parent_id'] );
						
						$parent = dashboard::fetch_assoc("{$prefix}_ticket_replies", $_POST['parent_id']);
						
						if( $parent['ticket_id'] !== $ticket['id'] ) $parent = null;
						
					} else $parent = null;
					
					$data = array(
						'message' => uss::htmlentities( trim($_POST['message']) ),
						'userid' => uss::$global['user']['id'],
						'ticket_id' => $ticket['id'],
						'viewpoint' => ( uss::query(0) !== ADMIN_FOCUS_URI ) ? 'client' : 'admin',
						'selfie' => core::keygen(10),
						'parent_id' => $parent ? $parent['id'] : null
					);
					
					if( !empty($data['message']) ) {
						
						$SQL = sQuery::insert( "{$prefix}_ticket_replies", $data, uss::$global['mysqli'] );
						
						$status = uss::$global['mysqli']->query( $SQL );
						
						if( !$status ) uss::console(':toastr.error.reply', 'The message was not sent' );
					
					};
				
				break;
				
				case 'state':
					
					$status = uss::$global['mysqli']->real_escape_string( trim($_POST['status']) );
					
					$valid_status = array( 'open', 'closed', 'resolved', 'cancelled' );
					
					if( in_array($status, $valid_status) ) {
						
						$SQL = sQuery::update( "{$prefix}_tickets", array(
							'status' => $status
						), "id = '{$ticket['id']}'");
						
						$status = uss::$global['mysqli']->query( $SQL );
						
						if( !$status ) uss::console( ':alert', "<i class='mdi mdi-alert me-1'></i> The request could not be completed!" );
						
					} else uss::console( ':alert', "<i class='mdi mdi-ticket fs-18px me-1'></i> The ticket status could not be altered" );
				
				break;
				
			};
		
		});
		
		//! 
		
		events::exec( 'util.support-ticket::POST' );
		
	};
	
	//! 
	
	dashboard::call('form:prevent-resubmit');
	
	
	/*
		Refresh the ticket;
		After _POST request has made some changes
	*/
	
	if( isset($TICKET_SQL) ) {
		$ticket = uss::$global['mysqli']->query( $TICKET_SQL )->fetch_assoc();
	};
	
};
