<?php 

defined( 'UADMIN_DIR' ) OR DIE;

$chat = new class($ticket, $TICKET_SQL ?? null) {

	protected $ticket;
	protected $SQL;
	protected $prefix = DB_TABLE_PREFIX;
	protected $post;

	public function __construct($ticket, string $SQL = null) {
		
		$this->SQL = $SQL;
		$this->ticket = $ticket;
		$this->post = array_map('trim', $_POST);

		if( !$this->method('post') || empty($ticket) || !$this->secured() ) {
			return;
		};

		$this->processChat();

	}

	public function processChat() {

		events::addListener('util.support-ticket::POST', function() {
			
			$prefix = DB_TABLE_PREFIX;
			
			switch( $_POST['type'] ) {
				
				case 'reply':
					$this->doReply();
				break;
				
				case 'state':
					$this->doState();
				break;
				
			};
		
		});
		
		# Execute Other Chat Script;

		events::exec( 'util.support-ticket::POST' );

	}

	public function refresh() {
		
		if( !is_null($this->SQL) ) {
			# Refresh Ticket Data
			$this->ticket = Uss::$global['mysqli']->query( $this->SQL )->fetch_assoc();
		};

		return $this->ticket;

	}

	protected function doReply() {

		if( !empty($this->post['parent_id']) ) {
						
			$this->post['parent_id'] = Uss::$global['mysqli']->real_escape_string( $this->post['parent_id'] );
			
			$parent = udash::fetch_assoc("{$this->prefix}_ticket_replies", $this->post['parent_id']);

			if( $parent['ticket_id'] !== $this->ticket['id'] ) $parent = null;
			
		} else $parent = null;
		
		$data = array(
			'message' => htmlspecialchars( trim($this->post['message']), ENT_QUOTES | ENT_HTML5, 'UTF-8' ),
			'userid' => Uss::$global['user']['id'],
			'ticket_id' => $this->ticket['id'],
			'viewpoint' => ( Uss::query(0) !== UADMIN_ROUTE ) ? 'client' : 'admin',
			'selfie' => core::keygen(10),
			'parent_id' => $parent ? $parent['id'] : null
		);
		
		if( !empty($data['message']) ) {
			
			$SQL = sQuery::insert( "{$this->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' );
		
		};
	}

	protected function doState() {

		$status = Uss::$global['mysqli']->real_escape_string( trim($this->post['status']) );
		
		$valid_status = array( 'open', 'closed', 'resolved', 'cancelled' );
		
		if( in_array($status, $valid_status) ) {
			
			$SQL = sQuery::update( "{$this->prefix}_tickets", array(
				'status' => $status
			), "id = '{$this->ticket['id']}'");
			
			$status = Uss::$global['mysqli']->query( $SQL );
			
			if( !$status ) Uss::console( '@alert', "<i class='bi bi-exclamation me-1'></i> The request could not be completed!" );
			
		} else Uss::console( '@alert', "<i class='bi bi-ticket fs-18px me-1'></i> The ticket status could not be altered" );

	}

	protected function secured() {

		$secured = Uss::nonce('chat', ($this->post['nonce'] ?? null)) && isset($this->post['type']);
			
		if( !$secured ) {
			Uss::console( '@alert', "<i class='bi bi-shield-exclamation'></i> Security Check Failed!" );
		};
		
		return $secured;

	}

	protected function method( string $method ) {

		# Get Request Method;

		return ( $_SERVER['REQUEST_METHOD'] == strtoupper($method) );

	}

};