<?php 

define('UHELPDESK_DIR', __DIR__ );

# Establish Support Ticket

new class {

	protected $authority = [
		'super-admin',
		'administrator'
	];

	public function __construct() {

		Events::addListener('uadmin:ready', function() {
			# Configure Ticket
			$this->configure();
		}, 'Helpdesk');

		Events::addListener('uadmin:ready', function() {
			# Load Ticket Pages
			if( $this->enabled() ) {
				$this->loadHelpdesk();
			} else {
				$this->loadErrorPages();
			};
		}, 'helpdesk');

	}

	public function enabled( ?bool $value = null ) {
		$enabled = Uss::$global['options']->get( 'helpdesk:enabled' );
		if( is_null($enabled) || !is_null($value) ) {
			$value = !empty($value) ? 1 : 0;
			$enabled = Uss::$global['options']->set( 'helpdesk:enabled', $value );
		};
		return $enabled;
	}

	public function configure() {
		# Authorized;
		foreach( $this->authority as $role ) {
			Roles::setPermission( $role, "manage-ticket" );
		};
		# Admin Ticket Setup;
		require UHELPDESK_DIR . '/setup.php';
	}

	public function loadHelpdesk() {
		
		require UHELPDESK_DIR . "/db.php";
		
		if( !Udash::is_ajax_mode() ) {
			
			require UHELPDESK_DIR . '/utils/scan.php';
			
			Udash::load( UADMIN_ROUTE,  UHELPDESK_DIR . '/backend/index.php' );
				
			Udash::load( UDASH_ROUTE, UHELPDESK_DIR . '/frontend/index.php' );

		} else {
			
			require_once UHELPDESK_DIR . "/ajax/index.php";

		};

	}
	

	public function loadErrorPages() {
	
		$clientRegexp = UDASH_ROUTE . "/support/?(chat/)?(?:\w+)?";
		$adminRegexp = UADMIN_ROUTE . "/ticket/?(?:\w+)?";
		
		Uss::route( "(?:(?:{$clientRegexp})|(?:{$adminRegexp}))", function() {
			
			udash::config('sidebar', false);
			
			udash::view(function() {
				
				$href = core::url( ROOT_DIR . '/' . Uss::query(0) );

				require_once UHELPDESK_DIR . "/utils/not-available.php";
				
			});
			
		});
		
	}

};


