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

if ( ! class_exists( 'BOOSTIFY_BLOG_AI' ) ) : 
    class  BOOSTIFY_BLOG_AI {

        /**
		 * Constructor.
		 */
		public function __construct(){
           
            add_action( 'wp_head', [ $this, 'add_meta_tags'] );
            add_action( 'boostify_blog_ai_post_cron', [ $this, 'check_post_schedule' ]);
        }

        /**
         * Add meta tags of the post.
         */
        function add_meta_tags() {
            if( is_single() && 'post' == get_post_type()){         
                global $post;

                $meta_title = get_post_meta( $post->ID, 'meta_title', true);
                if( $meta_title ){
                    echo sprintf('<meta name="title" content="%1$s">',esc_attr( $meta_title ));
                }

                $meta_description = get_post_meta( $post->ID, 'meta_description', true);
                if( $meta_description ){
                    echo sprintf('<meta name="description" content="%1$s">',esc_attr( $meta_description ) );
                }

                $meta_keywords = get_post_meta( $post->ID, 'meta_keywords', true);
                if( $meta_keywords ){
                    echo sprintf('<meta name="keywords" content="%1$s">',esc_attr( $meta_keywords ) );
                }
            }
        }

        function check_post_schedule(){

            boostify_blog_ai_log('schedule', 'boostify_');
            
            // Set transient to show notification on dashboard
            set_transient('boostify_cron_started', time(), 300); // Expires in 5 minutes


            //Todo - check if schedule asked to create post. when schedule is save
            // here we are generating and saving content
            
            // Try both option names for backward compatibility
            $setting = get_option('boostify_blog_ai_schedule_settings', []);
            if (empty($setting)) {
                $setting = get_option('boostify_schedule_settings', []);
            }
            
            boostify_blog_ai_log('Settings retrieved: ' . print_r($setting, true), 'boostify_');

            if( empty($setting) || !isset($setting['quantity']) || !$setting['quantity']){
                boostify_blog_ai_log('No quantity set or settings empty. Settings: ' . print_r($setting, true), 'boostify_');
                return ;
            }
            
            $quantity = (int) $setting['quantity'];
            $duration = strtolower( trim( $setting['duration'] ?? '' ) );
            boostify_blog_ai_log( 'Quantity: ' . $quantity . ', Duration: ' . $duration, 'boostify_' );

            // Count boostify posts in the current period (day/week/month/year). Stop creating when count >= quantity.
            $date_query = array();
            if ( $duration === 'day' && $quantity > 0 ) {
                $date_query = array(
                    array(
                        'after'     => date( 'Y-m-d 00:00:00', current_time( 'timestamp' ) ),
                        'inclusive' => true,
                    ),
                );
            } elseif ( $duration === 'week' && $quantity > 0 ) {
                $date_query = array(
                    array(
                        'after'     => date( 'Y-m-d 00:00:00', strtotime( 'monday this week', current_time( 'timestamp' ) ) ),
                        'inclusive' => true,
                    ),
                );
            } elseif ( $duration === 'month' && $quantity > 0 ) {
                $date_query = array(
                    array(
                        'after'     => date( 'Y-m-01 00:00:00', current_time( 'timestamp' ) ),
                        'inclusive' => true,
                    ),
                );
            } elseif ( $duration === 'year' && $quantity > 0 ) {
                $date_query = array(
                    array(
                        'after'     => date( 'Y-01-01 00:00:00', current_time( 'timestamp' ) ),
                        'inclusive' => true,
                    ),
                );
            } elseif ( $quantity > 0 ) {
                // Unknown duration: default to day
                $date_query = array(
                    array(
                        'after'     => date( 'Y-m-d 00:00:00', current_time( 'timestamp' ) ),
                        'inclusive' => true,
                    ),
                );
                $duration = 'day';
            }

            $posts_in_period = 0;
            if ( ! empty( $date_query ) ) {
                $count_args = array(
                    'post_type'      => 'post',
                    'post_status'    => 'any',
                    'meta_key'       => 'boostify_post',
                    'meta_value'     => '1',
                    'posts_per_page' => -1,
                    'fields'         => 'ids',
                    'date_query'     => $date_query,
                );
                $count_query = new WP_Query( $count_args );
                $posts_in_period = $count_query->post_count;
                boostify_blog_ai_log( 'Posts in current period (' . $duration . '): ' . $posts_in_period . ' (limit: ' . $quantity . ')', 'boostify_' );
            }

            if ( $posts_in_period >= $quantity ) {
                boostify_blog_ai_log( 'Limit reached for this ' . $duration . '. Not creating new post.', 'boostify_' );
                return;
            }

            $create_post     = true;
            $posts_to_create = 1;
            boostify_blog_ai_log( 'Creating 1 post (count for period: ' . $posts_in_period . '/' . $quantity . ')', 'boostify_' );

            if( !$create_post ){
                boostify_blog_ai_log('Exiting: create_post is false', 'boostify_');
               return;
            }
            
            boostify_blog_ai_log('Proceeding to create ' . $posts_to_create . ' post(s). Topics: ' . ($setting['topics'] ?? 'not set'), 'boostify_');

            $topics = array_filter( array_map( 'trim', explode( ',', $setting['topics'] ?? '' ) ) );
            if ( empty( $topics ) ) {
                boostify_blog_ai_log('No topics found, exiting', 'boostify_');
                return;
            }

            $api_key = boostify_blog_ai_openai_api_key();
            if ( empty( $api_key ) ) {
                boostify_blog_ai_log('API key not set, exiting', 'boostify_');
                return;
            }
            $boostify_api = new BOOSTIFY_BLOG_API( $api_key );
            $max_word_count = apply_filters( 'boostify_blog_ai_post_word_count_max', 1000 );
            $meta_tags = apply_filters( 'boostify_blog_ai_post_meta_tags', 'false' );
            $post_status = ( ! empty( $setting['trust_ai'] ) ) ? 'publish' : 'pending';

            for ( $i = 0; $i < $posts_to_create; $i++ ) {
                $topic_index = array_rand( $topics );
                $topic = $topics[ $topic_index ];
                boostify_blog_ai_log( 'Creating post ' . ( $i + 1 ) . '/' . $posts_to_create . '. Topic: ' . $topic, 'boostify_' );

                $keywords = apply_filters( 'boostify_blog_ai_post_keywords', $setting['keywords'] ?? '' );
                $content = $boostify_api->generate_content( $topic, $max_word_count, 1, $keywords, $meta_tags, $setting['image'] ?? false, $setting['image_position'] ?? '' );
                if ( ! $content ) {
                    boostify_blog_ai_log( 'Content not generated for topic: ' . $topic . ', skipping', 'boostify_');
                    continue;
                }

                $title = boostify_blog_ai_get_title( $content );
                if ( empty( $title ) ) {
                    boostify_blog_ai_log( 'Title not extracted, skipping', 'boostify_');
                    continue;
                }
                $meta = ( $meta_tags !== 'false' ) ? boostify_blog_ai_get_meta_tags( $content ) : array();
                $meta['boostify_post'] = 1;

                $post_content = boostify_blog_ai_clean_up_string( $content );
                $post_content = str_replace( 'Content:**', '', $post_content );
                $post_content = str_replace( '---', '', $post_content );
                $post_content = boostify_blog_ai_markdown_bold_to_strong( $post_content );

                if ( ! empty( $setting['image'] ) ) {
                    $post_content = boostify_blog_ai_strip_placeholder_images( $post_content );
                }

                $postID = $this->create_post( $title, $post_content, date( 'Y-m-d H:i:s' ), $post_status, $meta );
                if ( $postID ) {
                    boostify_blog_ai_log( 'Post created successfully. Post ID: ' . $postID, 'boostify_' );
                    // Generate AI image from title (or topic), set as featured image, and insert into content at position from settings
                    if ( ! empty( $setting['image'] ) ) {
                        $image_position = ! empty( $setting['image_position'] ) ? $setting['image_position'] : 'below';
                        $image_prompt = ! empty( $title ) ? $title : $topic;
                        $ai_image_url = $boostify_api->generate_image( $image_prompt );
                        if ( $ai_image_url ) {
                            require_once ABSPATH . 'wp-admin/includes/media.php';
                            require_once ABSPATH . 'wp-admin/includes/file.php';
                            require_once ABSPATH . 'wp-admin/includes/image.php';
                            $tmp = download_url( $ai_image_url );
                            if ( ! is_wp_error( $tmp ) ) {
                                $ext = pathinfo( wp_parse_url( $ai_image_url, PHP_URL_PATH ), PATHINFO_EXTENSION );
                                $name = 'boostify-ai-' . $postID . ( $ext ? '.' . $ext : '.png' );
                                $file_array = array( 'name' => $name, 'tmp_name' => $tmp );
                                $attachment_id = media_handle_sideload( $file_array, $postID );
                                if ( ! is_wp_error( $attachment_id ) ) {
                                    set_post_thumbnail( $postID, $attachment_id );
                                    $local_url = wp_get_attachment_image_url( $attachment_id, 'full' );
                                    if ( $local_url ) {
                                        $image_html = '<figure><img src="' . esc_url( $local_url ) . '" alt="' . esc_attr( $title ) . '" /></figure>';
                                        $post_content = boostify_blog_ai_insert_image_into_content( $post_content, $image_html, $image_position );
                                        wp_update_post( array( 'ID' => $postID, 'post_content' => $post_content ) );
                                    }
                                    boostify_blog_ai_log( 'AI image set as featured and inserted (attachment ID: ' . $attachment_id . ')', 'boostify_' );
                                }
                                if ( file_exists( $tmp ) ) {
                                    wp_delete_file( $tmp );
                                }
                            }
                        } else {
                            boostify_blog_ai_log( 'AI image generation failed for post ID: ' . $postID, 'boostify_' );
                        }
                    }
                } else {
                    boostify_blog_ai_log( 'Post creation failed for topic: ' . $topic, 'boostify_' );
                }
            }

            boostify_blog_ai_log( 'check_post_schedule function completed', 'boostify_' );
        }
        
        function create_post( $title, $content, $date, $status = 'published'  ,$meta = [] ){

            boostify_blog_ai_log('create_post called. Title: ' . ($title ?? 'empty') . ', Status: ' . $status, 'boostify_');
            
            $post = [
                'post_title' => $title,
                'post_content' => $content,
                'post_status' => $status,
                'post_date' => $date,
                'meta_input' => $meta
            ];
            
            boostify_blog_ai_log('Calling wp_insert_post with data: ' . print_r($post, true), 'boostify_');
            $post_id = wp_insert_post($post);

            if( !is_wp_error( $post_id ) ){
                boostify_blog_ai_log('wp_insert_post successful. Post ID: ' . $post_id, 'boostify_');
                return $post_id;
            }else{
                $error_message = $post_id->get_error_message();
                boostify_blog_ai_log('wp_insert_post failed. Error: ' . $error_message, 'boostify_');
                echo esc_html( $error_message );
            }

            boostify_blog_ai_log('create_post returning false', 'boostify_');
            return false;
        }

        


    }
endif;    
new BOOSTIFY_BLOG_AI();