<?php
class BotPressAddon extends APPAddOns{
	public function OnInit() {
		parent::OnInit();
		$this->RegisterAdminAction("settings",[$this,'settings']);


		$group=$this->AddAdminMenuGroup("BotPress",'fa fa-star');
		$group->AddSubMenu("Settings","fa fa-star","settings");
		
		
		add_action( 'action-bp-create-ticket', [ $this, "create_ticket" ], 10, 0 );
		$this->AddModule("chat",APP_Output::MODULE_PAGE_FOOTER);

	}
	function get_request_content_type() {
		if ( ! empty( $_SERVER['HTTP_CONTENT_TYPE'] ) ) {
			return  $_SERVER['HTTP_CONTENT_TYPE'];
		}
		if ( ! empty( $_SERVER['CONTENT_TYPE'] ) ) {
			return $_SERVER['CONTENT_TYPE'] ;
		}
	}

	function get_product_categories($slug=''){
		$pro_cat = unserialize(Mapp_setting_api::GetSettingsValue( "botpress", "pro_cat", '' ));
		$product_categoies=[
				"def"=>	$this->get_product_cat("def","Default",!empty($pro_cat['def'])?$pro_cat['def']:''),
				"vtp"=>	$this->get_product_cat("vtp","Vitepos",!empty($pro_cat['vtp'])?$pro_cat['vtp']:''),
				"el"=>	$this->get_product_cat("el","Elite Licenser",!empty($pro_cat['el'])?$pro_cat['el']:''),
				"bss"=>	$this->get_product_cat("bss","Best Support System",!empty($pro_cat['bss'])?$pro_cat['bss']:''),
				"mcd"=>	$this->get_product_cat("mcd","Mini Card Drawer",!empty($pro_cat['mcd'])?$pro_cat['mcd']:''),
		];
		if(!empty($slug)){
			if(!empty($product_categoies[$slug])){
				return $product_categoies[$slug];
			}else{
				return null;
			}
		}
		return $product_categoies;
	}
	function get_product_cat($name='',$title='',$cat_id=''){ 
		$obj=new stdClass();
		$obj->name=$name;
		$obj->title=$title;
		$obj->cat_id=$cat_id;
		return $obj;
	}
	public function create_ticket() {
		$req_type = $this->get_request_content_type();
		if ( ! empty( $req_type ) ) {
			$req_type = strtolower( $this->get_request_content_type() );
		}
		$api_reponse = new APPAPIResponse();
		if ( 'application/json' == $req_type ) {
			$_posted = file_get_contents( 'php://input' );
			if ( ! empty( $_posted ) ) {
				$_posted = json_decode( $_posted, true );
			}
		} else {
			$_posted = $_POST;
		}
		$pri_key = Mapp_setting_api::GetSettingsValue( "botpress", "pri_key", "" );
        
		$is_ok_validation=true;
		$required_flds=[];
		foreach ( [ 'pri_key','email','product_slug','title','ticket_body' ] as $k ) {
			if ( empty( $_posted[$k] ) ) {
				$is_ok_validation=false;
				$required_flds[]=$k;
			}
		}
		if(!$is_ok_validation){
			$tails= (implode(", ",$required_flds)).(count($required_flds)>1?" are":" is")." required";
			$api_reponse->displayErrorResponse( false, "unauthorized request. ".$tails,   422 );
		}

		if ( empty( $_posted['pri_key'] ) || $pri_key !== $_posted['pri_key'] ) {
			$api_reponse->displayErrorResponse( false, "unauthorized request",  401 );
		}




		try {
			$ticket_object = $this->open_ticket( $_posted );
		} catch ( Exception $e ) {
			$api_reponse->displayErrorResponse( false, $e->getMessage() );
		}
		$response_data           = new stdClass();
		$response_data->track_id = $ticket_object->ticket_track_id;
		$response_data->url      = "";

		if ( $ticket_object->user_type == "G" ) {
			$response_data->is_registerd      = false;
			$response_data->url = site_url( "ticket/guest-ticket/{$ticket_object->ticket_track_id}" );
		} else {
			$response_data->is_registerd      = true;
			$response_data->url = site_url( "ticket/user-ticket/{$ticket_object->ticket_track_id}" );
		}
		$api_reponse->displayWithResponse( true, "Successfully Ticket Created", $response_data, 202 );
	}

