<?php

if( !function_exists('boostify_blog_ai_log') ) {
    
    function boostify_blog_ai_log($arMsg, $file_name = 'boostify_blog_ai_') {

        $stEntry = "";

        $arLogData['event_datetime'] = '[' . date('D Y-m-d h:i:s A') . '] [client ' . ']';

        if (is_array($arMsg) || is_object($arMsg)) {

            foreach ($arMsg as $key => $msg)
                $stEntry .= $arLogData['event_datetime'] . " " . " $key => " . "" . print_r($msg, 1) . "\r\n";
        } else {
            $stEntry .= $arLogData['event_datetime'] . " " . $arMsg . "\r\n";
        }

        $stCurLogFileName = $file_name . date('Ymd') . '.txt';

        $path = wp_get_upload_dir()['basedir'];
        $fHandler = fopen($path . '/' . $stCurLogFileName, 'a+');


        fwrite($fHandler, $stEntry);

        fclose($fHandler);
    }

}
function boostify_blog_ai_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 boostify_blog_ai_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 boostify_blog_ai_clean_up_string($title);
}


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

    return $string;
}


function boostify_blog_ai_get_meta_tags( &$content ){

    $metas = [];

    $content = boostify_blog_ai_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 =  boostify_blog_ai_get_meta_title( $meta_content);

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

        $meta_desc =  boostify_blog_ai_get_meta_desc($meta_content);
        if( $meta_desc ){
            $metas['meta_description'] = $meta_desc;
        }
      
        $meta_keywords =  boostify_blog_ai_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 =  boostify_blog_ai_get_meta_title( $meta_content);
            if( $meta_title ){
                $metas['meta_title'] = $meta_title;
            }

            $meta_desc =  boostify_blog_ai_get_meta_desc($meta_content);
            if( $meta_desc ){
                $metas['meta_description'] = $meta_desc;
            }


            $meta_keywords =  boostify_blog_ai_get_meta_keywords( $meta_content );
            if( $meta_keywords ){
                $metas['meta_keywords'] = $meta_keywords;
            }
        
        }else{
            $meta_title =  boostify_blog_ai_get_meta_title( $content);
            if( $meta_title ){
                $metas['meta_title'] = $meta_title;
            }

            $meta_desc =  boostify_blog_ai_get_meta_desc($content);
            if( $meta_desc ){
                $metas['meta_description'] = $meta_desc;
            }


            $meta_keywords =  boostify_blog_ai_get_meta_keywords( $content );
            if( $meta_keywords ){
                $metas['meta_keywords'] = $meta_keywords;
            }
        }
        

        // Description
        ///if(){}

        


    }
    return $metas;
}


function boostify_blog_ai_get_meta_title( &$content ){

    $meta_title_start = false;
    $meta_title_end = false;

    $content = boostify_blog_ai_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 boostify_blog_ai_get_meta_desc( &$content ){

        $meta_desc_start = false;
        $meta_desc_end = false;
        $content = boostify_blog_ai_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 boostify_blog_ai_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;

        }
    }

}

/**
 * Get the first image URL from post content (from <img src="..."> or <figure><img ...>).
 *
 * @param string $content Post content.
 * @return string Empty string if no image found, else the image URL.
 */
function boostify_blog_ai_get_first_image_url_from_content( $content ) {
    if ( empty( $content ) ) {
        return '';
    }
    if ( preg_match( '/<img[^>]+src=["\']([^"\']+)["\']/', $content, $m ) ) {
        return trim( $m[1] );
    }
    return '';
}

/**
 * Convert markdown-style bold **text** to HTML <strong>text</strong> so it displays correctly in Gutenberg.
 *
 * @param string $content Post content.
 * @return string Content with **...** replaced by <strong>...</strong>.
 */
function boostify_blog_ai_markdown_bold_to_strong( $content ) {
    if ( empty( $content ) || ! is_string( $content ) ) {
        return $content;
    }
    return preg_replace( '/\*\*(.*?)\*\*/s', '<strong>$1</strong>', $content );
}

/**
 * Strip GPT-generated image placeholders from content (markdown, "Image: url", standalone URLs, etc.).
 *
 * @param string $content Post content.
 * @return string Content with placeholder image markup removed.
 */
