<?php
/**
 * Rest API
 *
 * @package    ChatGPT-OpenAI Content Generator
 * @license    GNU General Public License, version 3
 */
 
 if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly
}

class mych_Chatgpt_Custom_End_Point {
   public function __construct() {
        add_action( 'rest_api_init', array( $this, 'cicg_register_custom_endpoint' ) );
    }
    
    public function cicg_register_custom_endpoint() {
        //insert image
        register_rest_route( 'softtechit/v1', '/openai/insertimg', array(
            'methods' => 'POST',
            'callback' => array( $this, 'cicg_handle_custom_request' ),
        ) );
        //schedule post settings
        register_rest_route( 'softtechit/v1', '/openai/schedulesetiings', array(
            'methods' => 'POST',
            'callback' => array( $this, 'cicg_shedule_custom_post' ),
        ) );
    }
    
    public function cicg_handle_custom_request( WP_REST_Request $request ) {

        $cicg_data = $request->get_params('data');
        $cicg_img_url = $cicg_data['img_url'];
        // Set the file path and name of the image you want to upload
        $cicg_image_url = $cicg_img_url;

        $cicg_image_name = 'cicg_image.png';

        // Get the contents of the image and save it to a temporary file
        $cicg_image_data = file_get_contents($cicg_image_url);
        $cicg_temp_file = tempnam(sys_get_temp_dir(), $cicg_image_name);
        file_put_contents($cicg_temp_file, $cicg_image_data);

        // Include the WordPress media library functions
        if (!function_exists('wp_handle_upload')) {
            require_once(ABSPATH . 'wp-admin/includes/file.php');
            require_once(ABSPATH . 'wp-admin/includes/media.php');
            require_once(ABSPATH . 'wp-admin/includes/image.php');
        }

        // Set up the file array with the temporary file path and name
        $cicg_file = array(
            'name' => $cicg_image_name,
            'type' => 'image/png',
            'tmp_name' => $cicg_temp_file,
            'error' => 0,
            'size' => filesize($cicg_temp_file)
        );

        // Upload the file to the WordPress media library
        $cicg_attachment_id = media_handle_sideload($cicg_file, 0);

        // If the upload was successful, add the image to the media library and display its URL
        if (is_wp_error($cicg_attachment_id)) {
            echo 'Error uploading image: ' . $cicg_attachment_id->get_error_message();
        } else {
            $cicg_attachment_url = wp_get_attachment_url($cicg_attachment_id);
            return $data=[
                'success' => 'Image Uploaded Successfully'
            ];
        }

    }
    public function cicg_shedule_custom_post( WP_REST_Request $request ) {

        $cicg_datas = $request->get_params('data');
        $cicg_alldata = $cicg_datas['title_description'];
        $cicg_api_key = esc_attr( get_option('cicg_chatgpt_api_key') );
        $cicg_api_max_tokens = esc_attr(get_option('cicg_chatgpt_api_max_tokens'));
        $cicg_api_temperature = esc_attr( get_option('cicg_api_temperature') );

       if($cicg_alldata){
        foreach( $cicg_alldata as $data){
            //generate schedule title 

        $data_post_title = $data['post_title'];
        $data_post_time = $data['post_date'];

        if($data_post_title && $data_post_time){
            $api_data = [
                "model" => "text-davinci-003",
                "prompt" => 'Please generate a SEO-friendly title for a blog post about'. $data_post_title,
                "max_tokens" => 4000,
                "temperature" => 1,
          ];
          $curl = curl_init();
        curl_setopt_array($curl, array(
          CURLOPT_URL => 'https://api.openai.com/v1/chat/completions',
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_ENCODING => '',
          CURLOPT_MAXREDIRS => 10,
          CURLOPT_TIMEOUT => 0,
          CURLOPT_FOLLOWLOCATION => true,
          CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
          CURLOPT_CUSTOMREQUEST => 'POST',
          CURLOPT_POSTFIELDS => json_encode($api_data),
          CURLOPT_HTTPHEADER => array(
             'Content-Type: application/json',
             "Authorization: Bearer $cicg_api_key"
          ),
        ));
        
        $response = curl_exec($curl);
        
        curl_close($curl);
        $cicg_api_response_decode = json_decode($response);
        $cicg_title = ($cicg_api_response_decode->choices)[0]->text;
        $cicg_post_title = str_replace('"', '', $cicg_title);
        
        //api respone for description
        $api_data = [
            "model" => "text-davinci-003",
            "prompt" => 'Write about'.$data['post_description'],
            "max_tokens" => 4000,
            "temperature" => 1,
      ];
        $curl = curl_init();
        curl_setopt_array($curl, array(
        CURLOPT_URL => 'https://api.openai.com/v1/chat/completions',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_POSTFIELDS => json_encode($api_data),
        CURLOPT_HTTPHEADER => array(
            'Content-Type: application/json',
            "Authorization: Bearer $cicg_api_key"
        ),
        ));
        
        $response = curl_exec($curl);
        
        curl_close($curl);
        $cicg_ap_response_decode = json_decode($response);
        $cicg_post_content = ($cicg_ap_response_decode->choices)[0]->text;
        // Set the post content, title, and other properties
        $cicg_date_str = $data['post_date'];
        $cicg_date = new DateTime($cicg_date_str);
        $cicg_new_date_str = $cicg_date->format('Y-m-d H:i:s');
        // 2023-04-15 12:00:00
            
            $post_data = array(
                'post_title'    => $cicg_post_title,
                'post_content'  => $cicg_post_content,
                'post_date'     =>  $cicg_new_date_str,
                'post_status'   => 'future'
            );
        
            $post_id = wp_insert_post($post_data);
        }
        return "successfully Generated";
        
        }
       }else{
        return "Failed";
       }

    }
    
}

// Initialize the endpoint
new mych_Chatgpt_Custom_End_Point();