<?php

namespace metakeywordai\Admin;

use WP_REST_Response;

class UnleashAI
{
    private $lickey = "";
    private $plugiusingkey = "";
    private $helper = "";
/**
 * Plugin_Menu constructor.
 * Initializes helper class, retrieves plugin options, and sets up hooks.
 */
public function __construct()
{
    // Retrieve plugin options and sanitize them
    $this->lickey = sanitize_text_field(get_option('license_key_ai', ''));
    $this->plugiusingkey = sanitize_text_field(get_option('cg_act_plugnname', ''));

    // Initialize WordPress hooks
    $this->unleash_ai_initialize_hooks();
  
}

/**
 * Registers all WordPress hooks and actions for the plugin.
 */
private function unleash_ai_initialize_hooks() {
    // Add plugin menu
    
    add_action('admin_menu', [$this, 'unleash_ai_add_plugin_menu']);
    // Enqueue admin-specific scripts and styles
    add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));

    add_action('admin_enqueue_scripts', [$this, 'unleash_ai_enqueue_scripts']);
	add_action('wp_ajax_unleash_ai_logout',[$this,'unleash_ai_plug_logout_portal']);

    // Register AJAX actions
    $this->unleash_ai_register_ajax_hooks();

    // Add custom loader HTML to the admin footer
    add_action('admin_footer', [$this, 'unleash_ai_add_custom_loader_html']);

    // API-related hooks and filters
    $this->unleash_ai_initialize_api_hooks();
}

/**
 * Registers all AJAX actions for authenticated and unauthenticated users.
 */
private function unleash_ai_register_ajax_hooks()
{
    $ajax_actions = [
        'update_meta_action'       => 'unleash_ai_metupdate_cust',
        'update_image_alt_text'    => 'update_image_alt_text',
        'unleash_ai_fetchmeta_rec'            => 'unleash_ai_fetchmeta_rec',
        'unleash_ai_fetchalt_rec'             => 'unleash_ai_fetchalt_rec',
        'getalt_img'               => 'getalt_img',
        'unleash_ai_plug_reg_portal'          => 'unleash_ai_plug_reg_portal',
        'unleash_ai_plug_logout_portal'       => 'unleash_ai_plug_logout_portal',
        'unleash_ai_plug_login_portal'        => 'unleash_ai_plug_login_portal',
       // 'validate_license_key'     => 'validate_license_key',
       // 'track_profile_data'       => 'track_profile_data',
       // 'bulk_meta_genrate'        => 'bulk_meta_genrate',
       // 'unleash_ai_bulk_update_meta'         => 'unleash_ai_bulk_update_meta',
       // 'bulk_meta_alt_genrate'    => 'bulk_meta_alt_genrate',
       // 'bulk_alt_update_meta'     => 'bulk_alt_update_meta',
        //'fetch_req_limit'          => 'fetch_req_limit',
       // 'track_plugin_data'        => 'track_plugin_data',
        // 'admin_enqueue_scripts' => 'enqueue_logout_script',
       // 'generate_jwt_metakey_ai'  => 'generate_jwt_metakey_ai',
    ];

    foreach ($ajax_actions as $action => $callback) {
        // For logged-in users
        add_action("wp_ajax_{$action}", [$this, $callback]);

        // For logged-out users
        add_action("wp_ajax_nopriv_{$action}", [$this, $callback]);
    }
}

function enqueue_logout_script() {
    wp_enqueue_script('metakeywordailogout-script', plugins_url('/js/logout.js', __FILE__), array('jquery'), '1.0', true);
    wp_localize_script('metakeywordailogout-script', 'metaLogoutData', array(
        'ajaxUrl' => admin_url('admin-ajax.php'),
        'nonce'   => wp_create_nonce('update_meta_nonce'),
    ));
}

/**
 * Registers API routes and related filters.
 */
private function unleash_ai_initialize_api_hooks()
{
    // Define JWT constants (ensure this is safe and secure)
    //define('JWT_AUTH_SECRET_KEY', 'dfgtert453fg4#$%fvfg567%^&fsdfgh245$%der'); // Replace with a secure key
    //define('JWT_AUTH_ALGORITHM', 'HS256');

    // Register custom REST API routes
   add_action('rest_api_init', [$this, 'unleash_ai_register_routes']);

    // Generate JWT for admin on login
   // add_action('wp_login', [$this, 'generate_jwt_for_admin'], 10, 2);

    // Add custom authentication filters
   //add_filter('rest_authentication_errors', 'unleash_ai_validate_custom_api_token');

    // Update alt tags dynamically
  add_filter('the_content', function($content) {
    // Sanitize the `tagverify` parameter
    $tagverify = isset($_GET['tagverify']) ? sanitize_text_field($_GET['tagverify']) : '';

    // Bypass the filter if `tagverify` is set and matches the expected value
    if ($tagverify) {
        return $content; // Skip processing
    }

    // Skip for admin or non-main query
    if (is_admin() || !is_main_query()) {
        return $content;
    }

    // Apply the custom function
    return $this->unleash_ai_update_image_alt_tags($content);
    }, 99);

    //add_filter('the_content', 'unleash_ai_ai_update_image_alt_tags');
 

}

   /**
 * Adds custom loader HTML to the admin footer.
 * Ensures unique IDs for loaders to avoid conflicts.
 */
public function unleash_ai_add_custom_loader_html()
{
    ?>
    <div id="custom-loader-cust" class="custom-loader">
        <div class="loader-spinner"></div>
       <!-- <div class="loader-text">Loading...</div>-->
    </div>
    <div id="custom-loader" class="custom-loader">
        <div class="loader-spinner"></div>
       <!--   <div class="loader-text">Loading...</div>-->
    </div>
    
    <?php
}


/**
 * Enqueues scripts and styles for the plugin's admin pages.
 *
 * @param string $hook The current admin page hook.
 */

public function enqueue_admin_scripts($hook_suffix) {
    // Verify we are on the plugin's top-level page
    $current_screen = get_current_screen();
    if ($current_screen && $current_screen->id === 'toplevel_page_unleash_ai_plugin') {
        wp_enqueue_script(
            'getstarted-ui-script',
            plugins_url('js/get_started.js', __FILE__),
            array('jquery'),
            '1.0.0',
            true
        );

        wp_localize_script('getstarted-ui-script', 'ajax_object', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'update_nonce' => wp_create_nonce('update_meta_nonce'),
        ));
    }
}


public function unleash_ai_enqueue_scripts($hook) {
 
 $current_screen = get_current_screen();
 if ($current_screen && $current_screen->id === 'unleashai_page_cg_meta_al_altag') {
    wp_enqueue_script('altimages-ui-script', plugins_url('js/alt_images.js', __FILE__), array('jquery'), '1.0.0', true);
    wp_localize_script('altimages-ui-script', 'ajax_object', array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'update_nonce'    => wp_create_nonce('update_meta_nonce'),
    ));
   }
   if ($current_screen && $current_screen->id === 'unleashai_page_cg_meta_al_list') {
    wp_enqueue_script('page-list-ui-script', plugins_url('js/page_list.js', __FILE__), array('jquery'), '1.0.0', true);
    wp_localize_script('page-list-ui-script', 'ajax_object', array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'update_nonce'    => wp_create_nonce('update_meta_nonce'),
    ));
  }
  
  wp_enqueue_style('jquery-ui-style', plugins_url('css/jquery-ui.css', __FILE__));
    //wp_enqueue_style('bootstrap-css', plugins_url('css/bootstrap.min.css', __FILE__));
    wp_enqueue_script('bootstrap-js', plugins_url('js/bootstrap.min.js', __FILE__), array('jquery'), null, true);
    wp_enqueue_style('customcss', plugins_url('css/stylesheet-unleash.css', __FILE__));
   
    wp_enqueue_script(
        'getstarted-ui-script',
        plugins_url('js/get_started.js', __FILE__),
        array('jquery'),
        '1.0.0',
        false
    );

    wp_localize_script('getstarted-ui-script', 'ajax_object', array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'update_nonce' => wp_create_nonce('update_meta_nonce'),
    ));

}



    /**
 * Adds menu pages for the UnleashAI plugin.
 *
 * This function registers the main menu and various submenu pages for the plugin.
 * Some submenu pages are hidden and accessible only via direct URL.
 *
 * @since 1.0.0
 */
