<?php 

class SyrusAIAjax {
    private static $instance;
  
    public function __construct() {
      $methods = get_class_methods($this);
      array_shift($methods); // Rimuovo __construct()
      array_shift($methods); // Rimuovo getInstance()
  
      foreach($methods as $key => $method) {
        $method_obj = new ReflectionMethod($this,$method);
        $parameters = $method_obj->getParameters();
        $ajax_types = $parameters[0]->getDefaultValue();
        $method_slug = str_replace('_','-',$method);
  
        if(count($ajax_types) == 0 || in_array('priv',$ajax_types)) // Loggato
          add_action('wp_ajax_syrus-ai-' . $method_slug,[$this,$method]);
        
        if(in_array('no_priv',$ajax_types)) // Non loggato
          add_action('wp_ajax_nopriv_syrus-ai-' . $method_slug,[$this,$method]);
      }
    }
  
    public static function getInstance() {
      if(!isset(self::$instance)) 
        self::$instance = new self();
  
      return self::$instance;
    }

    public static function genera_contenuto($types = ['priv']) {
        global $syrus;
        $open_ai_key = $syrus->get_option('generali','chatgpt_token');
        $url = "https://api.openai.com/v1/chat/completions";

        $prompt = $_POST['prompt'];
        
        $headers = [
            "Content-Type" => "application/json",
            "Authorization" => "Bearer " . $open_ai_key,
          ];
        
        $api_res = wp_remote_post( $url,[
            'method' => 'POST',
            'timeout' => 45,
            'headers' => $headers,
            'body' => json_encode([
                "model" => "text-davinci-003",
                "prompt" => $prompt,
                "temperature" => 0.7,
                "max_tokens" => 2000,
                "top_p" => 1,
                "frequency_penalty" => 0,
                "presence_penalty" => 0
            ]),
        ]);
        
        $res = json_decode( wp_remote_retrieve_body( $api_res ), true );

        $risposta = $res['choices'][0]['text'];

        echo json_encode([
            'status' => "success",
            'result' => $risposta,
        ]);

        wp_die();       
    }

}

$syrusAIAjax = SyrusAIAjax::getInstance();
