<?php
require_once "google_ai_studio/Ai_Studio_Part.php";
require_once "chatgpt/ChatGPT.php";
class AI_Handler{
	/**
	 * Its property instruction
	 *
	 * @var array
	 */
	protected array $instruction;
	/**
	 * Its property prompt
	 *
	 * @var string
	 */
	protected string $prompt;
	/**
	 * Its property ai_type
	 *
	 * @var mixed
	 */
	protected $ai_type='G';

	const AI_TYPE_GIMINI='G';
	const AI_TYPE_CHATGPT='C';

	public function __construct() {
		$this->instruction=[];
		$this->prompt='';
	}

	/**
	 * The get instruction is generated by appsbd
	 *
	 * @return array
	 */
	public function get_instruction(){
		return $this->instruction;
	}

	/**
	 * The add instruction is generated by appsbd
	 *
	 * @param mixed $str It is str param.
	 */
	public function add_instruction( $str) {
		$this->instruction[] = $str;
	}

	/**
	 * The set prompt is generated by appsbd
	 *
	 * @param string $prompt It is prompt param.
	 */
	public function set_content( string $prompt ){
		$this->prompt = $prompt;
	}

	/**
	 * The set ai is generated by appsbd
	 *
	 * @param mixed $type C=ChatGPT, G=Gimini
	 */
	public function set_ai($type){
		$this->ai_type = $type;
	}
	protected function process_gimini() {
		$ai = new Google_AI_Studio();
		$instruction=implode("\n",$this->instruction);
		if(!empty($instruction)){
			$instruction.="\n\n";
		}
		$ai->add_part( $instruction.$this->prompt );

		return $ai->get_text_response();

	}

	protected function process_chatgpt(){
		$ai = new ChatGPT();
		$instruction=implode("\n",$this->instruction);
		if(!empty($instruction)){
			$instruction.="\n\n";
		}
		$ai->add_part( $instruction.$this->prompt );
		return $ai->get_text_response();

	}
	public function get_ai_response(){
		try {
			if ( $this->ai_type == self::AI_TYPE_CHATGPT ) {
				return $this->process_chatgpt();
			} else {
				return $this->process_gimini();
			}
		}catch (Exception $ex){
			return "Error: ".$ex->getMessage();
		}
	}


}