public function unleash_ai_add_plugin_menu()
{
    // Add main menu page
    add_menu_page(
        'UnleashAI',          // Page title
        'UnleashAI',          // Menu title
        'manage_options',     // Capability required to access the menu
        'cg_meta_al',         // Menu slug
        array($this, 'unleash_ai_plugin_page'), // Callback function to display page content
        'dashicons-list-view', // Icon URL or name
        80                    // Position in the menu
    );

    // Define submenu pages
    $submenus = [
        [
            'parent_slug' => 'cg_meta_al',
            'page_title'  => 'Manage Meta Information',
            'menu_title'  => 'Manage Meta Information',
            'capability'  => 'manage_options',
            'menu_slug'   => 'cg_meta_al_list',
            'callback'    => 'unleash_ai_render_list_content',
        ],
        [
            'parent_slug' => null,
            'page_title'  => 'View Page',
            'menu_title'  => 'View Page',
            'capability'  => 'manage_options',
            'menu_slug'   => 'cg_meta_al_product',
            'callback'    => 'unleash_ai_render_list_view',
            'condition'   => !defined('DO_NOT_SHOW_SUBMENU'), // Conditional visibility
        ],
        [
            'parent_slug' => 'cg_meta_al',
            'page_title'  => 'Manage Alt Tags',
            'menu_title'  => 'Manage Alt Tags',
            'capability'  => 'manage_options',
            'menu_slug'   => 'cg_meta_al_altag',
            'callback'    => 'unleash_ai_render_alttag_view',
        ],
        [
            'parent_slug' => 'cg_meta_al',
            'page_title'  => 'Account Settings',
            'menu_title'  => 'Account Settings',
            'capability'  => 'manage_options',
            'menu_slug'   => 'cg_meta_al_account',
            'callback'    => 'render_account_view',
        ],
    ];

    // Register submenu pages
    foreach ($submenus as $submenu) {
        // Check for any conditional logic before adding submenu
        if (isset($submenu['condition']) && !$submenu['condition']) {
            continue;
        }

        add_submenu_page(
            $submenu['parent_slug'],
            $submenu['page_title'],
            $submenu['menu_title'],
            $submenu['capability'],
            $submenu['menu_slug'],
            array($this, $submenu['callback'])
        );
    }

    // Uncomment the following line if you need to remove a menu item
    // add_action('admin_head', array($this, 'remove_custom_page_menu'));
}


/**
 * Callback function to display the main plugin page.
 *
 * Renders the main plugin page within the WordPress admin dashboard.
 *
 * @since 1.0.0
 */
public function unleash_ai_plugin_page()
{
    wp_enqueue_script('getstarted-ui-script', plugins_url('js/get_started.js', __FILE__), array('jquery'), '1.0.0', true);
    wp_localize_script('getstarted-ui-script', 'ajax_object', array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'update_nonce'    => wp_create_nonce('update_meta_nonce'),
    ));
    
    // Include the header file
    include(__DIR__ . '/templates/header.php');

    $secret_key = get_option('unleash_ai_secret_key');

    // Generate and save a new secret key if not already set
    if (!$secret_key) {
        $secret_key = wp_generate_password(32, false, false);
        update_option('unleash_ai_secret_key', $secret_key);
    }

    // Handle secret key regeneration
    if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['regenerate_key'])) {
        check_admin_referer('unleash_ai_regenerate_secret_key_action', 'regenerate_nonce'); // Verify nonce
        $stored_response = get_option( 'unleash_ai_registration_response' );
  
        $response = array();
       
        if ($stored_response) {
            $response_array = json_decode($stored_response, true);
    
            // Get the username and API token from the response array
            if (isset($response_array['username'])) {
                $username = $response_array['username'];
              
            }
        }

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

       // Ensure proper format for value(s) being passed into the query
$delete_result = $wpdb->delete(
    $table_name, 
    array('username' => $username),  // Column => Value
    array('%s')  // Format for the value (string)
);
        if ($delete_result === false) {
        echo '<div class="error notice"><p>Error deleting tokens. Please try again.</p></div>';
    } else {
        // Generate and update the secret key
         // Clear the cache for this specific data (if cached)
    wp_cache_delete( 'custom_api_tokens_' . $username, 'custom_api_tokens' );
        $new_secret_key = wp_generate_password(32, false, false);
        update_option('unleash_ai_secret_key', $new_secret_key);

        echo '<div class="updated notice"><p>Secret key regenerated successfully, and all tokens have been deleted!</p></div>';
        $secret_key = $new_secret_key;
    }
}

   
    // Include the 'Get Started' page content
    include(__DIR__ . '/templates/getstarted_page.php');
}

public function unleash_ai_render_alttag_view()
{
    // Enqueue necessary scripts and styles
  /*  wp_enqueue_script('jquery-ui-tabs');
   
   */
    // Pagination parameters
    $current_page = isset($_GET['paged']) ? absint($_GET['paged']) : 1;
    $per_page = isset($_GET['aifilterpage']) ? absint($_GET['aifilterpage']) : 10;

    $request = [
        "paged" => $current_page, // Current page
        "PostPerPage" => $per_page, // Number of posts per page
        "post_type" => "attachment", // Post type
    ];
    $json_request = wp_json_encode($request);

    // Get custom post meta list
    $response_data = $this->unleash_ai_get_custom_post_meta_list($json_request);

    // Include the header and the alt tag images UI
    include(__DIR__ . '/templates/header.php');
    include(__DIR__ . '/templates/alt_tag_images.php');
}

public function render_account_view()
{
    $secret_key = get_option('unleash_ai_secret_key');

    // Generate and save a new secret key if not already set
    if (!$secret_key) {
        $secret_key = wp_generate_password(32, false, false);
        update_option('unleash_ai_secret_key', $secret_key);
    }

    // Handle secret key regeneration
    if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['regenerate_key'])) {
        check_admin_referer('unleash_ai_regenerate_secret_key_action', 'regenerate_nonce'); // Verify nonce
        $stored_response = get_option( 'unleash_ai_registration_response' );
  
        $response = array();
       
        if ($stored_response) {
            $response_array = json_decode($stored_response, true);
    
            // Get the username and API token from the response array
            if (isset($response_array['username'])) {
                $username = $response_array['username'];
              
            }
        }

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

       // Ensure proper format for value(s) being passed into the query
$delete_result = $wpdb->delete(
    $table_name, 
    array('username' => $username),  // Column => Value
    array('%s')  // Format for the value (string)
);
        if ($delete_result === false) {
        echo '<div class="error notice"><p>Error deleting tokens. Please try again.</p></div>';
    } else {
        // Generate and update the secret key
         // Clear the cache for this specific data (if cached)
    wp_cache_delete( 'custom_api_tokens_' . $username, 'custom_api_tokens' );
        $new_secret_key = wp_generate_password(32, false, false);
        update_option('unleash_ai_secret_key', $new_secret_key);

        echo '<div class="updated notice"><p>Secret key regenerated successfully, and all tokens have been deleted!</p></div>';
        $secret_key = $new_secret_key;
    }
}
    // Include the header and the alt tag images UI
    include(__DIR__ . '/templates/header.php');
    include(__DIR__ . '/templates/account.php');
}
/**
 * Callback function to render the license key page.
 *
 * Renders the license key page within the WordPress admin dashboard.
 *
 * @since 1.0.0
 */
public function unleash_ai_render_license_key()
{

    // Include the header file, ensuring the file exists
    if (file_exists(__DIR__ . '/templates/header.php')) {
        include(__DIR__ . '/templates/header.php');
    } else {
        echo '<div class="error notice"><p>Header file missing!</p></div>';
    }

   
}



    /**
 * Callback function to render the list content page.
 *
 * This function is responsible for rendering the list content page within the WordPress admin dashboard.
 * It checks if the license key is empty and redirects to the license key page if necessary.
 * It enqueues necessary scripts and styles, including pagination parameters, and includes necessary files such as header and the list content UI.
 *
 * @since 1.0.0
 */