function boostify_blog_ai_strip_placeholder_images( $content ) {
    if ( empty( $content ) ) {
        return $content;
    }
    // Remove markdown images ![alt](url)
    $content = preg_replace( '/!\[[^\]]*\]\s*\([^)]+\)/s', '', $content );
    // Remove "Image: URL" or "Image: url" lines
    $content = preg_replace( '/\s*Image:\s*https?:\/\/[^\s\n]+/i', '', $content );
    // Remove GPT placeholder text: "*Image: * *(Replace with a real image source)*" and similar
    $content = preg_replace( '/\*?\s*Image:\s*\*?\s*\*?\(Replace with[^)]*\)\*?/i', '', $content );
    $content = preg_replace( '/\s*\(Replace with a real image source\)\s*/i', '', $content );
    // Remove standalone <img> tags that point to external placeholder URLs (e.g. wikimedia, placeholder services)
    $content = preg_replace( '/<img[^>]+src=["\']https?:\/\/[^"\']+["\'][^>]*\/?>/i', '', $content );
    // Remove <figure> wrappers that may be left empty or contain only whitespace
    $content = preg_replace( '/<figure[^>]*>\s*<\/figure>/i', '', $content );
    return trim( $content );
}

/**
 * Insert an image (HTML) into content at the position specified by settings (top, middle, below).
 *
 * @param string $content     Post content.
 * @param string $image_html  Full image HTML (e.g. <figure><img src="..." alt="..." /></figure>).
 * @param string $position    One of 'top', 'middle', 'below'.
 * @return string Content with image inserted.
 */
function boostify_blog_ai_insert_image_into_content( $content, $image_html, $position = 'below' ) {
    if ( empty( $image_html ) ) {
        return $content;
    }
    $position = strtolower( trim( $position ) );
    if ( $position === 'top' ) {
        return $image_html . "\n\n" . $content;
    }
    if ( $position === 'below' ) {
        return $content . "\n\n" . $image_html;
    }
    if ( $position === 'middle' ) {
        $len = strlen( $content );
        $mid = (int) ( $len / 2 );
        $space = strpos( $content, ' ', $mid );
        if ( $space !== false ) {
            return substr( $content, 0, $space + 1 ) . "\n\n" . $image_html . "\n\n" . substr( $content, $space + 1 );
        }
        return $content . "\n\n" . $image_html;
    }
    return $content . "\n\n" . $image_html;
}

function boostify_blog_ai_get_schedule(){

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

    ];


    $setting = get_option('boostify_blog_ai_schedule_settings', $defaults );

    return $setting;
}

function boostify_blog_ai_openai_api_key(){
    $api_key = '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';
    return $api_key;
}

/**
 * Get post views count for a specific post.
 *
 * @param int $post_id Post ID. If not provided, uses current post ID.
 * @return int Total views count.
 */
function boostify_blog_ai_get_post_views( $post_id = null ) {
    if ( ! $post_id ) {
        global $post;
        $post_id = $post ? $post->ID : 0;
    }

    if ( ! $post_id ) {
        return 0;
    }

    global $wpdb;
    $table_name = $wpdb->prefix . 'boostify_blog_ai_post_views';
    
    $total_views = $wpdb->get_var( $wpdb->prepare(
        "SELECT SUM(count) FROM {$table_name} WHERE post_id = %d",
        $post_id
    ) );

    return $total_views ? intval( $total_views ) : 0;
}

/**
 * Get unique visitors count for a specific post.
 *
 * @param int $post_id Post ID. If not provided, uses current post ID.
 * @return int Unique visitors count.
 */
function boostify_blog_ai_get_unique_visitors( $post_id = null ) {
    if ( ! $post_id ) {
        global $post;
        $post_id = $post ? $post->ID : 0;
    }

    if ( ! $post_id ) {
        return 0;
    }

    global $wpdb;
    $table_name = $wpdb->prefix . 'boostify_blog_ai_post_views';
    
    $unique_visitors = $wpdb->get_var( $wpdb->prepare(
        "SELECT COUNT(DISTINCT ip_address) FROM {$table_name} WHERE post_id = %d",
        $post_id
    ) );

    return $unique_visitors ? intval( $unique_visitors ) : 0;
}

/**
 * Display post views count.
 *
 * @param int $post_id Post ID. If not provided, uses current post ID.
 * @param string $format Display format. Use %d as placeholder for count.
 * @return string Formatted views count.
 */
function boostify_blog_ai_display_post_views( $post_id = null, $format = 'Views: %d' ) {
    $views = boostify_blog_ai_get_post_views( $post_id );
    return sprintf( $format, $views );
}

/**
 * Display unique visitors count.
 *
 * @param int $post_id Post ID. If not provided, uses current post ID.
 * @param string $format Display format. Use %d as placeholder for count.
 * @return string Formatted unique visitors count.
 */
function boostify_blog_ai_display_unique_visitors( $post_id = null, $format = 'Unique Visitors: %d' ) {
    $unique_visitors = boostify_blog_ai_get_unique_visitors( $post_id );
    return sprintf( $format, $unique_visitors );
}