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

if( !class_exists('BOOSTIFY_BLOG_AI_SETTING') ):

    class BOOSTIFY_BLOG_AI_SETTING {
        
	
        /**
        * Constructor.
        */
        public function __construct() {

        //    add_action( 'admin_menu', [$this,'register_menu_page'] );
            add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_admin_scripts'] );
			add_filter( 'plugin_action_links_' . BOOSTIFY_BLOG_AI_SLUG, [$this, 'plugin_settings_link'] );
            add_action( 'wp_ajax_boostify_generate_content', [$this, 'generate_content' ]);
            add_action( 'wp_ajax_boostify_save_schedule', [$this, 'save_schedule']);
            add_action( 'wp_ajax_boostify_run_schedule', [$this, 'manual_run']);
			
		
        }

        /**
         * Enqueue stylesheet and script for admin
         */
        function enqueue_admin_scripts( $hook ){
            wp_enqueue_style( 'boosyify_blog_ai_admin_style', BOOSTIFY_BLOG_AI_ASSETS_DIR_URL.'css/admin-style.css', [], wp_rand());
			wp_register_script( 'boostify_blog_ai_admin_script', BOOSTIFY_BLOG_AI_ASSETS_DIR_URL.'js/admin.js', ['jquery'], wp_rand());
            wp_localize_script( 'boostify_blog_ai_admin_script', 'boostify_blog_ai_vars',
                [
                    'ajaxurl' => admin_url( 'admin-ajax.php' ),
                    'nonce'   => wp_create_nonce('boostify_blog_ai_nonce')
                ]
            );
            
        }
		
		 /**
		 * Add plugin action links.
		 * @param array  $links array of plugin actions.
		 * 
		 * return array
		 */
        function plugin_settings_link( $links ) {
        
            $url = esc_url(add_query_arg(
                'page',
                'boostify-dashboard-schedule',
                get_admin_url() . 'admin.php'
            ));
            $settings_link = "<a href='$url'>" . __('Settings','boostify-blog-ai') . '</a>';
             
			$new_links = [];
			$new_links[] = $settings_link;
			
			$links = array_merge($new_links, $links);
            return $links;
        }

     
        /**
         * Register Boostify Blog menu .
         */
        function register_menu_page(){

            add_menu_page(  __( 'Boostify Blog', 'boostify-blog-ai' ), 'Boostify Blog', 'manage_options', 'boostify-blog-ai', [$this,'boostify_settings_page'], 'dashicons-welcome-write-blog' , 90); 
          //  add_submenu_page( 'boostify-blog-ai', __( 'Add New Scheduled Post', 'boostify-blog-ai' ), __( 'Add New', 'boostify-blog-ai' ), 'manage_options', 'boostify-new-post', [ $this, 'new_post_page']);
            add_submenu_page( 'boostify-blog-ai', __( 'Schedule', 'boostify-blog-ai' ), __( 'Schedule', 'boostify-blog-ai' ), 'manage_options', 'boostify-schedule', [ $this, 'schedule_page']);

        }
                
        /**
         * Display Boostify Blog menu page
         */
        function boostify_settings_page( ){ 

            include BOOSTIFY_BLOG_AI_DIR.'/templates/settings.php';      
        }
		
        /**
         * 
         */
        function schedule_page(){

            $defaults = [
                'topics'  => '',
                'keywords'  => '',
                'quantity'=> '',
                'duration' => '',
                'trust_ai'=> false,
                'image' => false,
                'image_position' => ''

            ];
            $setting = get_option('boostify_schedule_settings', $defaults);
          
            include BOOSTIFY_BLOG_AI_DIR.'/templates/schedule.php';   
        } 

		function new_post_page(){

            include BOOSTIFY_BLOG_AI_DIR.'/templates/add-new.php';   
        }


        function generate_content(){

            if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'boostify_blog_ai_nonce' ) ) {
                wp_die();
            }

            $data = array_map('sanitize_text_field', $_POST['data']);
            
            
            $api_key = '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';
            $boostify_api = new BOOSTIFY_BLOG_API($api_key);
            $content = $boostify_api->generate_content( $data['topic'], $data['max_word_count'],$data['number_of_posts'],$data['keywords'],$data['meta_tags']);
          
        //  $content = "";
          
            if( !$content ){
                wp_send_json_error();
            }
            
           // $content = "";
            $number_of_posts = $data['number_of_posts'];
            $post_content = [];

            $posts = [];
            for( $i = 1; $i <= $number_of_posts; $i++ ){
                $j = $i+1;
                if( $j <= $number_of_posts ){
                    $post_content[] = $this->get_string_between( $content, "**Post $i:**",  "**Post $j:**" );
                }else{
                    $ini = strpos($content, "**Post $i:**");
                    if( $ini !== false){
                        $ini += strlen("**Post $i:**");
                    }
                   
                    $post_content[] = trim( substr($content, $ini)); 
                }
                
            }
            foreach( $post_content as $i => $content){
       
                $title = $this->get_title( $content );
                
                $meta  =  [];
                if( $data['meta_tags']  != 'false' ){
                    $meta =  $this->get_meta_tags( $content );
                
                }
                $meta['boostify_post'] = 1;
            
                $post_content = $this->clean_up_string($content);//trim( trim( $content,'---'));
                $post_content = str_replace( 'Content:**','', $post_content );
                $post_content = str_replace( '---','', $post_content );
             
                
               
                $postID = $this->create_post( $title, $post_content, $data['post_date'], $meta);
                if( $postID ){
                    $posts[] = [
                        'title' => $title,
                        'link'  => get_edit_post_link($postID)
                    ];
                }
            
                
            }
            /*
            $posts = [
                [
                    'title' => 'Fluffy Felines: The Ultimate Comfort Companions',
                    'link'  => 'http://localhost/wordpress/wp-admin/post.php?post=114&amp;action=edit'
                ],
                [
                    'title' => 'The Allure of Luxurious Cat Fur',
                    'link'  => 'http://localhost/wordpress/wp-admin/post.php?post=115&amp;action=edit'
                ]
            ];
            */
            wp_send_json( [
                'message' => 'Post Created',
                'posts' =>  $posts
            ]);
            wp_die();

        }

        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 trim(substr($string, $ini, $len));
        }

        function create_post( $title, $content, $date, $status = 'published' , $meta = [] ){

            
            $post = [
                'post_title' => $title,
                'post_content' => $content,
                'post_status' => $status,
                'post_date' => $date,
                'meta_input' => $meta
            ];
            $post_id = wp_insert_post($post);


            if( !is_wp_error( $post_id ) ){
                return $post_id;
            }else{
                echo esc_html( $post_id->get_error_message() );
            }

            return false;
        }

        function get_title( &$content ){
            $title_end = strpos($content, "\n");
            $title_line = substr($content, 0, $title_end );
            

       //     $title_line = trim(str_replace( "Title:",  '', $title_line ));
            $title = trim( trim( str_replace(  'Title:','', $title_line ),'*'));
            $content = str_replace( $title_line,'', $content );
          
            return $this->clean_up_string($title);
        }

        function get_meta_tags( &$content ){

            $metas = [];

            $content = $this->clean_up_string($content);
            $meta_start = strpos($content, "**Meta Tags:**");
            
            if( $meta_start  ==  false && strpos($content, "**Meta Tags**")){

                $meta_start = strpos($content, "**Meta Tags**");
            }elseif( strpos($content, "Meta Tags:") !==  false ){
                $meta_start = strpos($content, "Meta Tags:");
              
            }
          
            if( $meta_start !== false ){
               
                
                $meta_content_end = null;
                if( strpos( $content, '---' ) !==  false ){
                    $meta_content_end =  strpos($content, "---");
                
                }
                
                if( strpos( $content, '**Content:**' ) !==  false ){
                    $meta_content_end = strpos($content, "**Content:**");
                   
                }
                
                $meta_content = substr($content, $meta_start, $meta_content_end );
      
               // pre_print($meta_content_end);
             //   pre_print($meta_content);
                $content = str_replace( $meta_content,'', $content );

                $meta_content = trim(str_replace( "**Meta Tags:**",  '', $meta_content ));
                $meta_content = trim(str_replace( "*Meta Tags:*",  '', $meta_content ));
                $meta_content = trim(str_replace( "Meta Tags:",  '', $meta_content ));

                
                $meta_title =  $this->get_meta_title( $meta_content);

                if($meta_title ){
                    $metas['meta_title'] = $meta_title;
                }

                $meta_desc =  $this->get_meta_desc($meta_content);
                if( $meta_desc ){
                    $metas['meta_description'] = $meta_desc;
                }
                /*
                $meta_content = trim(str_replace( "- **Meta Title:** ",  '', $meta_content ));
                $meta_content = trim(str_replace( " **Meta Title:** ",  '', $meta_content ));
                $meta_content = trim(str_replace( "- Title:",  '', $meta_content ));
                $meta_content = trim(str_replace( "- Meta Title:",  '', $meta_content ));
                $meta_content = trim(str_replace( "**Title:**",  '', $meta_content ));
                */
               /* $meta_desc_end = strpos($meta_content, "\n");
                $meta_desc_line = substr($meta_content, 0, $meta_desc_end );
            
                $meta_desc = str_replace( '- Meta Description: ','', $meta_desc_line );
                $meta_desc = str_replace( '**Meta Description:** ','', $meta_desc_line );
                $meta_desc = str_replace( '** Meta Description:** ','', $meta_desc_line );
                $meta_desc = str_replace( '- Description:','', $meta_desc_line );
                $meta_content = trim(str_replace( "- Meta Description:",  '', $meta_content ));
                $metas['meta_description'] = $meta_desc;

                $meta_content = trim(str_replace( $meta_desc_line,  '', $meta_content ));
                
                $meta_keywords_line = substr($meta_content, 0 );
                $meta_keywords = str_replace( '- Meta Keywords: ','', $meta_keywords_line );
                $metas[ 'meta_keywords'] = trim(trim($meta_keywords,'---'));
                */
               
                $meta_keywords =  $this->get_meta_keywords( $meta_content );
                if( $meta_keywords ){
                    $metas['meta_keywords'] = $meta_keywords;
                }
                
            }else{

               


                $meta_content_end = null;
                if( strpos( $content, '---' ) !==  false ){
                    $meta_content_end =  strpos($content, "---");
                    $meta_content = substr($content, 0, $meta_content_end );
                    $content = str_replace( $meta_content,'', $content );

                    $meta_title =  $this->get_meta_title( $meta_content);
                    if( $meta_title ){
                        $metas['meta_title'] = $meta_title;
                    }

                    $meta_desc =  $this->get_meta_desc($meta_content);
                    if( $meta_desc ){
                        $metas['meta_description'] = $meta_desc;
                    }


                    $meta_keywords =  $this->get_meta_keywords( $meta_content );
                    if( $meta_keywords ){
                        $metas['meta_keywords'] = $meta_keywords;
                    }
                
                }else{
                    $meta_title =  $this->get_meta_title( $content);
                    if( $meta_title ){
                        $metas['meta_title'] = $meta_title;
                    }

                    $meta_desc =  $this->get_meta_desc($content);
                    if( $meta_desc ){
                        $metas['meta_description'] = $meta_desc;
                    }


                    $meta_keywords =  $this->get_meta_keywords( $content );
                    if( $meta_keywords ){
                        $metas['meta_keywords'] = $meta_keywords;
                    }
                }
                

                // Description
                ///if(){}

                


            }
            return $metas;
        }

        function clean_up_string( $string ){
            $string = trim(trim(trim($string,'*'),'"'));

            return $string;
        }

        function get_meta_title( &$content ){

            $meta_title_start = false;
            $meta_title_end = false;

            $content = $this->clean_up_string($content);

            if( strpos( $content, '- **Meta Title:**' ) !==  false ){
                $meta_title_start =  strpos( $content, '- **Meta Title:**' );
                $meta_title_end = strpos($content, "\n");

            }if( strpos( $content, '- *Meta Title:*' ) !==  false ){
                $meta_title_start =  strpos( $content, '- *Meta Title:*' );
                $meta_title_end = strpos($content, "\n");

            }else if( strpos( $content, "**Meta Title:**") !==  false ){
                $meta_title_start =  strpos( $content, "**Meta Title:**");
                $meta_title_end = strpos($content, "\n");
            }
            else if( strpos( $content, "- Title:" ) !==  false ){
                $meta_title_start =  strpos( $content, "- Title:" ) ;
                $meta_title_end = strpos($content, "\n");


            }else if( strpos( $content, "- Meta Title:") !==  false ){
                $meta_title_start =  strpos( $content, "- Meta Title:" );
                $meta_title_end = strpos($content, "\n");
            }
            else if( strpos( $content, "**Title:**") !==  false ){
                $meta_title_start =  strpos( $content, "**Title:**" );
                $meta_title_end = strpos($content, "\n");
            }
            else if( strpos( $content, "- **Title:**") !==  false ){
                $meta_title_start =  strpos( $content, "**Title:**" );
                $meta_title_end = strpos($content, "\n");
            }
            else if( strpos( $content, "- *Title Tag:*") !==  false ){
                $meta_title_start =  strpos( $content, "- *Title Tag:*" );
                $meta_title_end = strpos($content, "\n");
            }
            else if( strpos( $content, "- *Title:*") !==  false ){
                $meta_title_start =  strpos( $content, "- *Title:*" );
                $meta_title_end = strpos($content, "\n");
            }
            elseif( strpos( $content, "- **Title Tag:**") !==  false ){
                $meta_title_start =  strpos( $content, "- **Title Tag:**" );
                $meta_title_end = strpos($content, "\n");
            }
            

            if( $meta_title_end < $meta_title_start){
                $meta_title_end = strpos($content, "\n", $meta_title_start);
            }
            if( $meta_title_start !== false){
               
                
                $meta_title_content = substr( $content, $meta_title_start,  $meta_title_end - $meta_title_start  );    
                $content = str_replace( $meta_title_content,'', $content );

                $meta_title_content = trim(str_replace( "- **Meta Title:**",  '', $meta_title_content ));
                $meta_title_content = trim(str_replace( "**Meta Title:**",  '', $meta_title_content ));
                $meta_title_content = trim(str_replace( "*Meta Title:*",  '', $meta_title_content ));
                $meta_title_content = trim(str_replace( "- Title:",  '', $meta_title_content ));
                $meta_title_content = trim(str_replace( "- Meta Title:",  '', $meta_title_content ));
                $meta_title_content = trim(str_replace( "**Title:**",  '', $meta_title_content ));
                $meta_title_content = trim(str_replace( "- **Title:**",  '', $meta_title_content ));
                $meta_title_content = trim(str_replace( "- *Title Tag:*",  '', $meta_title_content ));
                $meta_title_content = trim(str_replace( "- **Title Tag:**",  '', $meta_title_content ));              
                $meta_title_content = trim(str_replace( "- *Title:*",  '', $meta_title_content ));
               
                
                return $meta_title_content;
            }
        }

        function get_meta_desc( &$content ){

            $meta_desc_start = false;
            $meta_desc_end = false;
            $content = $this->clean_up_string($content);

            if( strpos( $content, '- Meta Description: ' ) !==  false ){
                $meta_desc_start =  strpos( $content, '- Meta Description: ' );
                $meta_desc_end = strpos($content, "\n");

            }else if( strpos( $content, "**Meta Description:**") !==  false ){
          
                $meta_desc_start =  strpos( $content, "**Meta Description:**");
                $meta_desc_end = strpos($content, "\n");
               
            }
            elseif( strpos( $content, "** Meta Description:**" ) !==  false ){
                $meta_desc_start =  strpos( $content, "** Meta Description:**" ) ;
                $meta_desc_end = strpos($content, "\n");

            }else if( strpos( $content, "- Description:") !==  false ){
                $meta_desc_start =  strpos( $content, "- Description:" );
                $meta_desc_end = strpos($content, "\n");
            }
            else if( strpos( $content, "- Meta Description:") !==  false ){
                $meta_desc_start =  strpos( $content, "- Meta Description:" );
                $meta_desc_end = strpos($content, "\n");
            }
            else if( strpos( $content, "- **Description:**") !==  false ){
                $meta_desc_start =  strpos( $content, "- **Description:**" );
                $meta_desc_end = strpos($content, "\n");
            }
            else if( strpos( $content, "- *Meta Description:*") !==  false ){
                $meta_desc_start =  strpos( $content, "- *Meta Description:*" );
                $meta_desc_end = strpos($content, "\n");
            }
            elseif( strpos( $content, "- *Description:*") !==  false ){
                $meta_desc_start =  strpos( $content, "- *Description:*" );
                $meta_desc_end = strpos($content, "\n");
             
               
            }

            if( strpos( $content, '---' ) !==  false ){
                $meta_desc_end =  strpos($content, "---");
            
            }
            

            if( $meta_desc_end < $meta_desc_start){
                $meta_desc_end = false;
            }
           
            if( $meta_desc_start !== false){
                $meta_desc_content = substr( $content, $meta_desc_start, ($meta_desc_end === false)?null:( $meta_desc_end - $meta_desc_start ) );
                
                
              
                $content = str_replace( $meta_desc_content,'', $content );

                $meta_desc_content = trim(str_replace( "- Meta Description:",  '', $meta_desc_content ));
                $meta_desc_content = trim(str_replace( "**Meta Description:**",  '', $meta_desc_content ));
                $meta_desc_content = trim(str_replace( "** Meta Description:**",  '', $meta_desc_content ));
                $meta_desc_content = trim(str_replace( "- Meta Description:",  '', $meta_desc_content ));
                $meta_desc_content = trim(str_replace( "- Description:",  '', $meta_desc_content ));
                $meta_desc_content = trim(str_replace( "- **Description:**",  '', $meta_desc_content ));
                $meta_desc_content = trim(str_replace( "- *Meta Description:*",  '', $meta_desc_content ));
                $meta_desc_content = trim(str_replace( "- *Description:*",  '', $meta_desc_content ));

                return $meta_desc_content;
            }


        }
        
        function get_meta_keywords( &$content ){
            $meta_keywords_start = false;
            if( strpos( $content, '- Meta Keywords:' ) !==  false ){
                $meta_keywords_start =  strpos( $content, '- Meta Keywords:' );
                $meta_keywords_end = strpos($content, "\n");

            }elseif( strpos( $content, '- *Keywords:*' ) !==  false ){
                $meta_keywords_start =  strpos( $content, '- *Keywords:*' );
                $meta_keywords_end = strpos($content, "\n");
                
            }elseif( strpos( $content, '- Keywords' ) !==  false ){
                $meta_keywords_start =  strpos( $content, '- Keywords' );
                $meta_keywords_end = strpos($content, "\n");
                
            }
            if( $meta_keywords_start !== false){
                $meta_keywords_content = substr( $content, $meta_keywords_start, ( $meta_keywords_end - $meta_keywords_start ) );
                $content = str_replace( $meta_keywords_content,'', $content );

                $meta_keywords_content = trim(str_replace( "- *Keywords:*",  '', $meta_keywords_content ));
                $meta_keywords_content = trim(str_replace( "- Meta Keywords:",  '', $meta_keywords_content ));
                $meta_keywords_content = trim(str_replace( "- Keywords",  '', $meta_keywords_content ));
          
                return $meta_keywords_content;

            }
        }

        /**
         * Save the schedule settings from the Form.
         */
        function save_schedule(){

            if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash ($_POST['nonce'])), 'boostify_blog_ai_nonce' ) ) {
                wp_die();
            }

            $data = array_map('sanitize_text_field', $_POST);

            $settings = [
                'topics'         => $data['topics'],
                'keywords'       => $data['keywords'],
                'quantity'       => $data['quantity'],
                'duration'       => $data['duration'],
                'trust_ai'       => $data['trustAI'],
                'image'          => $data['image'],
                'image_position' => $data['imagePosition']
            ];

            update_option('boostify_schedule_settings',$settings);
            /*
            wp_send_json( [
                'message' => 'Post Created',
                'posts' =>  $posts
            ]);
            */
            pre_print($settings);
            wp_die();
            
        }

        /**
         * Get Total number of boostify posts
         */
        function get_total_bootisfy_posts(){

            $args = [
                'post_type'  => 'post',
                'meta_key'   => 'boostify_post',
                'meta_value' => '1',
                'fields'     => 'ids'
            ];
            $boostify_posts = new WP_Query( $args );

            return $boostify_posts->found_posts;
        }


        /**
         * Retrieve last post by boostify.
         */
        function get_last_post(){

            $last_posts = get_posts([
                'post_type'  => 'post',
                'post_status' => 'any',
                'meta_key'    => 'boostify_post',
                'meta_value'  => '1',
                'numberposts' =>  1,
                'orderby'     => 'date',
		        'order'       => 'DESC',
            ]);

            if( count($last_posts) > 0 ){
                return $last_posts[0];
            }

            return false;

            pre_print($last_post);
        }

        /**
         * Execute Manual Run
         */
        function manual_run(){

            if (  ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash ($_POST['nonce'])), 'boostify_blog_ai_nonce' ) ) {
                wp_die();
            }

            $setting = boostify_blog_ai_get_schedule();

            if( !$setting['quantity'] ){
                wp_send_json_error();
            }


            $topics = explode(',',$setting['topics']);
            if( count($topics) > 0 ){
                $topic_index = wp_rand(0, array_key_last( $topics ));
            }else{
                wp_send_json_error();
            }

            $api_key = boostify_blog_ai_openai_api_key();
            $boostify_api = new BOOSTIFY_BLOG_API($api_key);

            $topic = $topics[$topic_index];

            $max_word_count = apply_filters('boostify_blog_ai_post_word_count_max',1000);
            $meta_tags = apply_filters('boostify_blog_ai_post_meta_tags','false'); 
            $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'],  $setting['image_position'] );          

            
            if( !$content ){
                boostify_blog_ai_log('Content not generated', 'boostify_');
                return;
            }

            $post_status = 'pending';
            if( !$setting['trust_ai'] ){
                $post_status = 'pending';
            }
          
            $title = boostify_blog_ai_get_title( $content );
                
            $meta  =  [];
            if( $meta_tags != 'false' ){
                $meta =  boostify_blog_ai_get_meta_tags( $content );  
            }
            $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 );
                

            if( $setting['image']){
                $image_name =  boostify_blog_ai_get_string_between($post_content, '![', ']' );
                $image_url = boostify_blog_ai_get_string_between($post_content, '!['.$image_name.'](', ')' );
                if( $image_url){
                    $post_content = str_replace( "![$image_name]($image_url)"  ,'<img  src= "'.$image_url.'" alt="'.$image_name.'" />', $post_content);
                }
            }
           
               
            $postID = $this->create_post( $title, $post_content, gmdate( 'Y-m-d H:i:s' ), $post_status, $meta );

            if( $postID ){      
                wp_send_json( [
                    'message' => sprintf('<a href="%1$s" >Post</a> Created',  get_edit_post_link($postID)),
                    'post' =>  $postID,
                    'title' => $title,
                    'link'  => get_edit_post_link($postID),
                    
                ]);
            }

            wp_die();
        }
    }

endif;