public function unleash_ai_render_list_content()
{
    
    // Define pagination parameters
    $pagination_args = array(
        'total' => ceil(count(get_pages()) / 10), // Total number of pages divided by number of pages per page
        'current' => max(1, get_query_var('paged')),
        'show_all' => false,
        'end_size' => 1,
        'mid_size' => 2,
        'prev_next' => true,
        'prev_text' => esc_html__('« Previous', 'unleashai'),
        'next_text' => esc_html__('Next »', 'unleashai'),
    );

    $plgactive = $this->plugiusingkey;

    // Include the header and the list content UI
    include(__DIR__ . '/templates/header.php');
    include(__DIR__ . '/templates/pages_list_ui.php');
}

/**
 * Callback function to render the list view page.
 *
 * This function is responsible for rendering the list view page within the WordPress admin dashboard.
 * It checks if the license key is empty and redirects to the license key page if necessary.
 * It enqueues necessary scripts and styles, and includes necessary files such as header and the list view content UI.
 * If WooCommerce is active, it retrieves and displays a list of products.
 *
 * @since 1.0.0
 */
public function unleash_ai_render_list_view()
{
   
    // Retrieve products if WooCommerce is active
    if (is_plugin_active('woocommerce/woocommerce.php')) {
        $paged = isset($_GET['paged']) ? absint($_GET['paged']) : 1;  // Default to 1 if not provided
        $products = wc_get_products(array(
            'status' => 'publish', // Retrieve only published products
            'limit' => 5,          // Number of products per page
            'offset' => ($paged - 1) * 5, // Offset calculation
        ));
    }

    // Include the header and the product list UI
    include(__DIR__ . '/templates/header.php');
    include(__DIR__ . '/templates/product_list_ui.php');
}



   
public function unleash_ai_metupdate_cust()
{
    global $wpdb;

    // Verify nonce for security
    $nonce = isset($_POST['nonce']) ? sanitize_text_field($_POST['nonce']) : '';
    if (!wp_verify_nonce($nonce, 'update_meta_nonce')) {
        wp_send_json_error('Invalid nonce.');
    }

    // Verify request method and user authentication
    if (isset($_POST['jwt_loggedin'])) {
        if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] !== 'POST') {
            wp_send_json_error('Unauthorized access.');
        }
    } else {
        if (!isset($_SERVER['REQUEST_METHOD']) || $_SERVER['REQUEST_METHOD'] !== 'POST' || !is_user_logged_in()) {

            wp_send_json_error('Unauthorized access.');
        }
    }

    // Sanitize and validate inputs
$pageID = isset($_POST['pageID']) ? intval(wp_unslash($_POST['pageID'])) : 0;
$metaTitle = isset($_POST['metaTitle']) ? sanitize_text_field(wp_unslash($_POST['metaTitle'])) : '';
$metaDescription = isset($_POST['metaDescription']) ? sanitize_text_field(wp_unslash($_POST['metaDescription'])) : '';
$altTag = isset($_POST['altTag']) ? sanitize_text_field(wp_unslash($_POST['altTag'])) : '';
$image_id = isset($_POST['image_id']) ? sanitize_text_field(wp_unslash($_POST['image_id'])) : '';

    // Check if the page ID is valid
    if (!$pageID || !get_post($pageID)) {
        wp_send_json_error('Invalid page ID.');
    }

    // Handle Alt Tags Update
    if (!empty($altTag)) {
        // Define custom alt tags table
        if (!$image_id) {
            wp_send_json_error('Invalid image ID.');
        }
        $table_name = $wpdb->prefix . 'ai_alt_tags';

        // Insert or update alt tag in the custom table
      // Check if the data is already in the cache
$cached_data = wp_cache_get("image_data_{$pageID}", 'custom_cache_group');

if (!$cached_data) {
    // If not found in cache, perform the replace operation
    global $wpdb;
  
    
    $replace_result = $wpdb->replace(
        $table_name,
        [
            'image_id' => $image_id,
            'page_id'  => $pageID,
            'alt_text' => $altTag,
        ],
        [
            '%d', // image_id format
            '%d', // page_id format
            '%s', // alt_text format
        ]
    );
    
    // Cache the result after replacing
    if ($replace_result !== false) {
        wp_cache_set("image_data_{$pageID}", [
            'image_id' => $image_id,
            'page_id'  => $pageID,
            'alt_text' => $altTag,
        ], 'custom_cache_group');
    }
}

        // Update the attachment alt meta in WordPress
        update_post_meta($image_id, '_wp_attachment_image_alt', $altTag);

        wp_send_json_success('Alt tags updated successfully.');
    }

    // Update Meta Title and Description
    if (!empty($metaTitle) || !empty($metaDescription)) {
        // Define AIOSEO table
        $table_name = $wpdb->prefix . 'aioseo_posts';

        // Data to be updated
        $data = [];
        $data_format = [];
        if (!empty($metaTitle)) {
            $data['title'] = $metaTitle;
            $data_format[] = '%s';
        }
        if (!empty($metaDescription)) {
            $data['description'] = $metaDescription;
            $data_format[] = '%s';
        }

        // WHERE condition
        $where = ['post_id' => $pageID];
        $where_format = ['%d'];

        // Execute the update query
        $result = $wpdb->update($table_name, $data, $where, $data_format, $where_format);

        // Update post meta for multiple SEO plugins
        if (!empty($metaTitle)) {
            $this->unleash_ai_update_or_add_post_meta($pageID, '_aioseo_title', $metaTitle);
            $this->unleash_ai_update_or_add_post_meta($pageID, '_yoast_wpseo_title', $metaTitle);
            $this->unleash_ai_update_or_add_post_meta($pageID, 'rank_math_title', $metaTitle);
            $this->unleash_ai_update_or_add_post_meta($pageID, '_seopress_titles_title', $metaTitle);
            $this->unleash_ai_update_or_add_post_meta($pageID, '_genesis_title', $metaTitle);
            $this->unleash_ai_update_or_add_post_meta($pageID, '_og_title', $metaTitle);
            $this->unleash_ai_update_or_add_post_meta($pageID, '_aioseo_og_title', $metaTitle);
            $this->unleash_ai_update_or_add_post_meta($pageID, '_aioseo_twitter_title', $metaTitle);
        }
        if (!empty($metaDescription)) {
            $this->unleash_ai_update_or_add_post_meta($pageID, 'rank_math_description', $metaDescription);
            $this->unleash_ai_update_or_add_post_meta($pageID, '_aioseo_description', $metaDescription);
            $this->unleash_ai_update_or_add_post_meta($pageID, '_yoast_wpseo_metadesc', $metaDescription);
            $this->unleash_ai_update_or_add_post_meta($pageID, '_genesis_description', $metaDescription);
            $this->unleash_ai_update_or_add_post_meta($pageID, '_og_description', $metaDescription);
            $this->unleash_ai_update_or_add_post_meta($pageID, '_aioseo_og_description', $metaDescription);
            $this->unleash_ai_update_or_add_post_meta($pageID, '_seopress_titles_desc', $metaDescription);
            $this->unleash_ai_update_or_add_post_meta($pageID, '_aioseo_twitter_description', $metaDescription);
        }

        // Check if the update was successful
        if ($result !== false) {
            wp_send_json_success('Meta information updated successfully.');
        } else {
            wp_send_json_error('Meta information update failed.');
        }
    }

    wp_send_json_error('No valid data provided for update.');
}


   /**
 * Updates or adds post meta for a given post.
 *
 * This function checks if the post exists, then checks if the post meta exists.
 * If the post meta doesn't exist, it adds it; otherwise, it updates it.
 * If the post doesn't exist, it logs an error.
 *
 * @param int    $postID    The ID of the post.
 * @param string $metaKey   The key of the meta data.
 * @param mixed  $metaValue The value of the meta data.
 *
 * @since 1.0.0
 */
