<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

if ( ! class_exists( 'BOOSTIFY_BLOG_API' ) ) : 

    class BOOSTIFY_BLOG_API {

        protected $api_key;
        protected $api_url = 'https://api.openai.com/';

        /**
		 * Constructor.
		 */
		public function __construct( $api_key ){
            boostify_blog_ai_log('BOOSTIFY_BLOG_API constructor called', 'boostify_');
            $this->api_key = $api_key;
            boostify_blog_ai_log('API key set: ' . (empty($this->api_key) ? 'empty' : 'exists'), 'boostify_');
        }

       
        /**
         * Generate blog content.
         */
        function generate_content($topic, $max_word_count, $number_of_posts, $keywords , $include_meta_tags ,$include_image = false, $image_position = 'below' ){

            boostify_blog_ai_log('generate_content called with params: topic=' . $topic . ', max_words=' . $max_word_count . ', num_posts=' . $number_of_posts . ', keywords=' . ($keywords ?? 'none') . ', meta_tags=' . ($include_meta_tags ?? 'false') . ', image=' . ($include_image ? 'true' : 'false'), 'boostify_');
            
            boostify_blog_ai_log('API key check: ' . (empty($this->api_key) ? 'empty' : 'exists (' . substr($this->api_key, 0, 10) . '...)'), 'boostify_');

           // $message =  'Write 2 100 word Content on Cats with keyword fluffy and give me a titles too and meta tags too';
            $message = "Write $number_of_posts posts of max $max_word_count words Content on $topic with $keywords and provide Title ";
            boostify_blog_ai_log('Initial message: ' . $message, 'boostify_');
            
            if( $include_meta_tags != 'false'){
                $message .= " and meta tags too";
                boostify_blog_ai_log('Added meta tags to message', 'boostify_');
            }

            // if( $include_image ) {
            //     $message .= " and include an image ";
            //     boostify_blog_ai_log('Adding image requirement. Position: ' . $image_position, 'boostify_');
            //     switch($image_position){
            //         case 'top':
            //             $message .=" on the top ";
            //             break;
            //         case 'middle':
            //             $message .=" in the middle ";
            //             break;
            //         case 'below' :
            //             $message .=" at the end";
            //             break ;  
            //     }
            // }
            $message .= " For all bold text in the content (section headings, sub-headings, list labels, or any emphasis), use only HTML strong tags: <strong>text</strong>. Do not use ** asterisks for bold anywhere.";
            boostify_blog_ai_log('Final message constructed: ' . $message, 'boostify_');
            
            $endpoint = 'v1/chat/completions';
            $url = $this->api_url. $endpoint;
            boostify_blog_ai_log('API URL: ' . $url, 'boostify_');
          
            $data = [
                'model' => 'gpt-4o',
                'messages' => [
                    [
                        'role' => 'user',
                        'content' => $message
                    ]
                ]
            ];
            boostify_blog_ai_log('Request data prepared. Model: ' . $data['model'], 'boostify_');

            $request_timeout = apply_filters( 'boostify_blog_ai_openai_timeout', 120 );
            boostify_blog_ai_log( 'Making API request to OpenAI... (timeout: ' . $request_timeout . 's)', 'boostify_' );
            $response = wp_remote_post( $url, array(
                'timeout' => $request_timeout,
                'body'    => json_encode( $data ),
                'headers' => array(
                    'Authorization' => 'Bearer ' . $this->api_key,
                    'Content-Type'  => 'application/json',
                ),
            ) );
            
            if ( is_wp_error( $response ) ) {
                $error_message = $response->get_error_message();
                $error_code = $response->get_error_code();
                boostify_blog_ai_log('API request failed with WP_Error. Code: ' . $error_code . ', Message: ' . $error_message, 'boostify_');
                echo 'Something went wrong: ' . esc_html( $error_message );
                return false;
            } else {
                $response_code = wp_remote_retrieve_response_code( $response );
                $response_message = wp_remote_retrieve_response_message( $response );
                boostify_blog_ai_log('API response received. HTTP Code: ' . $response_code . ', Message: ' . $response_message, 'boostify_');

                $body_raw = wp_remote_retrieve_body( $response );
                boostify_blog_ai_log('Response body length: ' . strlen($body_raw) . ' bytes', 'boostify_');
                
                $body = json_decode( $body_raw, true );
                
                if( json_last_error() !== JSON_ERROR_NONE ){
                    boostify_blog_ai_log('JSON decode error: ' . json_last_error_msg(), 'boostify_');
                    boostify_blog_ai_log('Response body (first 500 chars): ' . substr($body_raw, 0, 500), 'boostify_');
                    return false;
                }
               
                if( isset( $body['error'])){
                    $api_error = $body['error'];
                    $error_type = isset($api_error['type']) ? $api_error['type'] : 'unknown';
                    $error_message = isset($api_error['message']) ? $api_error['message'] : 'no message';
                    boostify_blog_ai_log('API returned error. Type: ' . $error_type . ', Message: ' . $error_message, 'boostify_');
                    return false;
                }else{
                   
                    if( isset($body['choices'])){
                        boostify_blog_ai_log('Choices found in response. Count: ' . count($body['choices']), 'boostify_');
                        $content = '';

                        foreach( $body['choices'] as $i => $choice){
                            if( isset($choice['message']['content']) ){
                                $choice_content = $choice['message']['content'];
                                $content .= $choice_content;
                                boostify_blog_ai_log('Choice ' . $i . ' content length: ' . strlen($choice_content) . ' chars', 'boostify_');
                            } else {
                                boostify_blog_ai_log('Choice ' . $i . ' missing content field', 'boostify_');
                            }
                        }
                        
                        boostify_blog_ai_log('Total content length: ' . strlen($content) . ' chars', 'boostify_');
                        boostify_blog_ai_log('generate_content returning content successfully', 'boostify_');
                        return $content;
                      
                    } else {
                        boostify_blog_ai_log('No choices found in response body. Body keys: ' . implode(', ', array_keys($body)), 'boostify_');
                        boostify_blog_ai_log('Response body: ' . print_r($body, true), 'boostify_');
                    }
                   
                }
            }
            boostify_blog_ai_log('generate_content returning false - no content generated', 'boostify_');
            return false;
        }

        /**
         * Generate an image using OpenAI DALL-E 3 (Images API) based on the post title.
         *
         * @param string $prompt Post title or description for the image.
         * @return string|false Image URL on success, false on failure.
         */
        public function generate_image( $prompt ) {
            if ( empty( $this->api_key ) ) {
                boostify_blog_ai_log( 'generate_image: API key empty', 'boostify_' );
                return false;
            }
            $prompt = is_string( $prompt ) ? trim( $prompt ) : '';
            $prompt = preg_replace( '/\s+/', ' ', $prompt );
            if ( empty( $prompt ) ) {
                boostify_blog_ai_log( 'generate_image: prompt/title empty', 'boostify_' );
                return false;
            }
            // Build image prompt from title: "Create an image that illustrates: [title]"
            $title_for_image = wp_trim_words( $prompt, 30 );
            $image_prompt = 'Professional blog article image, clean and modern. Illustrate this topic: ' . $title_for_image;
            boostify_blog_ai_log( 'generate_image: title="' . $prompt . '", prompt="' . $image_prompt . '"', 'boostify_' );

            $url = $this->api_url . 'v1/images/generations';
            $body = array(
                'model'            => 'dall-e-3',
                'prompt'           => $image_prompt,
                'n'                => 1,
                'size'             => '1024x1024',
                'response_format' => 'url',
                'quality'          => 'standard',
            );
            $request_timeout = apply_filters( 'boostify_blog_ai_openai_image_timeout', 90 );
            $response = wp_remote_post( $url, array(
                'timeout' => $request_timeout,
                'body'    => wp_json_encode( $body ),
                'headers' => array(
                    'Authorization' => 'Bearer ' . $this->api_key,
                    'Content-Type'  => 'application/json',
                ),
            ) );

            if ( is_wp_error( $response ) ) {
                boostify_blog_ai_log( 'generate_image: WP_Error ' . $response->get_error_message(), 'boostify_' );
                return false;
            }

            $code    = wp_remote_retrieve_response_code( $response );
            $body_raw = wp_remote_retrieve_body( $response );

            if ( $code !== 200 ) {
                boostify_blog_ai_log( 'generate_image: HTTP ' . $code . ', body=' . substr( $body_raw, 0, 500 ), 'boostify_' );
                return false;
            }

            $data = json_decode( $body_raw, true );
            if ( json_last_error() !== JSON_ERROR_NONE ) {
                boostify_blog_ai_log( 'generate_image: JSON error ' . json_last_error_msg() . ', body=' . substr( $body_raw, 0, 300 ), 'boostify_' );
                return false;
            }
            if ( empty( $data['data'][0]['url'] ) ) {
                boostify_blog_ai_log( 'generate_image: no url in response, body=' . substr( $body_raw, 0, 500 ), 'boostify_' );
                return false;
            }

            boostify_blog_ai_log( 'generate_image: success, url received', 'boostify_' );
            return $data['data'][0]['url'];
        }

        function process_response( $choices ){
            foreach( $choices as $i => $choice){
                $content = $choice['message']['content'];
                //$post_data = explode( '---', $content ); 
            }

        }

        function get_string_between($string, $start, $end){
            $string = ' ' . $string;
            $ini = strpos($string, $start);
            if ($ini == 0) return '';
            $ini += strlen($start);
            $len = strpos($string, $end, $ini) - $ini;
            return substr($string, $ini, $len);
        }
        
    }
endif;    
