<?php
/**
 * Plugin Name: MyContentCreatorPro FREE
 * Plugin URI: https://www.mycontentcreatorpro.com/
 * Description: The My Content Creator Pro WordPress plugin automates the creation of SEO-optimized content using AI to generate engaging articles effortlessly. It boosts productivity by streamlining content creation and improving website engagement.
 * Version: 1.0
 * Author: Chad Portnova
 *
*/

global $wpdb;

if ( !defined('MY_CONSTANT') )
    define('MY_CONSTANT', dirname(__FILE__) . '/');

require (dirname(__file__).'/plugin-update-checker/plugin-update-checker.php');

$myUpdateChecker = Puc_v4_Factory::buildUpdateChecker(
	'https://www.mycontentcreatorpro.com/updates/?action=get_metadata&slug=MyContentCreatorProFree',
	__FILE__, //Full path to the main plugin file or functions.php.
	'MyContentCreatorPro-Free'
);

if ( ! defined( 'ABSPATH' ) ) {	exit; }

if (!defined('WPCH_CURRENT_VERSION')){
    define('WPCH_CURRENT_VERSION', '1.0');
}
// define constants for later use
define('WPCH_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
define('WPCH_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
define('WPCH_API_URL', get_site_url() );
if (!defined('WPCH_LN')) {
    define('WPCH_LN', 'wpch');
}

add_action('admin_enqueue_scripts', 'mywpch_styles');
function mywpch_styles() {
    wp_register_style( 'contentpress_css', plugins_url('/includes/assets/css/afe_style.css',__FILE__));
    wp_register_style( 'contentpress_bootstrap', plugins_url('/includes/assets/css/bootstrap.css',__FILE__));

    wp_enqueue_style( 'contentpress_css' );
    wp_enqueue_style( 'contentpress_bootstrap' );

	//wp_enqueue_script( 'jquery' );
}
add_action('admin_enqueue_scripts', 'mywpch_blogger_js_script1');

function mywpch_blogger_js_script1()
{
    wp_register_script('blogger_bootstrap_script1', plugins_url('/includes/assets/js/bootstrap.min.js',__FILE__), array('jquery'));  
    wp_register_script('jquery', plugins_url('/includes/assets/js/jquery-3.2.1.js',__FILE__), array('jquery'));  
    wp_register_script('blogger_script_validate1', plugins_url('/includes/assets/js/jquery.validate.min.js',__FILE__), array('jquery'));  
      wp_register_script('pdf_client_generate', plugins_url('/includes/assets/js/jspdf.umd.min.js',__FILE__), array('jquery'));  

    wp_enqueue_script('blogger_bootstrap_script1');
    wp_enqueue_script('jquery');
    wp_enqueue_script('blogger_script_validate1');
    wp_enqueue_script('pdf_client_generate');

	
	$js_vars = [
		'endpoint' => esc_url_raw( rest_url( '/wp/v2/media/' ) ),
		'nonce'    => wp_create_nonce( 'wp_rest' ),
	];
	wp_localize_script( 'rest-uploader', 'RestVars', $js_vars );
} 

if (!function_exists('nxs_decodeEntitiesFull')) {

    function nxs_decodeEntitiesFull($string, $quotes = ENT_COMPAT, $charset = 'utf-8') {
        return html_entity_decode(preg_replace_callback('/&([a-zA-Z][a-zA-Z0-9]+);/', 'nxs_convertEntity', $string), $quotes, $charset);
    }

}
if (!function_exists('nxs_convertEntity')) {

    function nxs_convertEntity($matches, $destroy = true) {
        static $table = array('quot' => '&#34;', 'amp' => '&#38;', 'lt' => '&#60;', 'gt' => '&#62;', 'apos' => '&#39;', 'OElig' => '&#338;', 'oelig' => '&#339;', 'Scaron' => '&#352;', 'scaron' => '&#353;', 'Yuml' => '&#376;', 'circ' => '&#710;', 'tilde' => '&#732;', 'ensp' => '&#8194;', 'emsp' => '&#8195;', 'thinsp' => '&#8201;', 'zwnj' => '&#8204;', 'zwj' => '&#8205;', 'lrm' => '&#8206;', 'rlm' => '&#8207;', 'ndash' => '&#8211;', 'mdash' => '&#8212;', 'lsquo' => '&#8216;', 'rsquo' => '&#8217;', 'sbquo' => '&#8218;', 'ldquo' => '&#8220;', 'rdquo' => '&#8221;', 'bdquo' => '&#8222;', 'dagger' => '&#8224;', 'Dagger' => '&#8225;', 'permil' => '&#8240;', 'lsaquo' => '&#8249;', 'rsaquo' => '&#8250;', 'euro' => '&#8364;', 'fnof' => '&#402;', 'Alpha' => '&#913;', 'Beta' => '&#914;', 'Gamma' => '&#915;', 'Delta' => '&#916;', 'Epsilon' => '&#917;', 'Zeta' => '&#918;', 'Eta' => '&#919;', 'Theta' => '&#920;', 'Iota' => '&#921;', 'Kappa' => '&#922;', 'Lambda' => '&#923;', 'Mu' => '&#924;', 'Nu' => '&#925;', 'Xi' => '&#926;', 'Omicron' => '&#927;', 'Pi' => '&#928;', 'Rho' => '&#929;', 'Sigma' => '&#931;', 'Tau' => '&#932;', 'Upsilon' => '&#933;', 'Phi' => '&#934;', 'Chi' => '&#935;', 'Psi' => '&#936;', 'Omega' => '&#937;', 'alpha' => '&#945;', 'beta' => '&#946;', 'gamma' => '&#947;', 'delta' => '&#948;', 'epsilon' => '&#949;', 'zeta' => '&#950;', 'eta' => '&#951;', 'theta' => '&#952;', 'iota' => '&#953;', 'kappa' => '&#954;', 'lambda' => '&#955;', 'mu' => '&#956;', 'nu' => '&#957;', 'xi' => '&#958;', 'omicron' => '&#959;', 'pi' => '&#960;', 'rho' => '&#961;', 'sigmaf' => '&#962;', 'sigma' => '&#963;', 'tau' => '&#964;', 'upsilon' => '&#965;', 'phi' => '&#966;', 'chi' => '&#967;', 'psi' => '&#968;', 'omega' => '&#969;', 'thetasym' => '&#977;', 'upsih' => '&#978;', 'piv' => '&#982;', 'bull' => '&#8226;', 'hellip' => '&#8230;', 'prime' => '&#8242;', 'Prime' => '&#8243;', 'oline' => '&#8254;', 'frasl' => '&#8260;', 'weierp' => '&#8472;', 'image' => '&#8465;', 'real' => '&#8476;', 'trade' => '&#8482;', 'alefsym' => '&#8501;', 'larr' => '&#8592;', 'uarr' => '&#8593;', 'rarr' => '&#8594;', 'darr' => '&#8595;', 'harr' => '&#8596;', 'crarr' => '&#8629;', 'lArr' => '&#8656;', 'uArr' => '&#8657;', 'rArr' => '&#8658;', 'dArr' => '&#8659;', 'hArr' => '&#8660;', 'forall' => '&#8704;', 'part' => '&#8706;', 'exist' => '&#8707;', 'empty' => '&#8709;', 'nabla' => '&#8711;', 'isin' => '&#8712;', 'notin' => '&#8713;', 'ni' => '&#8715;', 'prod' => '&#8719;', 'sum' => '&#8721;', 'minus' => '&#8722;', 'lowast' => '&#8727;', 'radic' => '&#8730;', 'prop' => '&#8733;', 'infin' => '&#8734;', 'ang' => '&#8736;', 'and' => '&#8743;', 'or' => '&#8744;', 'cap' => '&#8745;', 'cup' => '&#8746;', 'int' => '&#8747;', 'there4' => '&#8756;', 'sim' => '&#8764;', 'cong' => '&#8773;', 'asymp' => '&#8776;', 'ne' => '&#8800;', 'equiv' => '&#8801;', 'le' => '&#8804;', 'ge' => '&#8805;', 'sub' => '&#8834;', 'sup' => '&#8835;', 'nsub' => '&#8836;', 'sube' => '&#8838;', 'supe' => '&#8839;', 'oplus' => '&#8853;', 'otimes' => '&#8855;', 'perp' => '&#8869;', 'sdot' => '&#8901;', 'lceil' => '&#8968;', 'rceil' => '&#8969;', 'lfloor' => '&#8970;', 'rfloor' => '&#8971;', 'lang' => '&#9001;', 'rang' => '&#9002;', 'loz' => '&#9674;', 'spades' => '&#9824;', 'clubs' => '&#9827;', 'hearts' => '&#9829;', 'diams' => '&#9830;', 'nbsp' => '&#160;', 'iexcl' => '&#161;', 'cent' => '&#162;', 'pound' => '&#163;', 'curren' => '&#164;', 'yen' => '&#165;', 'brvbar' => '&#166;', 'sect' => '&#167;', 'uml' => '&#168;', 'copy' => '&#169;', 'ordf' => '&#170;', 'laquo' => '&#171;', 'not' => '&#172;', 'shy' => '&#173;', 'reg' => '&#174;', 'macr' => '&#175;', 'deg' => '&#176;', 'plusmn' => '&#177;', 'sup2' => '&#178;', 'sup3' => '&#179;', 'acute' => '&#180;', 'micro' => '&#181;', 'para' => '&#182;', 'middot' => '&#183;', 'cedil' => '&#184;', 'sup1' => '&#185;', 'ordm' => '&#186;', 'raquo' => '&#187;', 'frac14' => '&#188;', 'frac12' => '&#189;', 'frac34' => '&#190;', 'iquest' => '&#191;', 'Agrave' => '&#192;', 'Aacute' => '&#193;', 'Acirc' => '&#194;', 'Atilde' => '&#195;', 'Auml' => '&#196;', 'Aring' => '&#197;', 'AElig' => '&#198;', 'Ccedil' => '&#199;', 'Egrave' => '&#200;', 'Eacute' => '&#201;', 'Ecirc' => '&#202;', 'Euml' => '&#203;', 'Igrave' => '&#204;', 'Iacute' => '&#205;', 'Icirc' => '&#206;', 'Iuml' => '&#207;', 'ETH' => '&#208;', 'Ntilde' => '&#209;', 'Ograve' => '&#210;', 'Oacute' => '&#211;', 'Ocirc' => '&#212;', 'Otilde' => '&#213;', 'Ouml' => '&#214;', 'times' => '&#215;', 'Oslash' => '&#216;', 'Ugrave' => '&#217;', 'Uacute' => '&#218;', 'Ucirc' => '&#219;', 'Uuml' => '&#220;', 'Yacute' => '&#221;', 'THORN' => '&#222;', 'szlig' => '&#223;', 'agrave' => '&#224;', 'aacute' => '&#225;', 'acirc' => '&#226;', 'atilde' => '&#227;', 'auml' => '&#228;', 'aring' => '&#229;', 'aelig' => '&#230;', 'ccedil' => '&#231;', 'egrave' => '&#232;', 'eacute' => '&#233;', 'ecirc' => '&#234;', 'euml' => '&#235;', 'igrave' => '&#236;', 'iacute' => '&#237;', 'icirc' => '&#238;', 'iuml' => '&#239;', 'eth' => '&#240;', 'ntilde' => '&#241;', 'ograve' => '&#242;', 'oacute' => '&#243;', 'ocirc' => '&#244;', 'otilde' => '&#245;', 'ouml' => '&#246;', 'divide' => '&#247;', 'oslash' => '&#248;', 'ugrave' => '&#249;', 'uacute' => '&#250;', 'ucirc' => '&#251;', 'uuml' => '&#252;', 'yacute' => '&#253;', 'thorn' => '&#254;', 'yuml' => '&#255;');
       ?><?php if (isset($table[$matches[1]]))
            return $table[$matches[1]];
        // else 
        return $destroy ? '' : $matches[0];
    }

}

require 'includes/functions.php';
require 'includes/auto_content/function-autoblog.php';
//require 'includes/seo_traffic/function_seo.php';

add_action('admin_menu', 'mywpch_plugin_menu');
add_action('admin_post_wpch_form_action','mywpch_form_action');
add_action('admin_post_wpch_activate','activate_account');
add_action('admin_post_wpch_delete_account','delete_account');

add_action('admin_post_wpch_tumblr_authorize_action','tumblr_authorize_action'); //action to authorize tumblr
add_action('admin_post_wpch_tumblr_callback_authorize','tumblr_callback_authorize');
	
add_action('admin_post_wpch_linkedin_authorize_action', 'linkedin_authorize_action');
add_action('admin_post_wpch_linkedin_callback_authorize', 'linkedin_callback_authorize');

add_action( 'transition_post_status','myauto_post_ch', 10, 3 );
add_action('publish_future_post', 'myauto_post_schedule_ch'); 

add_action('save_post', 'mysave_wpch_meta_value');
			
function mywpch_form_action() {
	if (!empty($_POST) && wp_verify_nonce($_POST['wpch_form_nonce'], 'wpch_form_action')) {
		include('includes/cores/save-account.php');
	} else {
		die('No script kiddies please!!');
	}
}

global $wpdb;

function mywpch_plugin_menu(){
    
	$pro_licence_activate = get_option('mycpfree_licence_key');
    $pro_licence_type = get_option('mycpfree_licence_type');
    $pro_licence_status = get_option('mycpfree_licence_status');
	add_menu_page('MyContentCreatorPro Free', 'MyContentCreatorPro  Free', 'publish_pages', 'MyContentCreatorPro', 'myfunc_content_hero' );
		if(!empty($pro_licence_status) && $pro_licence_status != "inactive") {
	add_submenu_page('MyContentCreatorPro', 'Auto Content Creation', 'Auto Content Creation', 'manage_options', 'my-auto-content', 'mywpch_main' );
	add_submenu_page( '', '', '', 'manage_options', 'my-import-result', 'mywpch_saved_result_function' );
	add_submenu_page( '', '', '', 'manage_options', 'my-campaign', 'mywpch_auto_campaign_function' );
	add_submenu_page( '', '', '', 'manage_options', 'my-campaign-details', 'mywpch_auto_campaign_details_function' );
	add_submenu_page( '', '', '', 'manage_options', 'my-campaign-posts', 'mywpch_auto_campaign_post_function' );
	add_submenu_page( '', '', '', 'manage_options', 'my-auto-campaign-edit', 'mywpch_edit_function' );
	add_submenu_page( '', '', '', 'manage_options', 'wpch_social_sharing', 'wpch_social_sharing' );
    //add_submenu_page('MyContentCreatorPro', 'Article Generator ', 'Article Generator', 'publish_pages','wpch_artic_gen_front', 'mywpch_art_gen_front_page' );
	//add_submenu_page('MyContentCreatorPro', 'Article Generator ', 'Article Generator', 'publish_pages','wpch_artic_gen_front', 'mywpch_art_gen_front_page' );
    add_submenu_page( 'MyContentCreatorPro', 'Settings', 'Settings', 'manage_options', 'mywpch_setting', 'mywpch_setting_function' );
	}
	add_submenu_page('MyContentCreatorPro', 'Activate License', 'Activate License', 'publish_pages','wp_mycp_unlock_pro', 'wp_mycp_unlock_pro' );
    //add_submenu_page( 'rank-buddy-plugin', 'ALLURE', 'publish_pages', 'rank-buddy-plugin','rank_buddy_setting' );
    add_submenu_page(
        'MyContentCreatorPro',
        'Support',
        'Support',
        'manage_options',
        'wp_myc_support_page',
        'wp_myc_support_page'
    ); 
}


function wp_myc_support_page() {
    // Get the plugin directory path
    $plugin_dir = plugin_dir_path(__FILE__);
    ?>
    <div class="wrap">
      

        <div class="wpcp-support-page">
            <div class="wpcp-support-content">
                <h2 class="wpcp-xlarge">Support &amp; Resources</h2>

                <div class="wpcp-support-section">
                    <h3>Training Videos</h3>
                    <p>Learn how to use the plugin and explore its features with our comprehensive training videos.</p>
                    <a href="https://www.mycontentcreatorpro.com/training-videos" class="wpcp-button" target="_blank">Watch Training Videos</a>
                </div>

                <div class="wpcp-support-section">
                    <h3>Get Support</h3>
                    <p>Need assistance or have any questions? Our support team is here to help.</p>
                    <a href="https://i-mediabizzhelp.com" class="wpcp-button" target="_blank">Contact Support</a>
                </div>
            </div>

            <div class="wpcp-support-banners">
                <?php
                // Replace these filenames and URLs with your actual banner image filenames and URLs
                $banner_data = array(
                    array(
                        'file' => 'wp-learning-101.webp',
                        'url' => 'https://www.wplearning101.com'
                    ),
                    array(
                        'file' => 'my-content-creator-pro-elite.webp',
                        'url' => 'https://www.mycontentcreatorpro.com'
                    ),
                    array(
                        'file' => 'wptrackit.webp',
                        'url' => 'https://www.wptrackit.com'
                    )                    
                    );
                

                       foreach ($banner_data as $banner) {
                    $banner_url = plugin_dir_url(__DIR__) . '/MyContentCreatorPro-Free/assets/img/' . $banner['file'];
                    echo '<a href="' . esc_url($banner['url']) . '" target="_blank"><img src="' . esc_url($banner_url) . '" alt="Banner" class="wpcp-banner-image"></a>';
                }
                ?>
            </div>
        </div>
    </div>

    <style>
        .wpcp-support-page {
            display: flex;
            justify-content: space-between;
            margin-top: 20px;
        }

        .wpcp-support-content {
            flex: 1;
            max-width: 60%;
        }

        .wpcp-support-section {
            margin-bottom: 30px;
        }

        .wpcp-button {
            display: inline-block;
            background-color: #00193A;
            color: #fff;
            text-decoration: none;
            padding: 10px 20px;
            border-radius: 4px;
            transition: background-color 0.3s ease;
        }

        .wpcp-button:hover {
            background-color: #002855;
            color:#fff;
        }

        .wpcp-support-banners {
            flex: 1;
            max-width: 35%;
            margin-left: 20px;
        }

        .wpcp-banner-image {
            max-width: 80%;
            margin-bottom: 20px;
        }

        .wpcp-xlarge {
            font-size: 24px;
            font-weight: bold;
            margin-bottom: 20px;
        }
    </style>
    <?php
}


function wp_mycp_unlock_pro(){
    
    $url = admin_url('admin.php?page=wp_mycp_unlock_pro');
    if(isset($_POST['license-submit']))
    {
        global $wpdb;
        
        update_option('mycpfree_licence_key',$_POST['post_pro1_licence_key']);
        update_option('mycpfree_licence_email',$_POST['post_pro1_licence_email']);
        
         $email_to_query = $_POST['post_pro1_licence_email'];
        // Set up the API request
        if($_POST['post_pro1_licence_key']=='MyContentCreatorFree-1234') {
                $api_endpoint = 'https://www.mycontentcreatorpro.com/api/plugininfo.php';
    
     $additional_params = array(
        'email' => $email_to_query,
        'ip' => $_SERVER['REMOTE_ADDR'], // Get IP address of the client
        'website_url' => 'https://' . $_SERVER['HTTP_HOST'], // Get website URL
        'date' => date('Y-m-d H:i:s') // Current date and time
    );
    
    // Add additional parameters to the query string
    $api_endpoint = add_query_arg($additional_params, $api_endpoint);
           
        // Make the API request
        $response = wp_remote_get($api_endpoint);

        
        // Check for errors
        if (is_wp_error($response)) {
            echo 'Error: ' . $response->get_error_message();
        } else {
            // Parse the JSON response or handle the data as needed
            $body = wp_remote_retrieve_body($response);
    
            if ($body) {
                  
                      if($body=='SUCCESS'){
                        update_option('mycpfree_licence_status','completed');
                                echo 'Your License is active now.';        
                    }
                      if($body=='Failed'){
                        update_option('mycpfree_licence_status','inactive');
                                    echo '<h3>No Match found. Please recheck your license again.</h3>';
    
                    }
            } else {
                update_option('mycpfree_licence_status','inactive');
            }
        }
        } else {
          echo '<h3>Please Enter valid license key.</h3>';
        }
    ?>   
        <script>
            location.href = "<?php  echo $url; ?>";
        </script>
        <?php
    }
    
    $pro_licence_actv = get_option('mycpfree_licence_key');
    $pro_licence_email = get_option('mycpfree_licence_email');
    $pro_licence_status = get_option('mycpfree_licence_status');
    
    ?>
    <br/>
    <div class="content_hero_container">
    <h3>Welcome To MyContentCreatorPro Free</h3><br/>
    <h3>Please activate your license below:</h3><br/>
    <form action="" method="post" enctype="multipart/form-data">
            <div style="display: flex;margin-top:10px;">
            
            <label style="padding:5px;cursor:auto;width:20%;font-size: 16px;">  Email address: </label> 
            <input type="text" class="regular-text" name="post_pro1_licence_email" placeholder="Enter Enter valid email address" value="<?php if(!empty($pro_licence_email)) { echo $pro_licence_email; } ?>" required> <br/>
        </div>
        <div style="display: flex;margin-top:10px;">
            
            <label style="padding:5px;cursor:auto;width:20%;font-size: 16px;">  License Key: </label> 
            <input type="text" class="regular-text" name="post_pro1_licence_key" placeholder="Enter the  licence key" value="<?php if(!empty($pro_licence_actv)) { echo $pro_licence_actv; } ?>" required> <br/>
        </div>
        <input style="margin-top:1em !important;" class="btn btn-success" type="submit" name="license-submit" value="Submit" />
        
    </form>
    </div>
    <?php 
    if($pro_licence_actv == "MyContentCreatorFree-1234" && $pro_licence_status != "inactive")
    {
        echo "<br/><h3> Thank You For Activating MyContentCreatorPro Free. </h3><br/><br/><br/>";
    }  else {
                echo "<br/><h3 style='color:#ff0000;'> Please enter valid email address and make sure your License is valid.</h3><br/><br/><br/>";
    
    }
        
    }

function mywpch_unlock_pro(){
	include( plugin_dir_path( __FILE__ ) . '/includes/lib/licence/licence.php' );
}

function mywpch_sharing(){
	include( plugin_dir_path( __FILE__ ) . '/includes/wpch_sharing.php' );
}

function myfunc_content_hero(){
	include( plugin_dir_path( __FILE__ ) . '/includes/welcome.php' );
}

function mywpch_api_settings()
{
    include( plugin_dir_path( __FILE__ ) . '/includes/api_settings.php' );
}


function mywpch_article_gen()
{
    include( plugin_dir_path( __FILE__ ) . '/includes/article_gen.php' );
}



function mywpch_search_products(){
    include( plugin_dir_path( __FILE__ ) . '/includes/autocontent.php' );
}
function mywpch_setting(){
    include( plugin_dir_path( __FILE__ ) . '/includes/seo.php' );
}
function mywpch_update_page(){
    include( plugin_dir_path( __FILE__ ) . '/includes/auto_content/template/update.php' );
}
function mywpch_main(){
    include_once( plugin_dir_path( __FILE__ ) . '/includes/auto_content/template/search-blog.php' );
}
function mywpch_saved_result_function(){
    include_once( plugin_dir_path( __FILE__ ) . '/includes/auto_content/template/saved-result.php' );
}
function mywpch_auto_campaign_function(){
    include_once( plugin_dir_path( __FILE__ ) . '/includes/auto_content/template/auto_blog.php' );
}
function mywpch_auto_campaign_post_function(){
    include_once( plugin_dir_path( __FILE__ ) . '/includes/auto_content/template/campaign-post.php' );
}
function mywpch_auto_campaign_details_function(){
    include_once( plugin_dir_path( __FILE__ ) . '/includes/auto_content/template/campaign-detail.php' );
}
function mywpch_setting_function(){
    include_once( plugin_dir_path( __FILE__ ) . '/includes/auto_content/template/setting.php' );
}
function mywpch_edit_function(){
    include_once( plugin_dir_path( __FILE__ ) . '/includes/auto_content/template/campaign-edit.php' );
}
function mywpch_art_gen_front_page()
{ 
    include_once( plugin_dir_path( __FILE__ ) . '/includes/article_spin.php' );
}



function mywpch_add_channels()
{
    include_once( plugin_dir_path( __FILE__ ) . '/includes/ytube_channels/ytubechannel-search.php' );
}

function myinit_nsw_ui_wp_full_auto_tags_manager_ch()
{ 
	require_once ( dirname(__file__).'/includes/seo_traffic/wp-full-auto-tags-manager/wp-full-auto-tags-manager.php' );
	require_once ( dirname(__file__).'/includes/seo_traffic/wp-full-auto-tags-manager/admin/admin.php' ); 
}

add_action('admin_enqueue_scripts', 'mywpch_callback_scripts');
function mywpch_callback_scripts() {
    wp_register_style( 'ch-style', plugin_dir_url( __FILE__ ).'assets/css/custom.css' );
    wp_enqueue_style( 'ch-style' );
	wp_enqueue_script( 'ch-script', plugin_dir_url( __FILE__ ) . 'assets/js/custom.js' );
}

function mywpch_campaign_plugin_database(){
	global $wpdb;

	$table_name = $wpdb->prefix . 'ch_camapign';
    if( $wpdb->get_var( "show tables like '{$table_name}'" ) != $table_name ) {
	$charset_collate = $wpdb->get_charset_collate();

	$sql = "CREATE TABLE $table_name 
		(
			id mediumint(20) NOT NULL AUTO_INCREMENT,
			c_title varchar(255) NOT NULL, 
			c_sub_cat varchar(255) NOT NULL, 
			c_keyword varchar(255) NOT NULL, 
			c_img_key text NOT NULL,
			c_ytube_key text NOT NULL,
			c_prod_short text NOT NULL,			
			c_hours mediumint(20) NULL,
			c_days mediumint(20) NULL,
			c_date datetime NOT NULL,
			PRIMARY KEY  (id)
		) 	$charset_collate;";

	require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
	dbDelta( $sql );
	}
}

function mywpch_tmp_table_plugin_database() 
{
	global $wpdb;

	$table_name1 = $wpdb->prefix . 'ch_tmp_table';
    if( $wpdb->get_var( "show tables like '{$table_name1}'" ) != $table_name1 ) {
	$charset_collate1 = $wpdb->get_charset_collate();

	$sql1 = "CREATE TABLE $table_name1 
		(
			id mediumint(20) NOT NULL AUTO_INCREMENT,
			catg_id mediumint(20) NOT NULL,
			title text NOT NULL, 
			link varchar(255) NOT NULL, 
			short_des text NOT NULL,
			long_desc text NOT NULL,
			type varchar(255) NOT NULL, 
			PRIMARY KEY  (id)
		) 	$charset_collate1;";

	require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
	dbDelta( $sql1 );
	}
}

function mywpch_saved_result_plugin_database() 
{
	global $wpdb;

	$table_name2 = $wpdb->prefix . 'ch_saved_result';
    if( $wpdb->get_var( "show tables like '{$table_name2}'" ) != $table_name2 ) {
	$charset_collate2 = $wpdb->get_charset_collate();

	$sql2 = "CREATE TABLE $table_name2 
		(
			id mediumint(20) NOT NULL AUTO_INCREMENT,
			catg_id mediumint(20) NOT NULL,
			title text NOT NULL, 
			link text NOT NULL, 
			short_des text NOT NULL,
			long_desc text NOT NULL,
			type varchar(255) NOT NULL, 
			PRIMARY KEY  (id)
		) 	$charset_collate2;";

	require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
	dbDelta( $sql2 );
	}
}

function mywpch_campaign_post_plugin_database() 
{
	global $wpdb;

	$table_name3 = $wpdb->prefix . 'ch_campaign_post';
    if( $wpdb->get_var( "show tables like '{$table_name3}'" ) != $table_name3 ) {
	$charset_collate3 = $wpdb->get_charset_collate();

	$sql3 = "CREATE TABLE $table_name3
		(
			id mediumint(20) NOT NULL AUTO_INCREMENT,
			post_id mediumint(20) NOT NULL,
			campaign_id mediumint(20) NOT NULL, 
			schedule_date datetime NOT NULL, 
			status tinyint(1) NOT NULL,
			PRIMARY KEY  (id)
		) 	$charset_collate3;";

	require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
	dbDelta( $sql3 );
	}
}

function ezarticles_table_plugin_database() 
{
	global $wpdb;
	
	$ez_affili_url_table_name = $wpdb->prefix . 'mych_ezarticles';
	$ez_affili_url_charset_collate = $wpdb->get_charset_collate();
    if ($wpdb->get_var("SHOW TABLES LIKE '$ez_affili_url_table_name'") != $ez_affili_url_table_name) {

	$ez_affili_url_sql = "CREATE TABLE $ez_affili_url_table_name
		(
			id mediumint(20) NOT NULL AUTO_INCREMENT,
			aid mediumint(20) NOT NULL,
			title text NOT NULL, 
			summary text NOT NULL, 
			cat text NOT NULL,
			scat text NOT NULL,
			url text NOT NULL, 
			schedule_date datetime NOT NULL, 
			used tinyint(1) NOT NULL,
			PRIMARY KEY  (id)
		) 	$ez_affili_url_charset_collate;";

	require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
	dbDelta( $ez_affili_url_sql );	
		}
}

function afarticles_table_plugin_database() 
{
	global $wpdb;
	
	$af_affili_url_table_name = $wpdb->prefix . 'mych_afarticles';
	$af_affili_url_charset_collate = $wpdb->get_charset_collate();
    if ($wpdb->get_var("SHOW TABLES LIKE '$af_affili_url_table_name'") != $af_affili_url_table_name) {

	$af_affili_url_sql = "CREATE TABLE $af_affili_url_table_name
		(
			id mediumint(20) NOT NULL AUTO_INCREMENT,
			title text NOT NULL, 
			description text NOT NULL, 
			image text NOT NULL, 
			category text NOT NULL, 
			vid_id text NOT NULL, 
			channel_post_id text NOT NULL,
			af_enable text NOT NULL,
			schedule_date datetime NOT NULL, 
			status tinyint(1) NOT NULL,
			PRIMARY KEY  (id)
		) 	$af_affili_url_charset_collate;";

	require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
	dbDelta( $af_affili_url_sql );	
		}
}

register_activation_hook( __FILE__, 'wpmy_activation' );
register_deactivation_hook( __FILE__, 'wpmy_deactivation' );
function wpmy_activation() {
	global $wp_rewrite,$wpdb;
	//include( plugin_dir_path( __FILE__ ) . '/includes/activation.php' );
	mywpch_campaign_plugin_database();
	mywpch_tmp_table_plugin_database();
	mywpch_saved_result_plugin_database();
	mywpch_campaign_post_plugin_database();
	ezarticles_table_plugin_database();
	afarticles_table_plugin_database();
	//custom_schedule_cron_jobs();
	$af_table_name_details = $wpdb->prefix . 'mych_afarticles';
	//comments two lines by naveen on 22-10.
	//$wpdb->query("ALTER TABLE $af_table_name_details ADD keyword text NOT NULL");
	//$wpdb->query("ALTER TABLE $af_table_name_details ADD subkey longtext NOT NULL");
}

function wpmy_deactivation() {
	global $wp_rewrite,$wpdb;
}

function mych_keyword_tool_meta_boxes() {
	
	 global $post;
	 $pid=$post->ID;
	
	 ?>


	<input id="wp_keyword_tool_ajax_src" type="hidden" value="<?php echo site_url('/?wp_keyword_tool=ajax&pid='.$pid)  ?>"> <input type="text" value="" autocomplete="off" placeholder=<?php _e( 'Keyword...','wp_keyword_tool' ) ?> size="14" class="form-input-tip" id="wp_keyword_tool_search_txt"> 
	<input type="button" tabindex="3" value="<?php _e('Search','wp_keyword_tool') ?>" class="button" id="wp_keyword_tool_more">
	<input type="button" tabindex="3" value="x" class="button tagadd" id="wp_keyword_tool_clean">
	 
	
	
<div id="wp_keyword_tool_body">
	
	<div id="wp_keyword_tool_keywords" class="wp-tab-panel"></div>
	
	<div style="margin-bottom:10px;padding-left:5px;"><label><input type="checkbox" id="wp_keyword_tool_check" value="s"><?php _e('Check/uncheck all','wp_keyword_tool') ?></label></div>

    <input type="button"   value="<?php _e('Add Tags','wp_keyword_tool') ?>" class="button" id="wp_keyword_tool_tag_btn">
	<input type="button"   value="<?php _e('Watch Density','wp_keyword_tool') ?>" class="button" id="wp_keyword_tool_density_btn">
	<input type="button"   value="<?php _e('Show as list','wp_keyword_tool') ?>" class="button" style="margin: 0 auto;" id="wp_keyword_tool_list_btn">
	
	<p>
		<?php _e('keyword tool has found','wp_keyword_tool') ?> (<span class="wp_keyword_tool_count"></span>) <?php _e('keywords for the term','wp_keyword_tool') ?>
	(<span class="wp_keyword_tool_keyword_status"></span>) 
	
	
	</p>
	
</div>

<div  style="display: none"  id="wp-keyword-tool-list-wrap">
	<textarea style="width:100%;height: 300px;" id="wp-keyword-tool-list"></textarea>
</div>




<?php
}

function mych_keyword_tool_meta_boxes2() {
	global $post;
	$pid=$post->ID;
	$oldkeys=get_post_meta($pid,'wp_keyword_tool_density',1 );
	
	if(! is_array($oldkeys)) $oldkeys=array();
	
	$display= ' style="display:none" ';
	if(count($oldkeys) >0) $display = "";
	
	echo '<div id="wp_keyword_tool_density_head" '.$display.' class="wp_keyword_tool_itm noborder"><div class="wp_keyword_tool_keyword"><strong>'.__('Keyword','wp_keyword_tool').'</strong></div><div class="wp_keyword_tool_volume"><strong>'.__('Density','wp_keyword_tool').'</strong></div><div class="clear"></div></div>';
	echo '<div id="wp_keyword_tool_keywords_density">'; 
	
	foreach($oldkeys as $key){
		?>
		<div class="wp_keyword_tool_itm"><span><a   class="dashicons-before dashicons-dismiss"></a></span><div class="wp_keyword_tool_keyword"><?php echo $key ?></div><div class="wp_keyword_tool_volume">-</div><div class="clear"></div></div>
		<?php 
	}
	
	echo '</div>';
	?>

<p style="text-align:center;margin-top:10px">
	<a id="wp_keyword_tool_density_info" href="#"><?php _e('What should density equal?','wp_keyword_tool') ?></a>
<p style="display: none" class="the-tagcloud" id="wp_keyword_tool_density_info_box" style="display: block;">
	<?php _e('The ideal density for a single keyword is','wp_keyword_tool') ?> <a href="http://www.submitedge.com/blog/ideal-keyword-density/">1-2%</a>
</p>
</p>

<script>
jQuery('#wp_keyword_tool_tag_btn').click(function () 
{
    	var searchIDs = jQuery('#wp_keyword_tool_keywords input[type="checkbox"]:checked').map(function()
    	{
          return jQuery(this).val();
        });
        //console.log(searchIDs.get());

        var ss = jQuery(this).val();
        var tagid = "<?php echo $pid; ?>";
         var data = {
            'action': 'tag_form_send',
            'tag_id': tagid,
            'tag_data': searchIDs.get()
        };
        
        
        var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
            	jQuery.ajax({
            		url: ajaxurl,
            		data: data,
            		type: 'POST',
            		success:function(data){
            			var response=JSON.parse(data);
            	        //console.log(response);
            	        location.reload(true);
            		},
            		error: function(errorThrown){
            			//alert(errorThrown);
            		} 
            	});
});

jQuery("#wp_keyword_tool_check").click(function()
{
    jQuery('#wp_keyword_tool_keywords input:checkbox').not(this).prop('checked', this.checked);
});

</script>

<?php
}

/*
 * settings menu
 */
add_action('admin_menu', 'my_keyword_tool_control_menu');

function my_keyword_tool_control_menu() {

	$page_hook_suffix = add_submenu_page( 'options-general.php', __('Keyword Tool','wp_keyword_tool'), 'Keyword tool', 'administrator', 'wp_keyword_tools_settings', 'ch_keword_tool_fn' );
	add_action('admin_print_scripts-' . $page_hook_suffix, 'my_keyword_tool_options_scripts');

}

//require_once 'includes/seo_traffic/options-keyword-tool.php';

function my_keyword_tool_options_scripts(){
	wp_enqueue_script ( 'wp_keyword_tool_options_main', plugins_url ( '/assets/js/options.js', __FILE__ ) );
	wp_enqueue_style ( 'wp-jquery-ui-dialog' );
	wp_enqueue_script ( 'jquery-ui-dialog' );
}	



/**
 * Function for adding header style sheets and js
 */
add_action ( 'admin_print_scripts-' . 'post-new.php', 'my_keyword_tool_admin_scripts' );
add_action ( 'admin_print_scripts-' . 'post.php', 'my_keyword_tool_admin_scripts' );
function my_keyword_tool_admin_scripts() {
	
	wp_enqueue_style ( 'wp-jquery-ui-dialog' );
	wp_enqueue_script ( 'jquery-ui-dialog' );


	//load letters and google source to js

	$wp_keyword_tool_alphabets=get_option('wp_keyword_tool_alphabets','a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z');	

	$letters_arr=explode(',', trim($wp_keyword_tool_alphabets));
	$letters=array_filter($letters_arr);
	$wp_keyword_tool_google = trim( get_option('wp_keyword_tool_google','google.com'));
	
	?> <script type="text/javascript">
			
			var wp_keyword_tool_letters=<?php echo json_encode($letters) ; ?>;
			var wp_keyword_tool_google = '<?php echo ($wp_keyword_tool_google) ; ?>';
			</script>
	<?php 
	
	// jquery main
	wp_enqueue_script ( 'wp_keyword_tool_jquery_main', plugins_url ( '/assets/js/main.js', __FILE__ ) , array() , '1.0.3' );
	
	// jquery gcomplete main
	wp_enqueue_script ( 'wp_keyword_tool_jquery_gcomplete', plugins_url ( '/assets/js/jquery.gcomplete.0.1.2.js', __FILE__ ) );
	
	wp_enqueue_style ( 'wp_keyword_tool-admin-style', plugins_url ( 'assets/css/style.css', __FILE__ ) );
	wp_enqueue_style ( 'wp_keyword_tool-admin-style-gcomplete', plugins_url ( 'assets/css/jquery.gcomplete.default-themes.css', __FILE__ ) );
}
/**
 * custom request for fetch boards
 */
function mych_keyword_tool_parse_request($wp) {
	
	// only process requests with "my-plugin=ajax-handler"
	if (array_key_exists ( 'wp_keyword_tool', $wp->query_vars )) {
		
		if ($wp->query_vars ['wp_keyword_tool'] == 'ajax') {
			
			require_once ('includes/seo_traffic/wp_keyword_ajax.php');
			exit ();
		}
	}
}
add_action ( 'parse_request', 'mych_keyword_tool_parse_request' );
function my_keyword_tool_query_vars($vars) {
	$vars [] = 'wp_keyword_tool';
	return $vars;
}
add_filter ( 'query_vars', 'my_keyword_tool_query_vars' );


/* ------------------------------------------------------------------------*
 * Function Selected
* ------------------------------------------------------------------------*/
if(! function_exists('opt_selected')){
	function opt_selected($src,$val){
		if (trim($src)==trim($val)) echo ' selected="selected" ';
	}
}

function my_ajax_tag_form_send() 
{
    $tag_post_data = $_POST['tag_data'];
    $tag_post_id = $_POST['tag_id'];
    foreach($tag_post_data as $tag_post_datas)
    {
        wp_set_post_tags($tag_post_id, $tag_post_datas , true );
    }
}
add_action( 'wp_ajax_tag_form_send', 'my_ajax_tag_form_send' );
add_action( 'wp_ajax_nopriv_tag_form_send', 'my_ajax_tag_form_send' );

function my_pagination_ch($pages = '', $paged=1 , $range = 4)
{
    $showitems = ($range * 2)+1;
 
    //global $paged;
    if(empty($paged)) $paged = 1;
 
    if($pages == '')
    {
        global $wp_query;
        $pages = $wp_query->max_num_pages;
        if(!$pages)
        {
            $pages = 1;
        }
    }
 
    if(1 != $pages)
    {
        echo "<div class=\"pagination\"><span>Page ".$paged." of ".$pages."</span>";
        if($paged > 2 && $paged > $range+1 && $showitems < $pages) echo "<a href='".get_pagenum_link(1)."'>&laquo; First</a>";
        if($paged > 1 && $showitems < $pages) echo "<a href='".get_pagenum_link($paged - 1)."'>&lsaquo; Previous</a>";
 
        for ($i=1; $i <= $pages; $i++)
        {
            if (1 != $pages &&( !($i >= $paged+$range+1 || $i <= $paged-$range-1) || $pages <= $showitems ))
            {
                echo ($paged == $i)? "<span class=\"current\">".$i."</span>":"<a href='".get_pagenum_link($i)."' class=\"inactive\">".$i."</a>";
            }
        }
 
        if ($paged < $pages && $showitems < $pages) echo "<a href=\"".get_pagenum_link($paged + 1)."\">Next &rsaquo;</a>";
        if ($paged < $pages-1 &&  $paged+$range-1 < $pages && $showitems < $pages) echo "<a href='".get_pagenum_link($pages)."'>Last &raquo;</a>";
        echo "</div>\n";
    }
}



require 'get_pdf.php';

// Our custom post type function
function create_posttype_channels() {
  
 $theme_labels = array(
            'name'                  => _x( 'View Channels', 'Post Type General Name', 'mych_channel' ),
            'singular_name'         => _x( 'View Channel', 'Post Type Singular Name', 'mych_channel' ),
            'menu_name'             => __( 'View Channels', 'mych_channel' ),
            'name_admin_bar'        => __( 'Post Type', 'mych_channel' ),
            'archives'              => __( 'View Channel Archives', 'mych_channel' ),
            'attributes'            => __( 'View Channel Attributes', 'mych_channel' ),
            'parent_item_colon'     => __( 'Parent View Channel:', 'mych_channel' ),
            'all_items'             => __( 'All View Channels', 'mych_channel' ),
            'add_new_item'          => __( 'Add New View Channel', 'mych_channel' ),
            'add_new'               => __( 'Add New', 'mych_channel' ),
            'new_item'              => __( 'New View Channel', 'mych_channel' ),
            'edit_item'             => __( 'Edit View Channel', 'mych_channel' ),
            'update_item'           => __( 'Update View Channel', 'mych_channel' ),
            'view_item'             => __( 'View View Channel', 'mych_channel' ),
            'view_items'            => __( 'View View Channel', 'mych_channel' ),
            'search_items'          => __( 'Search View Channel', 'mych_channel' ),
            'not_found'             => __( 'Not found', 'mych_channel' ),
            'not_found_in_trash'    => __( 'Not found in Trash', 'mych_channel' ),
            'featured_image'        => __( 'Featured Image', 'mych_channel' ),
            'set_featured_image'    => __( 'Set featured image', 'mych_channel' ),
            'remove_featured_image' => __( 'Remove featured image', 'mych_channel' ),
            'use_featured_image'    => __( 'Use as featured image', 'mych_channel' ),
            'insert_into_item'      => __( 'Insert into View Channel', 'mych_channel' ),
            'uploaded_to_this_item' => __( 'Uploaded to this View Channel', 'mych_channel' ),
            'items_list'            => __( 'Themes list', 'mych_channel' ),
            'items_list_navigation' => __( 'Themes list navigation', 'mych_channel' ),
            'filter_items_list'     => __( 'Filter themes list', 'mych_channel' ),
        );


		register_post_type( 'mych-ytube-channels',
    // CPT Options
        array(
            'labels' => $theme_labels,
            'public' => false,
			'publicly_queryable' => true,
			'show_ui' => true,
			'supports' => array( 'title', 'thumbnail' , 'excerpt' ),
            'has_archive' => false,
            'rewrite' => false,
            'show_in_rest' => true,
  
        )
    );
}

add_action( 'init', 'create_posttype_channels', 0 );

add_action( 'admin_menu', 'so_59866103_remove_menu_items', 999 );
function so_59866103_remove_menu_items(){
    remove_menu_page( 'edit.php?post_type=mych-ytube-channels' );
}


function custom_columns( $columns ) {
    $columns = array(
        'cb' => '<input type="checkbox" />',
        'featured_image' => 'Image',
        'title' => 'Title'
     );
    return $columns;
}
add_filter('manage_mych-ytube-channels_posts_columns' , 'custom_columns');

function custom_columns_data( $column, $post_id ) {
    switch ( $column ) {
    case 'featured_image':
        the_post_thumbnail( 'thumbnail' );
        break;
    }
}
add_action( 'manage_mych-ytube-channels_posts_custom_column' , 'custom_columns_data', 10, 2 ); 

// Add the custom columns to the book post type:
add_filter( 'manage_mych-ytube-channels_posts_columns', 'set_custom_edit_book_columns' );
function set_custom_edit_book_columns($columns) {
	unset($column['date']);

    $columns['site'] = __( 'Site', 'your_text_domain' );
    $columns['type'] = __( 'Type', 'your_text_domain' );
	$columns['auto_sync'] = __( 'Auto Sync', 'your_text_domain' );	 
	$columns['base_category'] = __( 'Ezine Category', 'your_text_domain' );	 
	$columns['post_afcategory'] = __( 'Category', 'your_text_domain' );	 

    return $columns;
}

// Add the data to the custom columns for the book post type:
add_action( 'manage_mych-ytube-channels_posts_custom_column' , 'custom_book_column', 10, 2 );
function custom_book_column( $column, $post_id ) {
    switch ( $column ) {

        case 'site' :
			echo "YouTube";
            break;
        case 'type' :
			echo "YouTube Channel";
            break;
        case 'auto_sync' :		
			$postmeta_autosync = get_post_meta( $post_id, 'mych_channels_autopost', true );
			if(!empty($postmeta_autosync) && $postmeta_autosync == 'on')
			{
				echo "on";
			}
			else
			{
				echo "off";
			}
            break;
        case 'base_category' :		
			$postmeta_category = get_post_meta( $post_id, 'mych_channels_catid', true );
			if(!empty($postmeta_category))
			{
				echo $postmeta_category;
			}
			else
			{
				echo "No Category Selected";
			}
            break;
        case 'post_afcategory' :		
			$postmeta_category = get_post_meta( $post_id, 'mych_post_cat_id', true );
			if(!empty($postmeta_category))
			{
				echo get_cat_name( $category_id = $postmeta_category );
			}
			else
			{
				echo "";
			}
            break;
    }
}

add_filter( 'post_row_actions', 'remove_row_actions', 10, 2 );

function remove_row_actions( $actions, $post )
{
    if ($post->post_type == "mych-ytube-channels") {
        unset( $actions['view'] );
    }
    return $actions;
}

function hide_publishing_actions_channels()
{
	$my_post_type = 'mych-ytube-channels';
	global $post;
    if($post->post_type == $my_post_type)
    {
	  echo '
		 <style type="text/css">
			#postbox-container-1 #submitdiv
			{
				 display:none;
			}
		 </style>
	   ';	   
	 }
}
add_action('admin_head-post.php', 'hide_publishing_actions_channels');
add_action('admin_head-post-new.php', 'hide_publishing_actions_channels');

add_action( 'add_meta_boxes', 'my_add_meta_boxes_channels' );
function my_add_meta_boxes_channels() {
    remove_meta_box( 'slugdiv', 'mych-ytube-channels', 'normal' );
}

if ( !class_exists("mych__Chatgpt_Ai_Content_Generator") ) {
    final class mych__Chatgpt_Ai_Content_Generator {

        // Define plugin properties
        private $version = '1.1.0';
        private $plugin_name = 'caacg';
        private static $instance;

		public static function getInstance() {
			if ( ! isset( self::$instance ) && ! ( self::$instance instanceof mych__Chatgpt_Ai_Content_Generator ) ) {
				self::$instance = new mych__Chatgpt_Ai_Content_Generator;	
				self::$instance->includes();
			}

			return self::$instance;
		}

        public function includes(){
            //admin menu page class
            require plugin_dir_path( __FILE__ ) . 'admin/classes/cicg-class-menu-page.php';
            //General settings class
             require plugin_dir_path( __FILE__ ) . 'admin/classes/cicg-class-general-settings.php';
            //admin general settings display
            require plugin_dir_path( __FILE__ ) . 'admin/partials/cicg-general-settings-display.php';
            //admin schedule settings display
            require plugin_dir_path( __FILE__ ) . 'admin/partials/cicg-post-schedule-display.php';


            //admin deshboard display
            require plugin_dir_path( __FILE__ ) . 'admin/partials/cicg-admin-deshboard.php';
            //metabox class
            require plugin_dir_path( __FILE__ ) . 'admin/classes/cicg-class-metabox.php';
            //metabox display
             require plugin_dir_path( __FILE__ ) . 'admin/partials/cicg-metabox-display.php';
            //admin scripts
            require plugin_dir_path( __FILE__ ) . 'admin/classes/cicg-class-scripts.php';
            //Rest API class
            require plugin_dir_path( __FILE__ ) . 'admin/classes/cicg-class-rest-api.php';
            //shedule Setting class
            require plugin_dir_path( __FILE__ ) . 'admin/classes/cicg-class-schedule-settings.php';
            //chatgpt deshboard shorcode 
            require plugin_dir_path( __FILE__ ) . 'admin/classes/cicg-class-chatgpt-deshboard-shortcode.php';
            //shedule Setting class
            require plugin_dir_path( __FILE__ ) . 'includes/classes/cicg-class-enqueue-scripts.php';

            require plugin_dir_path( __FILE__ ) . 'admin/partials/cicg-keyword-research.php';

        }
        // Constructor function
        public function __construct(){
             // Load plugin text domain
            add_action( 'plugins_loaded', array( $this, 'load_textdomain' ) );
        }
        // Load plugin text domain
        public function load_textdomain() {
            load_plugin_textdomain( 'caacg', false, dirname( plugin_basename( __FILE__ ) ) . '/languages' );
        }
     
    }
}
function mych_chatgpt_ai_content_generator() {
	return mych__Chatgpt_Ai_Content_Generator::getInstance();
}


add_action( 'plugins_loaded', 'mych_chatgpt_ai_content_generator' );

// Add a custom meta box for the custom-tags-input
function mych_add_custom_tags_meta_box() {
	$pro_licence_type = get_option('my_pro_licence_type');
	if($pro_licence_type == "elite")
	{

    add_meta_box(
        'custom-tags-meta-box',
        'Custom Tags From CHATGPT',
        'render_custom_tags_meta_box',
        'post', // You can specify other post types here like 'page'
        'normal',
        'default'
    );
  }
}
add_action('add_meta_boxes', 'mych_add_custom_tags_meta_box');

// Render the custom input field in the meta box
function render_custom_tags_meta_box($post) {
    // Retrieve the current custom tags value if it exists
    $custom_tags = get_post_meta($post->ID, 'custom_tags_field', true);

    // Output the input field
    ?>
    <label for="custom-tags-input">Custom Tags :</label>
    <input type="text" id="custom-tags-input" name="custom_tags_input" value="<?php echo esc_attr($custom_tags); ?>" style="width: 100%;" />
    <?php
}

// Save the custom input field value
function mych_save_custom_tags_field($post_id) {

    // Check if this is a valid post type (e.g., 'post' or 'page')
    if (get_post_type($post_id) != 'post') {
        return;
    }
	if(isset($_POST['custom_tags_input']) && !empty($_POST['custom_tags_input']) ) {
    // Get the custom tags from the input field
    $custom_tags = sanitize_text_field($_POST['custom_tags_input']);

    // Convert the custom tags into an array (assuming they are comma-separated)
    $custom_tags_array = explode(',', $custom_tags);

    // Remove leading and trailing spaces from each tag
    $custom_tags_array = array_map('trim', $custom_tags_array);

    // Update the post's tags with the custom tags
    wp_set_post_tags($post_id, $custom_tags_array);
	}
}
add_action('save_post', 'mych_save_custom_tags_field');





function mycp_isTitleSimilar($titleApi, $existing_titles, $similarity_threshold) {
    foreach ($existing_titles as $existing_title) {
        if(!empty($existing_title)){
        similar_text($titleApi, $existing_title, $similarity);
           // echo "Similarity between '$titleApi' and '$existing_title': $similarity%<br><br><br>";

        if ($similarity >= $similarity_threshold) {
            return true; // Title is too similar, needs to be regenerated
        }
    }
    }
    // If no similar titles are found in the entire array
    return false;
}
function mycp_get_last_10_titles() {
    global $wpdb;
   // $last_10_titles = $wpdb->get_col("SELECT post_title FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish' ORDER BY post_date DESC LIMIT 10");
   $last_10_titles = $wpdb->get_col("SELECT post_title FROM $wpdb->posts WHERE post_type = 'post' AND post_status IN ('publish', 'draft') ORDER BY post_date DESC LIMIT 12");
    return $last_10_titles;
}

function chatgpt_generate_title_spin_gpt4o($postTitle, $contentLanguage, $maxTokens, $temperature) {
    $api_key = get_option('cicg_chatgpt_api_key');
    $api_endpoint = 'https://api.openai.com/v1/chat/completions';

    // Adjust maxTokens to ensure it does not exceed the output token limit
    $max_output_tokens = min($maxTokens, 4096); // Ensure maxTokens does not exceed 4,096 for completion tokens

    // Prepare the data for the request
    $data = array(
        'model' => 'gpt-4o',
        'messages' => array(
            array(
                'role' => 'system',
                'content' => 'You are a helpful assistant that generates content titles.',
            ),
            array(
                'role' => 'user',
                'content' => "Please generate a SEO-friendly title for a blog post about \"$postTitle\" without including 'in $contentLanguage' and the article should be written in $contentLanguage language.",
            ),
        ),
        'max_tokens' => $max_output_tokens, 
        'temperature' => floatval($temperature),
    );

    // Send the request to the GPT-4o API
    $response = wp_safe_remote_post($api_endpoint, array(
        'body' => json_encode($data),
        'headers' => array(
            'Content-Type' => 'application/json',
            'Authorization' => 'Bearer ' . $api_key,
        ),
    ));
    
    
    // Handle the response
    if (is_wp_error($response)) {
        return null; // Handle the error
    } else {
        $body = wp_remote_retrieve_body($response);
        $titleApi = json_decode($body)->choices[0]->message->content;
        return $titleApi;
    }
}



function chatgpt_generate_title_spin_gpt4($postTitle, $contentLanguage, $maxTokens, $temperature) {
    $api_key = get_option('cicg_chatgpt_api_key');
    $api_endpoint = 'https://api.openai.com/v1/chat/completions';

    // Break down the post title into smaller chunks for better processing
    $chunks = str_split($postTitle, 500); // Split into chunks of 500 characters (adjust as needed)

    // Initialize the messages array
    $messages = array();

    // Add a system message
    $messages[] = array(
        'role' => 'system',
        'content' => 'You are a helpful assistant that generates content titles.',
    );

    // Add user messages with chunks of the post title
    foreach ($chunks as $chunk) {
        $messages[] = array(
            'role' => 'user',
            'content' => "Please generate a SEO-friendly title for a blog post about $chunk without including 'in $contentLanguage' and the article should be written in $contentLanguage language.",
        );
    }

    // Prepare the data for the request
    $data = array(
        'model' => 'gpt-4',
        'messages' => $messages,
        'max_tokens' => $maxTokens,
        'temperature' => $temperature,
    );

    // Send the request to the ChatGPT API
    $response = wp_safe_remote_post($api_endpoint, array(
        'body' => json_encode($data),
        'headers' => array(
            'Content-Type' => 'application/json',
            'Authorization' => 'Bearer ' . $api_key,
        ),
    ));
    
    // Handle the response
    if (is_wp_error($response)) {
        return null; // Handle the error
    } else {
        $body = wp_remote_retrieve_body($response);
        $titleApi = json_decode($body)->choices[0]->message->content;
        return $titleApi;
    }
}

function chatgpt_generate_title_spin_gpt3($postTitle, $contentLanguage, $maxTokens, $temperature) {
    $api_key = get_option('cicg_chatgpt_api_key');
    $api_endpoint = 'https://api.openai.com/v1/chat/completions';

    // Break down the post title into smaller chunks for better processing
    $chunks = str_split($postTitle, 500); // Split into chunks of 500 characters (adjust as needed)

    // Initialize the messages array
    $messages = array();

    // Add a system message
    $messages[] = array(
        'role' => 'system',
        'content' => 'You are a helpful assistant that generates content titles.',
    );

    // Add user messages with chunks of the post title
    foreach ($chunks as $chunk) {
        $messages[] = array(
            'role' => 'user',
            'content' => "Please generate a SEO-friendly title for a blog post about $chunk without including 'in $contentLanguage' and the article should be written in $contentLanguage language.",
        );
    }

    // Prepare the data for the request
    $data = array(
        'model' => 'gpt-3.5-turbo',
        'messages' => $messages,
        'max_tokens' => $maxTokens,
        'temperature' => $temperature,
    );

    // Send the request to the ChatGPT API
    $response = wp_safe_remote_post($api_endpoint, array(
        'body' => json_encode($data),
        'headers' => array(
            'Content-Type' => 'application/json',
            'Authorization' => 'Bearer ' . $api_key,
        ),
    ));
    
    // Handle the response
    if (is_wp_error($response)) {
        return null; // Handle the error
    } else {
        $body = wp_remote_retrieve_body($response);
        $titleApi = json_decode($body)->choices[0]->message->content;
        return $titleApi;
    }
}


function chatgpt_generate_title_gpt4($postTitle, $contentLanguage, $maxTokens, $temperature) {
    $api_key = get_option('cicg_chatgpt_api_key');
    $api_endpoint = 'https://api.openai.com/v1/chat/completions';

	$data = array(
		'model' => 'gpt-4',
		'messages' => array(
			array(
				'role' => 'system',
				'content' => 'You are a helpful assistant that generates content titles.',
			),
			array(
				'role' => 'user',
				'content' => "Please generate a SEO-friendly title for a blog post about $postTitle without including 'in $contentLanguage' and the article should be written in $contentLanguage language.",
			),
		),
		'max_tokens' => $maxTokens,
		'temperature' => $temperature,
	);

    $response = wp_safe_remote_post($api_endpoint, array(
        'body' => json_encode($data),
        'headers' => array(
            'Content-Type' => 'application/json',
            'Authorization' => 'Bearer ' . $api_key,
        ),
	));
	

    if (is_wp_error($response)) {
        return null; // Handle the error
    } else {
        $body = wp_remote_retrieve_body($response);
        $titleApi = json_decode($body)->choices[0]->message->content;
         $existing_titles = mycp_get_last_10_titles(); // You need to implement this function to get the last 10 titles from your database
        $similarity_threshold = 60;
      if (mycp_isTitleSimilar($titleApi, $existing_titles, $similarity_threshold)) {
          return chatgpt_generate_title_gpt4($postTitle, $contentLanguage, $maxTokens, $temperature);
      } else {
          return $titleApi;
      }       
    }
}

function chatgpt_generate_title_gpt4o($postTitle, $contentLanguage, $maxTokens, $temperature) {
    $api_key = get_option('cicg_chatgpt_api_key');
    $api_endpoint = 'https://api.openai.com/v1/chat/completions';

    $data = array(
        'model' => 'gpt-4o', // Update to GPT-4o model
        'messages' => array(
            array(
                'role' => 'system',
                'content' => 'You are a helpful assistant that generates content titles.',
            ),
            array(
                'role' => 'user',
                'content' => "Please generate a SEO-friendly title for a blog post about $postTitle without including 'in $contentLanguage' and the article should be written in $contentLanguage language.",
            ),
        ),
        'max_tokens' => 4000, // Ensure maxTokens does not exceed 128,000
        'temperature' => floatval($temperature), // Use floatval instead of intval
    );

    $response = wp_safe_remote_post($api_endpoint, array(
        'body' => json_encode($data),
        'headers' => array(
            'Content-Type' => 'application/json',
            'Authorization' => 'Bearer ' . $api_key,
        ),
    ));

    if (is_wp_error($response)) {
        return null; // Handle the error
    } else {
        $body = wp_remote_retrieve_body($response);
        $titleApi = json_decode($body)->choices[0]->message->content;

        $existing_titles = mycp_get_last_10_titles(); // You need to implement this function to get the last 10 titles from your database
        $similarity_threshold = 60;
        
        if (mycp_isTitleSimilar($titleApi, $existing_titles, $similarity_threshold)) {
            return chatgpt_generate_title_gpt4o($postTitle, $contentLanguage, $maxTokens, $temperature); // Recursive call to generate a new title
        } else {
            return $titleApi;
        }
    }
}




 function chatgpt_generate_tags($postTitle, $contentLanguage, $maxTokens, $temperature) {
	// Similar to the title generation function with appropriate content
	// Adjust the message content to request tags.

      
	$api_key = get_option('cicg_chatgpt_api_key');
	$api_endpoint = 'https://api.openai.com/v1/chat/completions';

	$data = array(
		'model' => 'gpt-3.5-turbo',
		'messages' => array(
			array(
				'role' => 'system',
				'content' => 'You are a helpful assistant that generates product tags.',
			),
			array(
				'role' => 'user',
				'content' => "Please generate SEO-friendly tags for a blog post about $postTitle and the article should be written in $contentLanguage language.",
			),
		),
		'max_tokens' => 4000,
		'temperature' => $temperature,
	);
	

	$response = wp_safe_remote_post($api_endpoint, array(
		'body' => json_encode($data),
		'headers' => array(
			'Content-Type' => 'application/json',
			'Authorization' => 'Bearer ' . $api_key,
		),
	));



	if (is_wp_error($response)) {
	        $error_message = is_wp_error($response) ? $response->get_error_message() : 'Unexpected response code';
	//	return null; // Handle the error

	} else {
		$body = wp_remote_retrieve_body($response);
		$responseData = json_decode($body);


				if (isset($responseData->choices) && count($responseData->choices) > 0) {
					$postTagsApi = $responseData->choices[0]->message->content;
			
					if (strpos($postTagsApi, ',') !== false) {
						$postTags = $postTagsApi;
					} else {
						$postTagsArray = preg_split('/\d+\.\s/', $postTagsApi);
						$postTags = implode(', ', array_filter($postTagsArray));
					}
					$postTags = array_slice(explode(', ', $postTags), 0, 5);
					// Limit the number of tags to 5
					//$postTags = implode(', ', array_slice(explode(', ', $postTags), 0, 5));
					return $postTags;
				} else {
					// Handle the case where there are no choices in the response
					return null; // Handle the error
				}
		}
}


function chatgpt_generate_tags_gpt4($postTitle, $contentLanguage, $maxTokens, $temperature) {
    // Similar to the title generation function with appropriate content
    // Adjust the message content to request tags.
      
    $api_key = get_option('cicg_chatgpt_api_key');
    $api_endpoint = 'https://api.openai.com/v1/chat/completions'; 
    
	$maxTokens = intval($maxTokens);
   $temperature = floatval($temperature);

    $data = array(
        'model' => 'gpt-4',
        'messages' => array(
            array(
                'role' => 'system',
                'content' => 'You are a helpful assistant that generates product reviews.',
            ),
            array(
                'role' => 'user',
                'content' => "Generate a review for a product.",
            ),
            array(
                'role' => 'user',
                'content' => "Product URL: https://konigle.com/",
            ),
        ),
        'max_tokens' => $maxTokens,
        'temperature' => $temperature,
    );
    
    
    
     $options = array(
        'body' => json_encode($data),
        'headers' => array(
            'Content-Type' => 'application/json',
            'Authorization' => 'Bearer ' . $api_key,
        ),
        'http' => array(
            'timeout' => 70, // Set the timeout value in seconds
        ),
    );

$response = wp_safe_remote_post($api_endpoint, $options);
  
   $response_code = wp_remote_retrieve_response_code($response);
$response_message = wp_remote_retrieve_response_message($response);

if ($response_code !== 200) {
    // Handle the error, log details, or display a meaningful message.
    echo "Error: $response_message (Code: $response_code)";
}
	 
    	echo "<pre>";
	print_r($response_code);
	echo "</pre>";

	/*$response = wp_safe_remote_post($api_endpoint, array(
		'body' => json_encode($data),
		'headers' => array(
			'Content-Type' => 'application/json',
			'Authorization' => 'Bearer ' . $api_key,
		),
	));*/
	
	echo "<pre>";
	print_r($response);
	echo "</pre>";
	die;

    if (is_wp_error($response)) {
        return null; // Handle the error
    } else {
        $body = wp_remote_retrieve_body($response);
        $responseData = json_decode($body);

        if (isset($responseData->choices) && count($responseData->choices) > 0) {
            $postTagsApi = $responseData->choices[0]->message->content;
    
            if (strpos($postTagsApi, ',') !== false) {
                $postTags = $postTagsApi;
            } else {
                $postTagsArray = preg_split('/\d+\.\s/', $postTagsApi);
                $postTags = implode(', ', array_filter($postTagsArray));
            }
            $postTags = array_slice(explode(', ', $postTags), 0, 5); // Limit the number of tags to 5
            return $postTags;
        } else {
            // Handle the case where there are no choices in the response
            return null; // Handle the error
        }
    }
}



//$content = chatgpt_generate_description('chatgpt prompts for writing',300,'formal','formal','en','on','on',4000,1);


 function chatgpt_generate_description($postTitle, $contentLength, $writingStyle, $writingTone, $contentLanguage, $cicggeneratefaq, $cicggenerateconc, $maxTokens, $temperature) {
		// Generate description
		$faq = $cicggeneratefaq;
		$conclusion = $cicggenerateconc;
	$maxTokens = intval($maxTokens);
		$temperature = intval($temperature);

		$api_key = get_option('cicg_chatgpt_api_key');
		$api_endpoint = 'https://api.openai.com/v1/chat/completions';
	
		$description_data = array(
			'model' => 'gpt-3.5-turbo',
			'messages' => array(
				array(
					'role' => 'system',
					'content' => 'You are a helpful assistant that generates product descriptions, conclusions and FAQs.',
				),
				array(
					'role' => 'user',
					'content' => 'Generate a product description for ' .  $postTitle . " The article should be " . $contentLength . " words. The article should be written in a " . $writingStyle . " style. The tone should be " . $writingTone . ". The article should be written in " . $contentLanguage . " language. Do not include the phrase 'Product Description' or any similar title.",
				),
				array(
					'role' => 'assistant',
                'content' => 'Generate product description, FAQ and conclusion for ' . $postTitle . '.',
				),
			),
			'max_tokens' => $maxTokens,
			'temperature' => $temperature,
		);
	
		if ($faq=='on' && $conclusion=='on') {
			// If both FAQ and conclusion are selected
			$description_data['messages'][0]['content'] = 'You are a helpful assistant that generates product descriptions, conclusions, and FAQs.';
		} elseif ($faq=='on' && $conclusion=='off') {
			// If only FAQ is selected
			$description_data['messages'][0]['content'] = 'You are a helpful assistant that generates product descriptions and FAQs.';
		} elseif ($faq=='off' && $conclusion=='off') {
			// If neither FAQ nor conclusion is selected
			$description_data['messages'][0]['content'] = 'You are a helpful assistant that generates product descriptions without conclusion';
			$description_data['messages'][2]['content'] = 'Do not include a conclusion.';
		} else {
			// If only conclusion is selected
			$description_data['messages'][0]['content'] = 'You are a helpful assistant that generates product descriptions with conclusion';
			$description_data['messages'][2]['content'] = '';
		}
	
		$response = wp_safe_remote_post($api_endpoint, array(
			'body' => json_encode($description_data),
			'headers' => array(
				'Content-Type' => 'application/json',
				'Authorization' => 'Bearer ' . $api_key,
			),
			'timeout' => 160, // Set the timeout to 30 seconds
		));
		
    // Log the request and response details
    $log_message = "Request URL: $api_endpoint\n";
    $log_message .= "Request Data: " . json_encode($description_data) . "\n";
    $log_message .= "Response: " . print_r($response, true) . "\n\n";
    error_log($log_message, 3, WPCH_PLUGIN_DIR . '/chatgt3.log');
    	
		if (is_wp_error($response)) {
			// Handle the error
			echo 'Error: ' . $response->get_error_message();
		} else {
			$body = wp_remote_retrieve_body($response);
			$responseData = json_decode($body);

	
			if (isset($responseData->choices) && count($responseData->choices) > 0) {
				$postDescriptionApi = $responseData->choices[0]->message->content;

				$sections = preg_split("/\n\n/", $postDescriptionApi);
	
				// Iterate through the sections and remove word counts and colons
				foreach ($sections as $key => $section) {
					$sections[$key] = preg_replace("/\(approx\.\s+\d+\s+words\):\s*/", '', $section);
				}
	
				// Join the sections back together
				$cleanedDescription = implode("\n\n", $sections);
				$jsonTextRemove = preg_replace("/^\s+/", '', $cleanedDescription);
				$htmlString = str_replace("\n", "<br>", $jsonTextRemove);
	
				// Assuming you have the HTML string in the 'htmlString' variable
				$conclusionIndex = strpos($htmlString, "Conclusion:");
				$faqIndex = strpos($htmlString, "FAQ:");
	
				// Initialize variables for each section
				$mainContent = "";
				$conclusion = "";
				$faq = "";
	
		  
	
				// Extract content based on marker positions
				if ($conclusionIndex !== false && $faqIndex !== false) {
					// If both "Conclusion:" and "FAQ:" are present
					if ($conclusionIndex < $faqIndex) {
						// If "Conclusion:" appears before "FAQ:", extract accordingly
						$mainContent = trim(substr($htmlString, 0, $conclusionIndex));
						$conclusion = trim(substr($htmlString, $conclusionIndex, $faqIndex - $conclusionIndex));
						$faq = trim(substr($htmlString, $faqIndex));
					} else {
						// If "FAQ:" appears before "Conclusion:", extract accordingly
						$mainContent = trim(substr($htmlString, 0, $faqIndex));
						$faq = trim(substr($htmlString, $faqIndex, $conclusionIndex - $faqIndex));
						$conclusion = trim(substr($htmlString, $conclusionIndex));
					}
				} elseif ($conclusionIndex !== false) {
					// Only "Conclusion:" is present
					$mainContent = trim(substr($htmlString, 0, $conclusionIndex));
					$conclusion = trim(substr($htmlString, $conclusionIndex));
				} elseif ($faqIndex !== false) {
					// Only "FAQ:" is present
					$mainContent = trim(substr($htmlString, 0, $faqIndex));
					$faq = trim(substr($htmlString, $faqIndex));
				} else {
					// Neither "Conclusion:" nor "FAQ:" found, consider the whole content as main content
					$mainContent = trim($htmlString);
				}
	
				// Now you have the main content, conclusion, and faq sections
				$formattedMainContent = removeHtmlLineBreaks($mainContent);
				$formattedConclusion = removeHtmlLineBreaks($conclusion);
				$formattedFaq = removeHtmlLineBreaks($faq);
			
				$finalContent = "
				$formattedMainContent
			
				$formattedFaq
			
				$formattedConclusion
				";

				return $finalContent;
			
				// Set the content in your Gutenberg editor
	
			} else {
				// Handle the case where there are no choices in the response
				return null;
			}
		}
	


}

function chatgpt_generate_description_gpt4($postTitle, $contentLength, $writingStyle, $writingTone, $contentLanguage, $cicggeneratefaq, $cicggenerateconc, $maxTokens, $temperature) {
	// Generate description
	$faq = $cicggeneratefaq;
	$conclusion = $cicggenerateconc;
    $maxTokens = intval($maxTokens);
	$temperature = intval($temperature);

	$api_key = get_option('cicg_chatgpt_api_key');
    $api_endpoint = 'https://api.openai.com/v1/chat/completions'; 

    $description_data = array(
        'model' => 'gpt-4',
        'messages' => array(
            array(
                'role' => 'system',
                'content' => 'You are a helpful assistant that generates product descriptions, conclusions and FAQs.',
            ),
            array(
                'role' => 'user',
                'content' => 'Generate a product description for ' .  $postTitle . " The article should be " . $contentLength . " words. The article should be written in a " . $writingStyle . " style. The tone should be " . $writingTone . ". The article should be written in " . $contentLanguage . " language. Do not include the phrase 'Product Description' or any similar title.",
            ),
				array(
					'role' => 'assistant',
                'content' => 'Generate product description, FAQ and conclusion for ' . $postTitle . '.',
				),            
        ),
        'max_tokens' => $maxTokens,
        'temperature' => $temperature,
    );



	if ($faq=='on' && $conclusion=='on') {
		// If both FAQ and conclusion are selected
		$description_data['messages'][0]['content'] = 'You are a helpful assistant that generates product descriptions, conclusions, and FAQs.';
	} elseif ($faq=='on' && $conclusion=='off') {
		// If only FAQ is selected
		$description_data['messages'][0]['content'] = 'You are a helpful assistant that generates product descriptions and FAQs.';
	} elseif ($faq=='off' && $conclusion=='off') {
		// If neither FAQ nor conclusion is selected
		$description_data['messages'][0]['content'] = 'You are a helpful assistant that generates product descriptions without conclusion';
		$description_data['messages'][2]['content'] = 'Do not include a conclusion.';
	} else {
		// If only conclusion is selected
		$description_data['messages'][0]['content'] = 'You are a helpful assistant that generates product descriptions with conclusion';
		$description_data['messages'][2]['content'] = '';
	}

	$response = wp_safe_remote_post($api_endpoint, array(
		'body' => json_encode($description_data),
		'headers' => array(
			'Content-Type' => 'application/json',
			'Authorization' => 'Bearer ' . $api_key,
		),
		'timeout' => 160, // Set the timeout to 30 seconds
	));
	
// Log the request and response details
$log_message = "Request URL: $api_endpoint\n";
$log_message .= "Request Data: " . json_encode($description_data) . "\n";
$log_message .= "Response: " . print_r($response, true) . "\n\n";
error_log($log_message, 3, WPCH_PLUGIN_DIR . '/chatgt4.log');

	if (is_wp_error($response)) {
		// Handle the error
		echo 'Error: ' . $response->get_error_message();
	} else {
		$body = wp_remote_retrieve_body($response);
		$responseData = json_decode($body);
		

		if (isset($responseData->choices) && count($responseData->choices) > 0) {
			$postDescriptionApi = $responseData->choices[0]->message->content;
           //$postDescriptionApi = str_replace("Product Description:", "", $postDescriptionApi);
    //error_log($postDescriptionApi, 3, WPCH_PLUGIN_DIR . '/test.log');


			$sections = preg_split("/\n\n/", $postDescriptionApi);

			// Iterate through the sections and remove word counts and colons
			foreach ($sections as $key => $section) {
				$sections[$key] = preg_replace("/\(approx\.\s+\d+\s+words\):\s*/", '', $section);
			}

			// Join the sections back together
			$cleanedDescription = implode("\n\n", $sections);
			$jsonTextRemove = preg_replace("/^\s+/", '', $cleanedDescription);
			$htmlString = str_replace("\n", "<br>", $jsonTextRemove);

			// Assuming you have the HTML string in the 'htmlString' variable
			$conclusionIndex = strpos($htmlString, "Conclusion:");
			$faqIndex = strpos($htmlString, "FAQ:");

			// Initialize variables for each section
			$mainContent = "";
			$conclusion = "";
			$faq = "";

	  

			// Extract content based on marker positions
			if ($conclusionIndex !== false && $faqIndex !== false) {
				// If both "Conclusion:" and "FAQ:" are present
				if ($conclusionIndex < $faqIndex) {
					// If "Conclusion:" appears before "FAQ:", extract accordingly
					$mainContent = trim(substr($htmlString, 0, $conclusionIndex));
					$conclusion = trim(substr($htmlString, $conclusionIndex, $faqIndex - $conclusionIndex));
					$faq = trim(substr($htmlString, $faqIndex));
				} else {
					// If "FAQ:" appears before "Conclusion:", extract accordingly
					$mainContent = trim(substr($htmlString, 0, $faqIndex));
					$faq = trim(substr($htmlString, $faqIndex, $conclusionIndex - $faqIndex));
					$conclusion = trim(substr($htmlString, $conclusionIndex));
				}
			} elseif ($conclusionIndex !== false) {
				// Only "Conclusion:" is present
				$mainContent = trim(substr($htmlString, 0, $conclusionIndex));
				$conclusion = trim(substr($htmlString, $conclusionIndex));
			} elseif ($faqIndex !== false) {
				// Only "FAQ:" is present
				$mainContent = trim(substr($htmlString, 0, $faqIndex));
				$faq = trim(substr($htmlString, $faqIndex));
			} else {
				// Neither "Conclusion:" nor "FAQ:" found, consider the whole content as main content
				$mainContent = trim($htmlString);
			}

			// Now you have the main content, conclusion, and faq sections
			$formattedMainContent = removeHtmlLineBreaks($mainContent);
			$formattedConclusion = removeHtmlLineBreaks($conclusion);
			$formattedFaq = removeHtmlLineBreaks($faq);
		
			$finalContent = "
			$formattedMainContent
		
			$formattedFaq
		
			$formattedConclusion
			";

			return $finalContent;
		
			// Set the content in your Gutenberg editor

		} else {
			// Handle the case where there are no choices in the response
			return null;
		}
	}



}
   
function chatgpt_generate_description_gpt4o($postTitle, $contentLength, $writingStyle, $writingTone, $contentLanguage, $cicggeneratefaq, $cicggenerateconc, $maxTokens, $temperature) {
    // Constants
    $context_limit = 128000 - 4096; // Adjust the context limit for chunks based on max context window and max output tokens
    $maxTokens = min(intval($maxTokens), 4096); // Ensure maxTokens does not exceed 4096
    $temperature = floatval($temperature); // Use floatval for temperature

    $api_key = get_option('cicg_chatgpt_api_key');
    $api_endpoint = 'https://api.openai.com/v1/chat/completions'; 

    // Prepare data for API request
    $description_data = array(
        'model' => 'gpt-4o',
        'messages' => array(
            array(
                'role' => 'system',
                'content' => 'You are a helpful assistant that generates product descriptions, conclusions, and FAQs.',
            ),
            array(
                'role' => 'user',
                'content' => 'Generate a product description for ' .  $postTitle . '. The article should be ' . $contentLength . ' words. The article should be written in a ' . $writingStyle . ' style. The tone should be ' . $writingTone . '. The article should be written in ' . $contentLanguage . ' language. Do not include the phrase "Product Description" or any similar title.',
            ),
        ),
        'max_tokens' => $maxTokens,
        'temperature' => $temperature,
    );

    // Adjust messages based on FAQ and Conclusion settings
    if ($cicggeneratefaq == 'on' && $cicggenerateconc == 'on') {
        $description_data['messages'][] = array(
            'role' => 'user',
            'content' => 'Generate product description, FAQ, and conclusion for ' . $postTitle . '.',
        );
    } elseif ($cicggeneratefaq == 'on') {
        $description_data['messages'][] = array(
            'role' => 'user',
            'content' => 'Generate product description and FAQ for ' . $postTitle . '. Do not include a conclusion.',
        );
    } elseif ($cicggenerateconc == 'on') {
        $description_data['messages'][] = array(
            'role' => 'user',
            'content' => 'Generate product description and conclusion for ' . $postTitle . '. Do not include a FAQ.',
        );
    } else {
        $description_data['messages'][] = array(
            'role' => 'user',
            'content' => 'Generate a product description for ' . $postTitle . '. Do not include a FAQ or conclusion.',
        );
    }

    $response = wp_safe_remote_post($api_endpoint, array(
        'body' => json_encode($description_data),
        'headers' => array(
            'Content-Type' => 'application/json',
            'Authorization' => 'Bearer ' . $api_key,
        ),
        'timeout' => 160, // Set the timeout to 160 seconds
    ));
    
    // Log the request and response details
    $log_message = "Request URL: $api_endpoint\n";
    $log_message .= "Request Data: " . json_encode($description_data) . "\n";
    $log_message .= "Response: " . print_r($response, true) . "\n\n";
    error_log($log_message, 3, WPCH_PLUGIN_DIR . '/chatgpt4o.log');

    if (is_wp_error($response)) {
        // Handle the error
        echo 'Error: ' . $response->get_error_message();
        return null;
    } else {
        $body = wp_remote_retrieve_body($response);
        $responseData = json_decode($body);
        
        if (isset($responseData->choices) && count($responseData->choices) > 0) {
            $postDescriptionApi = $responseData->choices[0]->message->content;

            // Process the content
            $conclusionIndex = strpos($postDescriptionApi, "Conclusion:");
            $faqIndex = strpos($postDescriptionApi, "FAQ:");

            // Initialize variables for each section
            $mainContent = "";
            $conclusion = "";
            $faq = "";

            // Extract content based on marker positions
            if ($conclusionIndex !== false && $faqIndex !== false) {
                // If both "Conclusion:" and "FAQ:" are present
                if ($conclusionIndex < $faqIndex) {
                    // If "Conclusion:" appears before "FAQ:", extract accordingly
                    $mainContent = trim(substr($postDescriptionApi, 0, $conclusionIndex));
                    $conclusion = trim(substr($postDescriptionApi, $conclusionIndex, $faqIndex - $conclusionIndex));
                    $faq = trim(substr($postDescriptionApi, $faqIndex));
                } else {
                    // If "FAQ:" appears before "Conclusion:", extract accordingly
                    $mainContent = trim(substr($postDescriptionApi, 0, $faqIndex));
                    $faq = trim(substr($postDescriptionApi, $faqIndex, $conclusionIndex - $faqIndex));
                    $conclusion = trim(substr($postDescriptionApi, $conclusionIndex));
                }
            } elseif ($conclusionIndex !== false) {
                // Only "Conclusion:" is present
                $mainContent = trim(substr($postDescriptionApi, 0, $conclusionIndex));
                $conclusion = trim(substr($postDescriptionApi, $conclusionIndex));
            } elseif ($faqIndex !== false) {
                // Only "FAQ:" is present
                $mainContent = trim(substr($postDescriptionApi, 0, $faqIndex));
                $faq = trim(substr($postDescriptionApi, $faqIndex));
            } else {
                // Neither "Conclusion:" nor "FAQ:" found, consider the whole content as main content
                $mainContent = trim($postDescriptionApi);
            }

            // Now you have the main content, conclusion, and FAQ sections
            $formattedMainContent = removeHtmlLineBreaks($mainContent);
            $formattedConclusion = removeHtmlLineBreaks($conclusion);
            $formattedFaq = removeHtmlLineBreaks($faq);
        
            $finalContent = "
            $formattedMainContent
        
            $formattedFaq
        
            $formattedConclusion
            ";

            return $finalContent;

        } else {
            // Handle the case where there are no choices in the response
            return null;
        }
    }
}
   
   
   
   
 function removeHtmlLineBreaks($input) {
	return preg_replace('/<br\s*\/?>/i', "\n", $input);
}


function mycc_schedule_articles_cron() {
    global $wpdb;
    
    
  		$action1 = 'weekly_licenseapi_action_event';
        if (!wp_next_scheduled($action1)) {
            wp_schedule_event(time(),'weekly_licenseapi', $action1);
        }
		add_action($action1, 'mycc_process_licenseapi_event');
  
    
    $table_name = $wpdb->prefix . 'mych_article_autocampaigns';
    $articles = $wpdb->get_results("SELECT * FROM $table_name WHERE status = 'run'");
	if(!empty($articles)) {
    foreach ($articles as $article) {
        $interval = $article->interval_time;
        $post_id = $article->id;

        // Determine the interval and schedule the event accordingly
        switch ($interval) {
            case 'em':
                $schedule = 'every_minutes_chatgptauto'; // Every Minute
                break;
            case 'hourly':
                $schedule = 'hourly_chatgptauto'; // Hourly
                break;
            case 'e3hours':
                $schedule = 'every_3_hours_chatgptauto'; // Every 3 hours
                break;
            case 'e6hours':
                $schedule = 'every_6_hours_chatgptauto'; // Every 6 hours
                break;
            case 'e12hours':
                $schedule = 'every_12_hours_chatgptauto'; // Every 12 hours
                break;
            case 'e24hours':
                $schedule = 'daily_chatgptauto'; // Every 24 hours
                break;
            case 'e3days':
                $schedule = 'every_3_days_chatgptauto'; // Every 3 days
                break;
            case 'week':
                $schedule = 'weekly_chatgptauto'; // Once a week
                break;
            default:
                $schedule = 'daily_chatgptauto'; // Default to 24 hours
                break;
        }

        // Schedule the event using the calculated schedule
		$action = $schedule.'_action_event';
        if (!wp_next_scheduled($action)) {
            wp_schedule_event(time(), $schedule, $action);
        }
		add_action($action, 'mycc_process_articles_event');
		//add_action($action, 'mycc_process_articles_event');
		//wp_schedule_event(time(), 'every1minute_chatgpt', 'every1minute_chatgpt_events');

    }
}
}

//add_action('init', 'mycc_schedule_articles_cron');

//mycc_process_articles_event();


function mycc_process_licenseapi_event() {
        global $wpdb;
    $email_to_query = get_option('my_pro_licence_email');
    $api_endpoint = 'https://www.mycontentcreatorpro.com/api/ordersa.php';
    $api_endpoint = add_query_arg(['email' => $email_to_query], $api_endpoint);

    // Make the API request
    $response = wp_remote_get($api_endpoint);

    // Check for errors
    if (is_wp_error($response)) {
        echo 'Error: ' . $response->get_error_message();
    } else {
        // Parse the JSON response or handle the data as needed
        $body = wp_remote_retrieve_body($response);
            $data = json_decode($body, true);
        if ($data) {
                    $order_status = $data[0];
                     $product_id = $data[1];
                if($product_id=='5346'){
                    update_option('my_pro_licence_type','elite');
                } elseif($product_id=='5339'){
                    update_option('my_pro_licence_type','normal');
                }
                if($order_status=='refunded'){
                    update_option('my_pro_licence_status','inactive');
                }
                  if($order_status=='completed'){
                    update_option('my_pro_licence_status','completed');
                }
                  if($order_status=='Failed'){
                    update_option('my_pro_licence_status','inactive');
                }
        } else {
            update_option('my_pro_licence_status','inactive');
        }
    }
    
}

function mycc_process_articles_event() {
    // Fetch the article with the given $post_id
    global $wpdb;
	    $table_name = $wpdb->prefix . 'mych_article_autocampaigns';

		$articles = $wpdb->get_results("SELECT * FROM $table_name WHERE status = 'run'", ARRAY_A);
    //$articles = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table_name WHERE id = %d", $post_id));
	//$title = $article->title;
	$maxTokens = esc_attr( (get_option('cicg_chatgpt_api_max_tokens')) ? get_option('cicg_chatgpt_api_max_tokens') : 4000 );
	$temperature = esc_attr( (get_option('cicg_api_temperature')) ? get_option('cicg_api_temperature') : 1 );
	$cicg_gpt_version = esc_attr( (get_option('cicg_gpt_version')) ? get_option('cicg_gpt_version') : 'gpt-3.5' );

	$maxTokens = intval($maxTokens);
   // $temperature = get_option('cicg_api_temperature');
   $temperature = floatval($temperature); // Cast to float
    //$requests = $wpdb->get_results("SELECT * FROM $table_name WHERE status = 'pending' limit 0,1", ARRAY_A);
	if(!empty($articles)){
		foreach ($articles as $article) {
		$title = $article['title'];
		$contentLength = $article['content_length'];
		$writingStyle = $article['writing_style'];
		$writingTone = $article['writing_tone'];
		$contentLanguage = $article['content_language'];
		$generate_tag = $article['generate_tag'];
		$cicggeneratefaq = $article['generate_faq'];
		$cicggenerateconc = $article['generate_conc'];
		$pstatus = $article['pstatus'];
		$post_category = $article['category_id'];


						if($cicg_gpt_version=='gpt-4.0'){

						// Generate and insert articles based on the request parameters
						$article_title = chatgpt_generate_title_gpt4($title,$contentLength, $maxTokens, $temperature); 

						$article_content = chatgpt_generate_description_gpt4($title, $contentLength, $writingStyle, $writingTone, $contentLanguage, $cicggeneratefaq, $cicggenerateconc, $maxTokens, $temperature); // Implement this function to generate content
						$heading = '<h2>' . $article_title . '</h2>';
						$article_content = $heading . $article_content;
									$my_post1 = array(
								'post_title'    => $article_title,
								'post_content'  => $article_content,
								'post_status'   => $pstatus,
								'post_category' => array($post_category),
							);
	  
						if (function_exists('wp_insert_post')) {
							$post_id = @wp_insert_post($my_post1);

							$current_post_count = $wpdb->get_var("SELECT post_count FROM $table_name WHERE id = " . $article['id']);

							// Increment the post_count
							$new_post_count = $current_post_count + 1;
							
							$post_count++; // Increment the post count
							// Update the post count in the database
							$wpdb->update(
								$table_name,
								array('post_count' => $new_post_count),
								array('id' => $article['id'])
							);

							if (is_wp_error($post_id)) {
								// Handle the error
								$error_message = $post_id->get_error_message();
								//echo "Error: $error_message";
							} else {


								$tags = chatgpt_generate_tags($title,$contentLanguage,3000,$temperature);
								if(!empty($tags)){
								wp_set_post_tags($post_id,$tags);
								}

							}
						} else {
							//echo "WordPress is not loaded.";
						}
					} elseif($cicg_gpt_version=='gpt-4o'){

						// Generate and insert articles based on the request parameters
						$article_title = chatgpt_generate_title_gpt4($title,$contentLength, $maxTokens, $temperature); 

						$article_content = chatgpt_generate_description_gpt4o($title, $contentLength, $writingStyle, $writingTone, $contentLanguage, $cicggeneratefaq, $cicggenerateconc, $maxTokens, $temperature); // Implement this function to generate content
						$heading = '<h2>' . $article_title . '</h2>';
						$article_content = $heading . $article_content;
									$my_post1 = array(
								'post_title'    => $article_title,
								'post_content'  => $article_content,
								'post_status'   => $pstatus,
								'post_category' => array($post_category),
							);
	  
						if (function_exists('wp_insert_post')) {
							$post_id = @wp_insert_post($my_post1);

							$current_post_count = $wpdb->get_var("SELECT post_count FROM $table_name WHERE id = " . $article['id']);

							// Increment the post_count
							$new_post_count = $current_post_count + 1;
							
							$post_count++; // Increment the post count
							// Update the post count in the database
							$wpdb->update(
								$table_name,
								array('post_count' => $new_post_count),
								array('id' => $article['id'])
							);

							if (is_wp_error($post_id)) {
								// Handle the error
								$error_message = $post_id->get_error_message();
								//echo "Error: $error_message";
							} else {


								$tags = chatgpt_generate_tags($title,$contentLanguage,3000,$temperature);
								if(!empty($tags)){
								wp_set_post_tags($post_id,$tags);
								}

							}
						} else {
							//echo "WordPress is not loaded.";
						}
					}
					
					else {
						// Generate and insert articles based on the request parameters
						$article_title = chatgpt_generate_title($title,$contentLength, $maxTokens, $temperature); 

						$article_content = chatgpt_generate_description($title, $contentLength, $writingStyle, $writingTone, $contentLanguage, $cicggeneratefaq, $cicggenerateconc, $maxTokens, $temperature); // Implement this function to generate content
						$heading = '<h2>' . $article_title . '</h2>';
						$article_content = $heading . $article_content;
									$my_post1 = array(
								'post_title'    => $article_title,
								'post_content'  => $article_content,
								'post_status'   => $pstatus,
								'post_category' => array($post_category),
							);
	  
						if (function_exists('wp_insert_post')) {
							$post_id = @wp_insert_post($my_post1);

							$current_post_count = $wpdb->get_var("SELECT post_count FROM $table_name WHERE id = " . $article['id']);

							// Increment the post_count
							$new_post_count = $current_post_count + 1;
							
							$post_count++; // Increment the post count
							// Update the post count in the database
							$wpdb->update(
								$table_name,
								array('post_count' => $new_post_count),
								array('id' => $article['id'])
							);

							if (is_wp_error($post_id)) {
								// Handle the error
								$error_message = $post_id->get_error_message();
								//echo "Error: $error_message";
							} else {


								$tags = chatgpt_generate_tags($title,$contentLanguage,$maxTokens,$temperature);
								if(!empty($tags)){
								wp_set_post_tags($post_id,$tags);
								}

							}
						} else {
							//echo "WordPress is not loaded.";
						}						
					}



	
    }
}
	//exit();
}



function mycc_custom_cron_schedules($schedules) {
    $schedules['every_minutes_chatgptauto'] = array(
        'interval' => 60, // 60 seconds
        'display' => __('Every Minute', 'textdomain')
    );
    $schedules['hourly_chatgptauto'] = array(
        'interval' => 3600, // 60 seconds
        'display' => __('Every Hour', 'textdomain')
    );	
    $schedules['every_3_hours_chatgptauto'] = array(
        'interval' => 10800, // 3 hours in seconds
        'display' => __('Every 3 hours', 'textdomain')
    );
    $schedules['every_6_hours_chatgptauto'] = array(
        'interval' => 21600, // 6 hours in seconds
        'display' => __('Every 6 hours', 'textdomain')
    );
    $schedules['every_12_hours_chatgptauto'] = array(
        'interval' => 43200, // 12 hours in seconds
        'display' => __('Every 12 hours', 'textdomain')
    );
    $schedules['every_3_days_chatgptauto'] = array(
        'interval' => 259200, // 3 days in seconds
        'display' => __('Every 3 days', 'textdomain')
    );
    $schedules['weekly_chatgptauto'] = array(
        'interval' => 604800, // 1 week in seconds
        'display' => __('Once a week', 'textdomain')
    );
    $schedules['weekly_licenseapi'] = array(
        'interval' => 604800, // 1 week in seconds
        'display' => __('Once a week', 'textdomain')
    );    
    return $schedules;
}

add_filter('cron_schedules', 'mycc_custom_cron_schedules');

add_action('wp_ajax_handle_campaign_action', 'handle_campaign_action');
add_action('wp_ajax_nopriv_handle_campaign_action', 'handle_campaign_action');

function handle_campaign_action() {
    // Get the campaign ID and action type from the AJAX request
    $campaign_id = isset($_POST['campaign_id']) ? intval($_POST['campaign_id']) : 0;
    $action_type = isset($_POST['action_type']) ? sanitize_text_field($_POST['action_type']) : '';


    global $wpdb;
    $table_name = $wpdb->prefix . 'mych_article_autocampaigns';

    if ($action_type === 'Pause') {
        // Perform the pause action
        // Replace the following line with your actual logic
        $wpdb->update($table_name, array('status' => 'Paused'), array('id' => $campaign_id), array('%s'), array('%d'));
        $response = 'Campaign paused successfully.';
    }  elseif ($action_type === 'Resume') {
        // Perform the pause action
        // Replace the following line with your actual logic
        $wpdb->update($table_name, array('status' => 'run'), array('id' => $campaign_id), array('%s'), array('%d'));
        $response = 'Campaign Resume successfully.';
    }	elseif ($action_type === 'delete') {
        // Perform the delete action
        // Replace the following line with your actual logic
		$wpdb->delete($table_name, array('id' => $campaign_id), array('%d'));
        $response = 'Campaign deleted successfully.';
    } else {
        $response = 'Invalid action.';
    }
    // Return a response (e.g., success message)
    echo $response;
    // Always exit to prevent extra output
    wp_die();
}


add_action('wp_ajax_handle_postspin_action', 'mycc_handle_postspin_action');
add_action('wp_ajax_nopriv_handle_postspin_action', 'mycc_handle_postspin_action');

function mycc_handle_postspin_action() {
    // Get the campaign ID and action type from the AJAX request
        $stitle = isset($_POST['stitle']) ? sanitize_text_field($_POST['stitle']) : '';
    $scontent = isset($_POST['scontent']) ? sanitize_text_field($_POST['scontent']) : '';
    
    
        $sstatus = isset($_POST['sstatus']) ? sanitize_text_field($_POST['sstatus']) : '';
    $scategory = isset($_POST['scategory']) ? sanitize_text_field($_POST['scategory']) : '';
    $gtag = isset($_POST['gtag']) ? sanitize_text_field($_POST['gtag']) : '';
// Convert line breaks to <br> tags
$scontent = str_replace("\n", "<br><br>", $scontent);
// Wrap the content with <p> tags
                $maxTokens = 7900;
                $temperature = 1.0;
                $contentLanguage = 'en';
									$my_post1 = array(
								'post_title'    => $stitle,
								'post_content'  => $_POST['scontent'],
								'post_status'   => $sstatus,
								'post_category' => array($scategory),
							);

						if (function_exists('wp_insert_post')) {
							$post_id = @wp_insert_post($my_post1);
							
							if (is_wp_error($post_id)) {
								// Handle the error
								$error_message = $post_id->get_error_message();
								//echo "Error: $error_message";
							} else {
							    if($gtag=='yes'){
								$tags = chatgpt_generate_tags($stitle,$contentLanguage,$maxTokens,$temperature);
								if(!empty($tags)){
								wp_set_post_tags($post_id,$tags);
								}
							    }

							}
						} else {
							// WordPress is not loaded, handle this case accordingly
							//echo "WordPress is not loaded.";
						
						}
    // Return a response (e.g., success message)
    //echo $response;
    // Always exit to prevent extra output
    wp_die();
}

function get_button_label($status) {
    if ($status === 'run') {
        return 'Pause';
    } elseif ($status === 'Paused') {
        return 'Resume';
    }
}

?>