function unleash_ai_update_or_add_post_meta($postID, $metaKey, $metaValue)
{
    // Check if the post exists
    if (get_post_status($postID)) {
        // If the post exists, check if the post meta exists
        if (!get_post_meta($postID, $metaKey, true)) {
            // If the post meta doesn't exist, add it
            add_post_meta($postID, $metaKey, $metaValue, true);
        } else {
            // If the post meta exists, update it
            update_post_meta($postID, $metaKey, $metaValue);
        }
    } else {
        // If the post doesn't exist, handle the error or log it
        debug_log('Error: Attempted to update or add post meta for non-existent post ID ' . $postID);
    }
}

/**
 * Updates the alt tag for a given attachment.
 *
 * This function updates the alt tag for a specified attachment by updating its metadata.
 * If the attachment metadata is found, it updates the alt tag and saves the metadata.
 * If the metadata is not found, it displays an error message.
 *
 * @param int    $attachment_id The ID of the attachment.
 * @param string $new_alt_tag   The new alt tag value.
 *
 * @since 1.0.0
 */
function unleash_ai_update_alttags($attachment_id, $new_alt_tag)
{
    // Get the attachment metadata
    $attachment_meta = wp_get_attachment_metadata($attachment_id);

    if ($attachment_meta) {
        // Update the alt tag in the attachment metadata
        $attachment_meta['image_meta']['alt'] = $new_alt_tag;

        // Update the attachment metadata
        wp_update_attachment_metadata($attachment_id, $attachment_meta);

        echo 'Alt tag updated successfully.';
    } else {
        echo 'Error: Attachment metadata not found.';
    }
}


   /**
 * Retrieves alt tags from images within the content of a specified post.
 *
 * This function searches for all image tags within the content of a specified post
 * and extracts the alt attribute values from them, returning an array of alt tags.
 *
 * @param int $post_id The ID of the post.
 *
 * @return array An array containing the alt tags of images within the post content.
 *
 * @since 1.0.0
 */
public function unleash_ai_get_image_alt_tags($post_id)
{
    $image_alt_tags = array();

    // Get the post content
    $post_content = get_post_field('post_content', $post_id);

    // Find all image tags in the post content
    preg_match_all('/<img[^>]+>/', $post_content, $matches);

    // Loop through the matched image tags
    foreach ($matches[0] as $image_tag) {
        // Get the alt attribute value from the image tag
        preg_match('/alt="([^"]+)"/', $image_tag, $alt_match);

        // If alt attribute exists, add it to the array
        if (!empty($alt_match[1])) {
            $image_alt_tags[] = $alt_match[1];
        }
    }

    return $image_alt_tags;
}


public function unleash_ai_fetchmeta_rec()
{
    $nonce = isset($_POST['nonce']) ? sanitize_key($_POST['nonce']) : '';

    // Validate the nonce
    if (!wp_verify_nonce($nonce, 'update_meta_nonce')) {
        wp_send_json_error('Invalid nonce.');
    }

    // Get and sanitize the post/page ID from the request
    $post_id = isset($_POST['pageID']) ? intval($_POST['pageID']) : 0;

    // Ensure post exists
    if ($post_id <= 0 || !get_post($post_id)) {
        wp_send_json_error('Invalid post ID.');
    }

    // Fetch post/page description
    $post = get_post($post_id);
    $post_description = '';
    if ($post) {
        // Get the post content and strip HTML tags
        $post_description = wp_strip_all_tags($post->post_content);
    }

    // Fetch image alt tags for the post/page
    $image_alt_tags = $this->unleash_ai_get_image_alt_tags($post_id);

    // Get the admin email address
    $admin_email = get_option('admin_email');

    // Get the site URL and remove "https://" and "www." from it
    $site_url = get_site_url();
    $nsite_url = str_replace("https://", " ", $site_url);
    $nsite_url = str_replace("www.", " ", $nsite_url);

    $user_id = get_current_user_id();
    $stored_response = get_option( 'unleash_ai_registration_response' );
  
    $response = array();
    $plan_id = 0;
    $username = $token = '';

    if ($stored_response) {
        $response_array = json_decode($stored_response, true);

        // Get the username and API token from the response array
        if (isset($response_array['username']) && isset($response_array['api_token'])) {
            $username = $response_array['username'];
            $token = $response_array['api_token'];
        }
    }

    // Prepare data to send in the request
    $request_data = array(
        "engine" => "chat gpt",
        "text" => $post_description,
        "image_alt_tags" => $image_alt_tags,
        "admin_email" => $admin_email,
        "titlechk" => isset($_POST['titlechk']) ? sanitize_text_field(wp_unslash($_POST['titlechk'])) : '',
        "deschk" => isset($_POST['deschk']) ? sanitize_text_field(wp_unslash($_POST['deschk'])) : '',
        "focus_words" => isset($_POST['foukeyword']) ? sanitize_text_field(wp_unslash($_POST['foukeyword'])) : '',    
        "site_url" => trim($nsite_url),
        "username" => $username,
    );

    // Convert data to JSON format
    $json_data = wp_json_encode($request_data);

    // Prepare data
    $args = array(
        'body'        => $json_data,
        'headers'     => array(
            'Content-Type'  => 'application/json',
            'Authorization' => 'Bearer ' . $token,
        ),
        'timeout'     => 15,  // Timeout (adjust as needed)
        'httpversion' => '1.1', // HTTP version
           'sslverify' => true, // Disable SSL verification
    );
    
    // Send the POST request using WordPress' wp_remote_post()
    $response = wp_remote_post('https://unleashai.co/api/seo_ai/get_meta_data', $args);
    
    // Check if the request was successful
    if (is_wp_error($response)) {
        wp_send_json_error('Request failed: ' . $response->get_error_message());
    } else {
        // Decode the JSON response
        $response_body = wp_remote_retrieve_body($response);
        $decoded_response = json_decode($response_body, true);
    
        // Check if the response is valid JSON
        if (json_last_error() === JSON_ERROR_NONE) {
            echo wp_json_encode($decoded_response); // Send the response to the client
        } else {
            wp_send_json_error('Error processing response.');
        }
    }
    
    // Terminate script execution
    die();
    
}


public function unleash_ai_fetchalt_rec() {
   // Verify nonce to prevent unauthorized access
if (
    !isset($_POST['nonce']) || 
    !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'update_meta_nonce')
) {
    wp_send_json_error('Invalid nonce.');
}


    // Get the post/page ID and image ID from the request
    $post_id = isset($_POST['pageID']) ? intval($_POST['pageID']) : 0;
    $attachment_id = isset($_POST['image_id']) ? intval($_POST['image_id']) : 0;

    // Fetch the post content description
    $post = get_post($post_id);
    $post_description = $post ? $post->post_content : '';

    // Fetch the image URL and alt text
    $image_url = wp_get_attachment_url($attachment_id);
    global $wpdb;
    $table_name = $wpdb->prefix . 'ai_alt_tags';

    // Get the alt text from the custom table or fallback to post meta
   /* $alt_text = $wpdb->get_var(
        $wpdb->prepare("SELECT alt_text FROM $table_name WHERE image_id = %d AND page_id = %d", $attachment_id, $post_id)
    );
    */

 $cache_key = "alt_text_{$attachment_id}_{$post_id}";  // Unique cache key based on image_id and page_id

// Try to get the cached alt_text first
$alt_text = wp_cache_get($cache_key, 'custom_cache_group');

if ($alt_text === false) {
    // If not found in cache, execute the query
    $alt_text = $wpdb->get_var(
        $wpdb->prepare(
            "SELECT alt_text FROM $table_name WHERE image_id = %d AND page_id = %d",
            $attachment_id,
            $post_id
        )
    );
    
    // If alt_text is found, cache it
    if ($alt_text !== null) {
        wp_cache_set($cache_key, $alt_text, 'custom_cache_group');
    }
}


    if (empty($alt_text)) {
        $alt_text = get_post_meta($attachment_id, '_wp_attachment_image_alt', true);
    }

    // Prepare the images array
   /* $images = $image_url ? array(
        'id' => $attachment_id,
        'url' => $image_url,
        'current_alt_tag' => $alt_text
    ) : []; */
    // Prepare the images array
    $images = [];