	/**
	 * The open ticket is generated by appsbd
	 *
	 * @param mixed $oTicket It is oTicket param.
	 * @param APPAPIResponse $api_reponse It is api_reponse param.
	 *
	 * @return Mticket
	 * @throws Exception
	 */
	public function open_ticket($oTicket) {
		$isEveryThingOk = true;
		$isHtmlEditor=Mapp_setting::GetSettingsValue("ticket_htmleditor","Y")=="Y";
		$ticketBody     =$oTicket['ticket_body'];
		$isNewlyOpenGuestUser=false;
		if ( ! $isHtmlEditor ) {
			$ticketBody = strip_tags( $ticketBody );
		} else {
			$ticketBody = strip_tags( $ticketBody,
				'<h1><h2><h3><h4><strong><b><span><ul><u><font><li><table><tr><img><div><td><th><tbody><thead><tfoot><hr><p><a>' );
			if ( isset( $_POST['ticket_body'] ) ) {
				$_POST['ticket_body'] = $ticketBody;
			}
		}
		

		
		if ( $isEveryThingOk ) {
			$newobj       = new Mticket();
			$newobj->cat_id('0');
			$product_slug=$this->get_product_categories($oTicket['product_slug']);
			if(empty($product_slug)) {
				throw new Exception( "Successfully Ticket Created");
			}else{
				if(!empty($product_slug->cat_id)){
					$newobj->cat_id($product_slug->cat_id);
				}else{
					$def_cat=$this->get_product_categories('def');
					if(!empty($def_cat->cat_id)){
						$newobj->cat_id($def_cat->cat_id);
					}
				}
			}
			$emailAddress = $oTicket['email'];
			$newobj->is_open_using_email("Y");

			$newobj->is_public("N");
			$newobj->status("N");
			$newobj->priroty("M");
			$old_site_user=Msite_user::FindBy("email", $oTicket['email']);
			if(!$old_site_user){
				
				if(true || Mapp_setting::GetSettingsValue("is_guest_ticket","N")=="Y") {
					$password = strtoupper( get8BitHashCode( rand( 1000, 9999 ) ) ) . rand( 10, 99 );
					$siteU    = new Msite_user();
					$siteU->email( $oTicket['email'] );
					$siteU->first_name( $oTicket['name']['first'] );
					$siteU->last_name($oTicket['name']['first']);
					$siteU->user_type( "G" );
					$siteU->pass( $password );
					if ( $siteU->Save() ) {
						$newobj->ticket_user( $siteU->id );
						$newobj->user_type( $siteU->user_type );
						$isNewlyOpenGuestUser = true;
					} else {
						Mdebug_log::AddGeneralLog( "Ticket creation form bot has been failed",
							Mdebug_log::STATUS_FAILED, Mdebug_log::ENTRY_TYPE_ERROR );
						throw new Exception( "Ticket creation form bot has been failed" );
					}
				}else{
					Mdebug_log::AddGeneralLog( "Ticket creation form bot has been failed-guest ticket has been disabled",
						Mdebug_log::STATUS_FAILED, Mdebug_log::ENTRY_TYPE_ERROR );
					throw new Exception( "Guest ticket has been disabled,Ticket creation form bot has been failed" );
				}
			}else{
				$newobj->ticket_user($old_site_user->id);
				$newobj->user_type($old_site_user->user_type);
			}
			$newobj->title($oTicket['title']);
			$newobj->ticket_body($ticketBody."<br/> From Webchat Bot");
			if ( $newobj->IsValidForm(true,false)) {
				if($newobj->Save()){
					return $newobj;
				}else{
					throw new Exception( GetMsgForAPI() );
				}
			}else{
				throw new Exception( GetMsgForAPI() );
			}

		}
		throw new Exception( "Ticket creation failed with unknown error" );
	}
	public function OnActivate() {
		
	}
	public function OnDeactivate() {
		
	}

	public function getPluginSlug() {
		return 'bot-press';
	}

	public function settings(){
		$this->SetTitle("Bot Press Settings");
		$pri_key=Mapp_setting_api::GetSettingsValue("botpress","pri_key","");

		if(IsPostBack) {
			$p_pri_key = PostValue( "pri_key", "" );
			$products  = PostValue( "product", [] );
			$sProduct  = [];
			foreach ( $products as $product ) {
				$sProduct[ $product['name'] ] = $product['cat_id'];
			}
			$is_updated = false;
			if ( Mapp_setting_api::UpdateSettingsOrAdd( "botpress", "pri_key", $p_pri_key ) ) {
				$is_updated = true;
			}

			if ( Mapp_setting_api::UpdateSettingsOrAdd( "botpress", "pro_cat", serialize( $sProduct ) ) ) {
				$is_updated = true;
			}
			if ( $is_updated ) {
				AddInfo( "Successfully updated" );
			} else {
				AddError( "No change found to update" );
			}

		}
		$this->controller->AddViewData("pri_key",$pri_key);
		$this->controller->AddViewData("product_cats",$this->get_product_categories());
		$this->Display('settings');
	}

	public function other(){
		if(IsPostBack) {
			AddInfo( "We got your post request" );
			AddInfo( print_r( $_POST, true ) );
		}
		$this->SetTitle("Simple Admin");
		$this->Display('other');
	}
	public function another(){
		$this->SetTitle("Simple Admin");
		$this->Display('test');
	}
}