// Add multiple images to the array

    $images[] = [
        'id' => $attachment_id,
        'url' => $image_url,
        'current_alt_tag' => $alt_text,
    ];


    // Retrieve the stored response for user-specific details (username & token)
    $user_id = get_current_user_id();
    $stored_response = get_option( 'unleash_ai_registration_response' );
    if ($stored_response) {
        $response_array = json_decode($stored_response, true);
        $username = $response_array['username'];
        $token = $response_array['api_token'];
    }
    if (isset($_POST['foukeyword'])) {
        // Unsanitize the input to remove automatically added slashes
        $foukeyword = sanitize_text_field(wp_unslash($_POST['foukeyword']));
    
        // Validate if 'foukeyword' is not empty (if applicable)
        if (empty($foukeyword)) {
            // Handle the case where 'foukeyword' is empty
            $foukeyword = '';
        }
    }
    
    // Prepare data to send to the external API
    $request_data = array(
        "engine" => "chat gpt",
        "text" => $post_description,
        "images" => $images,
        "focus_words" => $foukeyword,
        "username" => $username,
    );

    // Convert data to JSON format
    $json_data = wp_json_encode($request_data);
    //print_r($json_data);
 
    // Prepare data for the request
    $args = array(
        'body'        => $json_data,  // The JSON data you are sending
        'headers'     => array(
            'Content-Type'  => 'application/json',
            'Authorization' => 'Bearer ' . $token,  // Use the actual token here
        ),
        'timeout'     => 15,  // Set a timeout value (optional)
        'httpversion' => '1.1', // Specify HTTP version
        'sslverify' => true, // Disable SSL verification
    );
    
    // Send the POST request using wp_remote_post
    $response = wp_remote_post('https://unleashai.co/api/seo_ai/get_alt_tags', $args);
    
    // Check if the request was successful
    if (is_wp_error($response)) {
        // Handle error, output the error message
        echo 'Request failed: ' .esc_html($response->get_error_message());
    } else {
        // Get the response body
        $response_body = wp_remote_retrieve_body($response);
        
        // Output the response (you can process the response as needed)
        echo wp_kses_post($response_body);
    }
    
    // Terminate script execution
    die();
    
}

    /**
     * Registers the plugin on the portal.
     *
     * This function sends a registration request to the plugin portal API to register the plugin.
     * It retrieves the registration email, admin email, and site URL, then sends this data along
     * with the plugin's license key to the portal API.
     *
     * @since 1.0.0
     *
     * @return void This function does not return any value. It sends a registration request to the portal API and terminates the script execution.
     */
    public function unleash_ai_plug_reg_portal() {
        // Verify nonce to protect against CSRF attacks
        if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] )), 'update_meta_nonce' ) ) {
            wp_send_json_error( 'Invalid nonce.' );
        }
        
        // Sanitize and validate form data
        $username = isset( $_POST['username'] ) ? sanitize_text_field( wp_unslash( $_POST['username'] ) ) : '';
        $email = isset( $_POST['email'] ) ? sanitize_email( wp_unslash( $_POST['email'] ) ) : '';
        $customer_full_name = isset( $_POST['customer_full_name'] ) ? sanitize_text_field( wp_unslash( $_POST['customer_full_name'] ) ) : '';
        $customer_company_name = isset( $_POST['customer_company_name'] ) ? sanitize_text_field( wp_unslash( $_POST['customer_company_name'] ) ) : '';
        $customer_phone = isset( $_POST['customer_phone'] ) ? sanitize_text_field( wp_unslash( $_POST['customer_phone'] ) ) : '';
        $plan_id = isset( $_POST['plan_id'] ) ? sanitize_text_field( wp_unslash( $_POST['plan_id'] ) ) : '';
        $password = isset( $_POST['password'] ) ? sanitize_text_field( wp_unslash( $_POST['password'] ) ) : '';
        
        // Prepare data to send in the request
        $request_data = array(
            'username' => $username,
            'customer_full_name' => $customer_full_name,
            'customer_company_name' => $customer_company_name,
            'customer_email' => $email,
            'customer_phone' => $customer_phone,
            'plan_id' => $plan_id,
            'password' => $password,
        );
    
        // Convert data to JSON format
        $json_data = wp_json_encode( $request_data );
    
        // Use wp_remote_post instead of cURL for better compatibility with WordPress
        $response = wp_remote_post(
            'https://unleashai.co/api/customers/register',
            array(
                'method'    => 'POST',
                'body'      => $json_data,
                'headers'   => array(
                    'Accept'       => 'application/json',
                    'Content-Type' => 'application/json',
                ),
                'timeout'   => 45, // Set a timeout for the request
            )
        );
    
        // Check for any errors with the request
        if ( is_wp_error( $response ) ) {
            wp_send_json_error( 'Request failed: ' . $response->get_error_message() );
        }
    
        // Check the response status
        $http_code = wp_remote_retrieve_response_code( $response );
        if ( $http_code !== 200 ) {
            wp_send_json_error( 'Failed to register: HTTP ' . $http_code );
        }
    
        // Decode JSON response if applicable
        $response_data = json_decode( wp_remote_retrieve_body( $response ), true );
        if ( json_last_error() !== JSON_ERROR_NONE ) {
            wp_send_json_error( 'JSON decode error: ' . json_last_error_msg() );
        }
    
   // Save the response data in the WordPress options table
        if ( ! empty( $response_data ) ) {
            update_option( 'unleash_ai_registration_response', wp_json_encode( $response_data ) );
        }


    // Send a JSON response
    wp_send_json_success( $response_data );
        // Terminate script execution
        die();
    }
    
    
    public function unleash_ai_plug_login_portal() {
       // Verify nonce to protect against CSRF attacks
if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] )), 'update_meta_nonce' ) ) {
    wp_send_json_error( 'Invalid nonce.' );
}

// Sanitize and validate form data
$username = isset( $_POST['username'] ) ? sanitize_text_field( wp_unslash( $_POST['username'] ) ) : '';
$email = get_option( 'admin_email' );
$password = isset( $_POST['password'] ) ? sanitize_text_field( wp_unslash( $_POST['password'] ) ) : '';

        // Prepare data to send in the request
        $request_data = array(
            'password' => $password,
        );
    
        // Add email or username if provided
        if ( ! empty( $email ) ) {
            $request_data['customer_email'] = $email;
        }
        if ( ! empty( $username ) ) {
            $request_data['username'] = $username;
        }
    
        // Convert data to JSON format
        $json_data = wp_json_encode( $request_data );
    
        // Use wp_remote_post instead of cURL for better compatibility with WordPress
        $response = wp_remote_post(
            'https://unleashai.co/api/customers/login',
            array(
                'method'    => 'POST',
                'body'      => $json_data,
                'headers'   => array(
                    'Accept'       => 'application/json',
                    'Content-Type' => 'application/json',
                ),
                'timeout'   => 45, // Set a timeout for the request
                'sslverify' => true, // Disable SSL verification

            )
        );
    
        // Check for any errors with the request
        if ( is_wp_error( $response ) ) {
            wp_send_json_error( 'Request failed: ' . $response->get_error_message() );
        }
    
        // Check the response status
        $http_code = wp_remote_retrieve_response_code( $response );
        if ( $http_code !== 201 ) {
            wp_send_json_error( 'Failed to login: HTTP ' . $http_code );
        }
    
        // Decode JSON response if applicable
        $response_data = json_decode( wp_remote_retrieve_body( $response ), true );
        if ( json_last_error() !== JSON_ERROR_NONE ) {
            wp_send_json_error( 'JSON decode error: ' . json_last_error_msg() );
        }
    
          // Save the response data in the WordPress options table
          if ( ! empty( $response_data ) ) {
            update_option( 'unleash_ai_registration_response', wp_json_encode( $response_data ) );
        }
        // Return the response data as JSON
        wp_send_json_success($response_data);
  

    
        // Terminate script execution
        die();
    }
    
    /**
 * Handles the logout process for the AI plugin and clears the admin response meta.
 * Verifies the nonce for security and ensures the current user is an administrator.
 */

public function unleash_ai_plug_logout_portal() {
 // Verify nonce for security
if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] )), 'update_meta_nonce' ) ) {
    wp_send_json_error( 'Invalid nonce.' );
}

    // Check if the user is logged in and is an administrator
    if ( is_user_logged_in() && current_user_can( 'administrator' ) ) {
        // Remove the global option for the registration response
        $option_key = 'unleash_ai_registration_response';

        // Check if the option exists and delete it
        if ( get_option( $option_key ) ) {
            delete_option( $option_key );
        }
    } else {
        // If the user is not logged in or is not an administrator
        wp_send_json_error( 'Unauthorized access.' );
    }

    // Send a success response
    wp_send_json_success( 'Logout successful and option removed.' );
}



/**
 * Register custom REST API routes.
 * 
 * This function registers multiple custom REST API routes to handle different functionalities.
 * Each route is tied to a callback function and permission callback to ensure proper access control.
 */
public function unleash_ai_register_routes() {

    // Route to get secure data with POST request
    register_rest_route('cg_meta_al/v1', '/secure-data', [
        'methods' => 'POST',
        'callback' => [$this, 'unleash_ai_get_secure_data'],
        'permission_callback' => [$this, 'unleash_ai_validate_custom_api_token'],  // Custom permission validation
    ]);

    // Route to get a custom list of post meta with POST request
    register_rest_route('cg_meta_al/v1', '/get-custom-post-meta-list', [
        'methods' => 'POST',
        'callback' => [$this, 'unleash_ai_get_custom_post_meta_list'],
        'permission_callback' => [$this, 'unleash_ai_validate_custom_api_token'],  // Custom permission validation
    ]);

    // Route to fetch SEO plugins information with GET request
    register_rest_route('cg_meta_al/v1', '/seo-plugins', [
        'methods' => 'GET',
        'callback' => [$this, 'unleash_ai_seo_plugins_api_callback'],
        'permission_callback' => [$this, 'unleash_ai_validate_custom_api_token'],  // Custom permission validation
    ]);

    // Route to update custom post meta with POST request
    register_rest_route('cg_meta_al/v1', '/update-custom-post-meta-api', [
        'methods'  => 'POST',
        'callback' => [$this, 'unleash_ai_handle_update_meta_api'],
        'permission_callback' => [$this, 'unleash_ai_validate_custom_api_token'],  // Custom permission validation
    ]);

    // Route to generate custom API token with POST request (no authentication needed)
    register_rest_route('custom-api/v1', '/generate-token', [
        'methods' => 'POST',
        'callback' => [$this, 'unleash_ai_generate_custom_api_token'],
        'permission_callback' => [$this, 'unleash_ai_check_request_origin'],
    ]);
}


/**
 * Check if the request is coming from the allowed secret key.
 *
 * @return bool
 */
public function unleash_ai_check_request_origin($request) {
    $parameters = $request->get_params();
        $secret_key = get_option('unleash_ai_secret_key');
        
        // Validate the shared secret
        $shared_secret = isset($parameters['secret']) ? $parameters['secret'] : null;
        if ($shared_secret !== $secret_key) {
            return false;
        }
    // Deny access if secret key does not match
    return true;
}

/**
 * Get secure data after validating custom API token.
 *
 * This function validates the JWT token and retrieves secure user data.
 * If the token is valid, it returns the secure data; otherwise, it returns an error.
 * 
 * @param WP_REST_Request $request The REST request object.
 * 
 * @return WP_REST_Response|WP_Error The response containing secure data or error.
 */
public function unleash_ai_get_secure_data($request) {
    // Validate the custom API token and get user data
    $user_data = $this->unleash_ai_validate_custom_api_token();

    // If JWT verification failed, return the error message
    if (is_wp_error($user_data)) {
        return $user_data;  // Return the WP_Error object
    }

    // Check that user data is either an array or object
    if (!is_array($user_data) && !is_object($user_data)) {
        return new \WP_Error(
            'invalid_data', 
            'User data must be an array or object.', 
            array('status' => 400)
        );
    }

    // Return a success response with secure data
    return new WP_REST_Response(
        array(
            'message' => 'This is secure data.',  // Optional message
            'data'    => $user_data,             // The secure user data
        ), 
        200 // HTTP status code for successful response
    );
}


public function unleash_ai_get_custom_post_meta_list($request) {
    global $wpdb;
    if (is_string($request)) {
        $data = json_decode($request, true); // Decode JSON if a string is passed
    } else {
        $data = $request->get_json_params(); // Use this if a request object is passed
    }
    $paged = isset($data['paged']) ? max(1, (int)$data['paged']) : 1;
    $PostPerPage = isset($data['PostPerPage']) ? max(1, (int)$data['PostPerPage']) : 8;
    $post_type = isset($data['post_type']) ? $data['post_type'] : 'post';
    $plgactive = isset($data['plgactive']) ? $data['plgactive'] : '';

    if ($post_type === 'attachment') {
        global $wpdb;
    
        // Get all published posts/pages
        $all_posts = $wpdb->get_col("
            SELECT DISTINCT p.ID
            FROM {$wpdb->posts} p
            WHERE p.post_type IN ('page', 'post') AND p.post_status = 'publish'
        ");
    
        $filtered_posts = [];
    
        foreach ($all_posts as $post_id) {
            // Extract images from post content using the improved method
            $content = get_post_field('post_content', $post_id);
            preg_match_all('/<img[^>]+src=["\'](.*?)["\']/', $content, $matches);
            $image_ids = [];
    
            if (!empty($matches[1])) {
                foreach ($matches[1] as $image_url) {
                    // Retrieve image ID using the URL
                    $attachment_id = attachment_url_to_postid($image_url);
                    if ($attachment_id) {
                        $image_ids[] = $attachment_id;
                    }
                }
            }
    
            // Add featured image if available
            $featured_image_id = get_post_thumbnail_id($post_id);
            if ($featured_image_id) {
                $image_ids[] = $featured_image_id;
            }
    
            // Ensure unique image IDs
            $image_ids = array_unique($image_ids);
    
            // Only include posts/pages with images
            if (!empty($image_ids)) {
                $filtered_posts[] = $post_id;
            }
        }
    
        // Total count of filtered posts/pages
        $total_results = count($filtered_posts);
    
        // Pagination
        $offset = ($paged - 1) * $PostPerPage;
        $paginated_post_ids = array_slice($filtered_posts, $offset, $PostPerPage);
    
        if (empty($paginated_post_ids)) {
            return new WP_REST_Response([
                'status' => 200,
                'message' => 'No results found',
                'post_type' => 'attachment_with_pages',
                'total_result' => 0,
                'per_page' => $PostPerPage,
                'page' => $paged,
                'data' => [],
            ], 200);
        }
    
        // Fetch paginated posts/pages
        $pages_query = new \WP_Query([
            'post__in'       => $paginated_post_ids,
            'post_type'      => ['page', 'post'],
            'post_status'    => 'publish',
            'orderby'        => 'post__in',
            'posts_per_page' => -1,
        ]);
    
        $page_data_list = [];
    
        while ($pages_query->have_posts()) : $pages_query->the_post();
            $page_id = get_the_ID();
            $attachments = [];
            $content = get_post_field('post_content', $page_id);
    
            // Extract image IDs from content
            preg_match_all('/<img[^>]+src=["\'](.*?)["\']/', $content, $matches);
            $image_ids = [];
    
            if (!empty($matches[1])) {
                foreach ($matches[1] as $image_url) {
                    $attachment_id = attachment_url_to_postid($image_url);
                    if ($attachment_id) {
                        $image_ids[] = $attachment_id;
                    }
                }
            }
    
            // Add the featured image ID
            $featured_image_id = get_post_thumbnail_id($page_id);
            if ($featured_image_id) {
                $image_ids[] = $featured_image_id;
            }
    
            // Remove duplicate IDs
            $image_ids = array_unique($image_ids);
    
            // Fetch image details
            $table_name = $wpdb->prefix . 'ai_alt_tags';
    
            foreach ($image_ids as $image_id) {
                // Fetch alt text from custom table or post meta
                $alt_text = $wpdb->get_var(
                    $wpdb->prepare("SELECT alt_text FROM $table_name WHERE image_id = %d AND page_id = %d", $image_id, $page_id)
                );
    
                if (empty($alt_text)) {
                    $alt_text = get_post_meta($image_id, '_wp_attachment_image_alt', true);
                }
    
                $file_url = wp_get_attachment_url($image_id);
                $file_extension = strtolower(pathinfo($file_url, PATHINFO_EXTENSION));
    
                // Exclude certain file types
                $excluded_extensions = ['mp4', 'pdf', 'svg', 'tiff'];
                if (in_array($file_extension, $excluded_extensions)) {
                    continue;
                }
    
                $attachments[] = [
                    "post_id" => $image_id,
                    "url" => $file_url,
                    "alt_tag" => $alt_text,
                ];
            }
    
            // Skip if no attachments
            if (empty($attachments)) {
                continue;
            }
    
            $page_data_list[] = [
                "post_id" => $page_id,
                "post_title" => get_the_title($page_id),
                "post_slug" => basename(get_permalink($page_id)),
                "post_url" => esc_url(get_permalink($page_id)),
                "post_content" => $content,
                "attachments" => $attachments,
            ];
        endwhile;
        wp_reset_postdata();
    
        return new WP_REST_Response([
            'status' => 200,
            'message' => 'Success',
            'post_type' => 'attachment_with_pages',
            'total_result' => (int)$total_results,
            'per_page' => $PostPerPage,
            'page' => $paged,
            'data' => $page_data_list,
        ], 200);
    }
    

    // Default logic for non-attachment post types
    $post_status = $post_type === 'attachment' ? 'inherit' : 'publish';
    $args = [
        'post_type'      => $post_type,
        'post_status'    => $post_status,
        'posts_per_page' => $PostPerPage,
        'paged'          => $paged,
    ];

    $query = new \WP_Query($args);
    $meta_data_list = [];

    while ($query->have_posts()) : $query->the_post();
        $post_id = get_the_ID();
        $post_title = get_the_title();
        $post_content = get_the_content();
        $post_slug = basename(get_permalink());
        $post_url = esc_url(get_permalink($post_id));

        // Fetch SEO data based on active plugin
        $seo_title = get_post_meta($post_id, '_yoast_wpseo_title', true);
         $seo_description = get_post_meta($post_id, '_yoast_wpseo_metadesc', true);
        switch ($plgactive) {
            case "cg_aioseo":
            case "cg_yoast":
                $seo_title = get_post_meta($post_id, '_yoast_wpseo_title', true);
                $seo_description = get_post_meta($post_id, '_yoast_wpseo_metadesc', true);
                break;
            case "cg_rank_math":
                $seo_title = get_post_meta($post_id, 'rank_math_title', true);
                $seo_description = get_post_meta($post_id, 'rank_math_description', true);
                break;
        }

        $meta_data_list[] = [
            "post_id" => $post_id,
            "post_title" => $post_title,
            "post_content" => $post_content,
            "post_slug" => $post_slug,
            "post_url" => $post_url,
            "seo_title" => $seo_title,
            "seo_description" => $seo_description,
        ];
    endwhile;
    wp_reset_postdata();

    // Calculate total results without filtering
    $queryTotal = new \WP_Query([
        'post_type' => $post_type,
        'post_status' => $post_status,
        'posts_per_page' => -1,
    ]);
    $total_results = $queryTotal->found_posts;
    wp_reset_postdata();

    // Prepare the response
    return new WP_REST_Response([
        'status' => 200,
        'message' => 'Success',
        'post_type' => $post_type,
        'total_result' => $total_results,
        'per_page' => $PostPerPage,
        'page' => $paged,
        'data' => $meta_data_list,
    ], 200);
}

function unleash_ai_get_installed_seo_plugins() {
    $active_plugins = get_option('active_plugins');
    $seo_plugins = [
        'wordpress-seo/wp-seo.php' => array('plugin_name' => 'Yoast SEO', 'api_name' => 'cg_yoast'),
        'all-in-one-seo-pack/all_in_one_seo_pack.php' => array('plugin_name' => 'All in One SEO', 'api_name' => 'cg_aioseo'),
        'rank-math/rank-math.php' => array('plugin_name' => 'Rank Math SEO', 'api_name' => 'cg_rank_math'),
    ];

    $installed_seo_plugins = [];
    
    // Check each plugin in the $seo_plugins list
    foreach ($seo_plugins as $plugin_file => $plugin_info) {
        // Check if the plugin is active
        if (in_array($plugin_file, $active_plugins)) {
            $installed_seo_plugins[] = $plugin_info;
        }
    }

    // Optionally, return the installed SEO plugins with additional info such as plugin version
    $detailed_plugins = [];
    foreach ($installed_seo_plugins as $plugin) {
        $plugin_data = get_plugin_data(WP_PLUGIN_DIR . '/' . $plugin_file);
        $detailed_plugins[] = array_merge($plugin, ['version' => $plugin_data['Version']]);
    }

    return $installed_seo_plugins;
}

    // Create the API endpoint callback
function unleash_ai_seo_plugins_api_callback() {
    // Fetch installed SEO plugins
    $seo_plugins_installed = $this->unleash_ai_get_installed_seo_plugins();

    // Check if any SEO plugins are installed and return appropriate response
    if (!empty($seo_plugins_installed)) {
        $result = array(
            'status' => 200,
            'message' => 'Success',
            'total_result' => count($seo_plugins_installed),
            'data' => $seo_plugins_installed
        );
    } else {
        $result = array(
            'status' => 200, // Changed to 200 as it's a successful API call
            'message' => 'No SEO plugins found.',
            'total_result' => 0,
            'data' => $seo_plugins_installed
        );
    }

    // Optionally log the result for debugging purposes
    //error_log(print_r($result, true));

    // Return the response as JSON
    return new WP_REST_Response($result, 200);
}

    public function unleash_ai_handle_update_meta_api($request) {
        // Retrieve JSON parameters
        $data = $request->get_json_params();
    
        // Extract parameters with proper validation
        $post_id = isset($data['post_id']) ? sanitize_text_field($data['post_id']) : '';
        $meta_title = isset($data['meta_title']) ? sanitize_text_field($data['meta_title']) : '';
        $meta_description = isset($data['meta_description']) ? sanitize_textarea_field($data['meta_description']) : '';
        $alt_tag = isset($data['alt_tag']) ? sanitize_text_field($data['alt_tag']) : '';
        $image_id = isset($data['image_id']) ? intval($data['image_id']) : '';
    
        // Validate required parameters
        if (empty($post_id)) {
            return new \WP_Error('missing_post_id', 'Post ID is required.', ['status' => 400]);
        }
    
       // Skip metadata checks if `image_id` is provided
        if (empty($image_id)) {
            // Ensure at least one metadata field is provided
            if (empty($meta_title) && empty($meta_description) && empty($alt_tag)) {
                return new \WP_Error('missing_meta', 'Provide at least a meta title or description.', ['status' => 400]);
            }
        }
        // Prepare the payload data
        $payload = [
            'action'         => 'update_meta_action',
            'nonce'          => wp_create_nonce('update_meta_nonce'),
            'pageID'         => $post_id,
            'metaTitle'      => $meta_title,
            'metaDescription'=> $meta_description,
            'altTag'         => $alt_tag,
            'image_id'       => $image_id,
            'jwt_loggedin'   => 1
        ];
        
        // Set up the arguments for wp_remote_post
        $args = [
            'body'        => http_build_query($payload),  // Format data as a query string
            'timeout'     => 15,                          // Optional: set a timeout
            'httpversion' => '1.1',                       // Optional: specify HTTP version
        ];
        
        // Send the POST request using wp_remote_post
        $response = wp_remote_post(admin_url('admin-ajax.php'), $args);
        
        // Check for errors in the response
        if (is_wp_error($response)) {
            $error_msg = $response->get_error_message();
            return new \WP_Error('wp_remote_error', $error_msg, ['status' => 500]);
        }
        
        // Retrieve the response body
        $response_body = wp_remote_retrieve_body($response);
        
        // Decode the JSON response
        $response_data = json_decode($response_body, true);
        
        // Check for a valid response and if 'success' is set
        if (!is_array($response_data) || !isset($response_data['success'])) {
            return new \WP_Error('invalid_response', 'Invalid response from server.', ['status' => 500]);
        }
        
        // Return the successful response
       // return $response_data;
        
    
        // Format response based on success
        if ($response_body['success']) {
            $result = [
                'status' => 200,
                'success' => true,
                'message' => $response_body['data'] ?? 'Meta updated successfully.',
            ];
        } else {
            $result = [
                'status' => 400,
                'success' => false,
                'message' => $response_body['data'] ?? 'Failed to update meta.',
            ];
        }
    
        // Return the REST response
        return new WP_REST_Response($result, $result['status']);
    }
    

    function unleash_ai_generate_custom_api_token($request) {
        $parameters = $request->get_params();
        $secret_key = get_option('unleash_ai_secret_key');
        
        // Validate the shared secret
        $shared_secret = isset($parameters['secret']) ? $parameters['secret'] : null;
        if ($shared_secret !== $secret_key) {
            return new \WP_Error('invalid_secret', 'Invalid secret provided.', array('status' => 401));
        }
        
        // Global database access
        global $wpdb;
        $table_name = $wpdb->prefix . 'custom_api_tokens';
    
        // Check if a token already exists
        $existing_token = $wpdb->get_row(
            "SELECT token, expires FROM $table_name LIMIT 1",
            ARRAY_A
        );
    
        if ($existing_token) {
            // Return the existing token if it is still valid
            return array(
                'token' => $existing_token['token'],
                'expires' => $existing_token['expires'],
            );
        }
    
        // Generate a new token
        $token = bin2hex(random_bytes(32));
        $expiration = time() + (60 * 60 * 24 * 365 * 50); // 50 years expiration
        $stored_response = get_option( 'unleash_ai_registration_response' );
  
        $response = array();
       
        if ($stored_response) {
            $response_array = json_decode($stored_response, true);
    
            // Get the username and API token from the response array
            if (isset($response_array['username'])) {
                $username = $response_array['username'];
              
            }
        }
       
    
        // Insert the new token into the database
        $wpdb->insert(
            $table_name,
            array(
                'token' => $token,
                'expires' => $expiration,
                'username'=>  $username 
               
            ),
            array('%s', '%d')
        );
    
        // Return the new token
        return array(
            'token' => $token,
            'expires' => $expiration,
        );
    }
    
    
    public function unleash_ai_get_secret_key() {
        // Retrieve the secret key from the options table
        $secret_key = get_option('unleash_ai_secret_key');
        
        // If the secret key does not exist, generate and save a new one
        if (!$secret_key) {
            $secret_key = wp_generate_password(32, false, false);
            update_option('unleash_ai_secret_key', $secret_key);
        }
    
        return $secret_key;
    }
    
    function unleash_ai_regenerate_secret_key() {
        global $wpdb;
    
        // Delete all tokens from the custom_api_tokens table
        $table_name = $wpdb->prefix . 'custom_api_tokens';
        $wpdb->query("DELETE FROM $table_name");
    
        // Generate a new secret key
        $new_secret_key = wp_generate_password(32, false, false);
    
        // Update the option with the new key
        update_option('unleash_ai_secret_key', $new_secret_key);
    
        return $new_secret_key;
    }
    
    function unleash_ai_fetch_token() {
        global $wpdb;
    
        // Fetch the token and its expiration from the database
        $table_name = $wpdb->prefix . 'custom_api_tokens';
        $current_time = time(); // Current Unix timestamp
    
        // Query to fetch the token and its expiration for active and valid tokens
        $token_data = $wpdb->get_row(
            $wpdb->prepare(
                "SELECT token, expires, username
                 FROM $table_name 
                 WHERE expires > %d
                 LIMIT 1",
                $current_time
            ),
            ARRAY_A
        );
    
        // Check if a valid token exists
        if ($token_data) {
            $token = $token_data['token'];
            $expires = $token_data['expires'];
         
    
            // Calculate remaining time
            $remaining_time = $expires - $current_time;
    
            // Return the token and remaining time (optional if needed)
            return array(
                'token' => $token,
              
                'expires_in' => $remaining_time,
            );
        } else {
            // No valid token found or all tokens are expired
            return false;
        }
    }
    
    
    function unleash_ai_validate_custom_api_token() {
       // Check if the result already has an error
    /*if (is_wp_error($result)) {
        return $result;  // If the result already has an error, pass it along
    }*/

    
        $headers = getallheaders();
        $auth_header = isset($headers['Authorization']) ? $headers['Authorization'] : null;
    
        if (!$auth_header || strpos($auth_header, 'Bearer ') !== 0) {
            return new \WP_Error('missing_token', 'Authorization header with Bearer token is required.', array('status' => 401));
        }
    
        $token = substr($auth_header, 7); // Extract the token
    
        global $wpdb;
        $table_name = $wpdb->prefix . 'custom_api_tokens';
    
        $row = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM $table_name WHERE token = %s",
            $token
        ));
    
        if (!$row || time() > $row->expires) {
            return new \WP_Error('invalid_token', 'Invalid or expired token.', array('status' => 401));
        }

        // Fetch admin user details
    $user = get_user_by('ID', 1); // Assuming the first admin user
    if (!$user || !in_array('administrator', $user->roles)) {
      //  return new \WP_Error('not_admin', 'User is not an administrator.', array('status' => 403));
      return true; // Token is valid
    } else {
    // Return admin user details
    return array(
        'ID' => $user->ID,
        'email' => $user->user_email,
    );

    }

    
       
    }
    
   public function unleash_ai_update_image_alt_tags($content) {
        global $wpdb;
   // Skip this function when `tagverify` is set to '1'
    if (isset($_GET['tagverify']) && $_GET['tagverify'] === '1') {
        return $content;
    }
        // Get the current post/page ID (Ensure proper context)
        if (!is_single() && !is_page()) {
            return $content; // No valid post context
        }
    
        $page_id = get_the_ID();
        if (!$page_id) return $content;
    
        // Find all image tags in the content
        $pattern = '/<img[^>]+>/i';
        preg_match_all($pattern, $content, $images);
    
        if (isset($images[0])) {
            foreach ($images[0] as $img_tag) {
                // Try to extract the image ID from the "wp-image-{ID}" class
                if (preg_match('/wp-image-(\d+)/', $img_tag, $matches)) {
                    $image_id = $matches[1];
                } else {
                    // Try to get the image ID from the src URL (if it's a direct image URL)
                    if (preg_match('/src="([^"]+)"/', $img_tag, $src_matches)) {
                        $image_url = $src_matches[1];
                        $image_id = attachment_url_to_postid($image_url);
                    } else {
                        continue; // If no image ID can be extracted, skip
                    }
                }
    
                // Retrieve the custom alt text for this image on this page
                $table_name = $wpdb->prefix . 'ai_alt_tags';
                $alt_text = $wpdb->get_var(
                    $wpdb->prepare("SELECT alt_text FROM $table_name WHERE image_id = %d AND page_id = %d", $image_id, $page_id)
                );
    
                if ($alt_text) {
                    // Replace or add the alt attribute in the image tag
                    $updated_img_tag = preg_replace('/alt="[^"]*"/i', 'alt="' . esc_attr($alt_text) . '"', $img_tag);
                    
                    // If no alt attribute was found, we can add it
                    if ($updated_img_tag === $img_tag) {
                        $updated_img_tag = preg_replace('/<img(.*?)>/i', '<img$1 alt="' . esc_attr($alt_text) . '">', $img_tag);
                    }
    
                    // Replace the original image tag with the updated one in the content
                    $content = str_replace($img_tag, $updated_img_tag, $content);
                }
            }
        }
    
        // Return the modified content
        return $content;
    }
    
   
    
}
