<?php 
if ( ! defined( 'ABSPATH' ) ) exit; // Thoát nếu truy cập trực tiếp
if (!class_exists('Aiautotool_Canonical')) {
class Aiautotool_Canonical extends rendersetting {
    public  $active = true;
    public  $active_option_name = 'Aiautotool_Canonical_active';
    public  $usage_option_name = 'Canonical_AI_usage';
    public  $icon = '<i class="fa-regular fa-clock"></i>';
   
    protected $postfields = array();
    protected $shortcodes = array();
    protected $htmltags = array();
    public $limit = AIAUTOTOOL_FREE;
    private $plan_limit_aiautotool ;
    public $name_plan ;
    public $config = array();
    public $notice ;
    
    // Static flag to prevent duplicate menu registration
    private static $menu_registered = false;
    
    public function __construct() {
        
        $this->name_plan =  __('Canonical URL Manager & Auto Post Cleanup','ai-auto-tool');
        $this->plan_limit_aiautotool =  'plan_limit_aiautotool_'.$this->active_option_name;
        
        $this->notice = new aiautotool_Warning_Notice();
        $this->active = get_option($this->active_option_name, true);
        if ($this->active=='true') {
            $this->init();
        }
        add_action('init', array($this,'redirect'), 1);
        add_action('wp_ajax_update_active_option_canonical_'.$this->active_option_name, array($this, 'update_active_option_callback'));


    }

public function update_active_option_callback() {
    check_ajax_referer('aiautotool_nonce', 'security');
    
    if (!current_user_can('manage_options')) {
        wp_die(__('Permission denied', 'ai-auto-tool'), '', array('response' => 403));
    }
    
    if (isset($_POST['active'])) {
        $active = sanitize_text_field($_POST['active']);
        update_option($this->active_option_name, $active,null, 'no');
        print_r($active);
    }

    wp_die();
}

public function init(){
    add_action('admin_menu', array($this, 'add_menu'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_scripts'));
        add_action('wp_ajax_aiautotool_search_posts', array($this, 'search_posts'));
        add_action('wp_ajax_aiautotool_save_canonical', array($this, 'save_canonical'));

        add_action('wp_ajax_aiautotool_del_canonical', array($this, 'del_canonical'));
        // add_action('init', array($this, 'schedule_cron_job'));


        add_filter('cron_schedules', array($this, 'aiautotool_canonical_intervals'));

        if (!wp_next_scheduled('aiautotool_canonical_event')) {
            wp_schedule_event(time(), 'aiautotool_canonical_intervals', 'aiautotool_canonical_event');
            
        }

        add_action('aiautotool_canonical_event', array($this, 'aiautotool_canonical_cron'));
}
 public function aiautotool_canonical_intervals($schedules) {
        $translate_interval = get_option('aiautotool_canonical_public_time', 5);
        $schedules['aiautotool_canonical_intervals'] = array(
            'interval' => $translate_interval * 60, 
            'display' => 'aiautotool canonical Interval'
        );
        return $schedules;
    }
    public function add_menu() {
        // Prevent duplicate menu registration
        if (self::$menu_registered) {
            return;
        }
        self::$menu_registered = true;
       
        add_submenu_page(
            MENUSUBPARRENT,
            '<i class="fa-solid fa-link"></i> ' . esc_html__('Canonical Manager', 'ai-auto-tool'),
            '<i class="fa-solid fa-link"></i> ' . esc_html__('Canonical Manager', 'ai-auto-tool'),
            'manage_options',
            'aiautotool_canonical',
            array($this, 'aiautotool_canonical')
        );
        add_submenu_page(
            MENUSUBPARRENT,
            '<i class="fa-solid fa-arrow-turn-up"></i> ' . esc_html__('301 Redirects', 'ai-auto-tool'),
            '<i class="fa-solid fa-arrow-turn-up"></i> ' . esc_html__('301 Redirects', 'ai-auto-tool'),
            'manage_options',
            'aiautotool_301_edirect',
            array($this, 'canonical_301_redirect')
        );
    }
    public function del_canonical(){
        check_ajax_referer('aiautotool_nonce', 'security');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
        }
        
        $ids = sanitize_text_field($_POST['ids']);

        if ($ids<0) {
            wp_send_json_error(array('message' => 'Error id'));
        }
        $canonical_data = get_option('aiautotool_canonical_data');
        if(isset($canonical_data[$ids])){
            unset($canonical_data[$ids]);
            update_option('aiautotool_canonical_data',$canonical_data,null, 'no');
            wp_send_json_success($canonical_data);
        }
        wp_send_json_success(array('msg'=>'No action'));

    }
    public function aiautotool_canonical(){

        $canonical_data = get_option('aiautotool_canonical_data',array());
       

        
        ?>
        <div id="" class="wrap aiautotool_container" style="">
        <div class="aiautotool_left">
            <div class="ft-box">
                <div class="ft-menu">
                     <div class="ft-logo"><img src="<?php echo esc_url(defined('AIAUTOTOOL_URI') ? AIAUTOTOOL_URI . 'images/logo.svg' : plugins_url('../../../images/logo.svg', __FILE__)); ?>">
                    <br>Canonical URL Manager</div>
                </div>
                <div class="ft-main">
        
        <!-- Feature Description Header -->
        <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 25px; border-radius: 10px; margin-bottom: 25px; color: white; box-shadow: 0 4px 15px rgba(0,0,0,0.1);">
            <h1 style="margin: 0 0 15px 0; color: white; font-size: 28px; display: flex; align-items: center; gap: 12px;">
                <i class="fa-solid fa-link"></i> <?php echo esc_html__('Canonical URL Manager & Auto Post Cleanup', 'ai-auto-tool'); ?>
            </h1>
            <p style="margin: 0 0 10px 0; font-size: 16px; line-height: 1.6; opacity: 0.95;">
                <?php echo esc_html__('Manage duplicate content intelligently by setting canonical URLs for multiple posts, scheduling automatic post deletion, and implementing 301 redirects to preserve SEO value.', 'ai-auto-tool'); ?>
            </p>
        </div>

        <!-- Benefits Section -->
        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 15px; margin-bottom: 25px;">
            <div style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); padding: 20px; border-radius: 8px; color: white; box-shadow: 0 3px 10px rgba(0,0,0,0.1);">
                <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 10px;">
                    <i class="fa-solid fa-shield-halved" style="font-size: 24px;"></i>
                    <h3 style="margin: 0; font-size: 16px;"><?php echo esc_html__('Avoid Duplicate Content', 'ai-auto-tool'); ?></h3>
                </div>
                <p style="margin: 0; font-size: 13px; opacity: 0.95; line-height: 1.5;">
                    <?php echo esc_html__('Tell search engines which version of similar content is the original to prevent SEO penalties.', 'ai-auto-tool'); ?>
                </p>
            </div>

            <div style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); padding: 20px; border-radius: 8px; color: white; box-shadow: 0 3px 10px rgba(0,0,0,0.1);">
                <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 10px;">
                    <i class="fa-solid fa-clock-rotate-left" style="font-size: 24px;"></i>
                    <h3 style="margin: 0; font-size: 16px;"><?php echo esc_html__('Auto Cleanup & Redirect', 'ai-auto-tool'); ?></h3>
                </div>
                <p style="margin: 0; font-size: 13px; opacity: 0.95; line-height: 1.5;">
                    <?php echo esc_html__('Automatically delete old posts after a set period and redirect traffic via 301 to maintain link value.', 'ai-auto-tool'); ?>
                </p>
            </div>

            <div style="background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%); padding: 20px; border-radius: 8px; color: white; box-shadow: 0 3px 10px rgba(0,0,0,0.1);">
                <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 10px;">
                    <i class="fa-solid fa-chart-line" style="font-size: 24px;"></i>
                    <h3 style="margin: 0; font-size: 16px;"><?php echo esc_html__('Preserve SEO Value', 'ai-auto-tool'); ?></h3>
                </div>
                <p style="margin: 0; font-size: 13px; opacity: 0.95; line-height: 1.5;">
                    <?php echo esc_html__('Consolidate ranking signals from multiple URLs into one authoritative page for better search performance.', 'ai-auto-tool'); ?>
                </p>
            </div>
        </div>

        <!-- How It Works Section -->
        <div style="background: #f8f9fa; border-left: 4px solid #667eea; padding: 20px; border-radius: 8px; margin-bottom: 25px;">
            <h3 style="margin: 0 0 15px 0; color: #333; display: flex; align-items: center; gap: 10px;">
                <i class="fa-solid fa-circle-info"></i> <?php echo esc_html__('How It Works', 'ai-auto-tool'); ?>
            </h3>
            <div style="display: grid; gap: 12px;">
                <div style="display: flex; gap: 12px; align-items: start;">
                    <span style="background: #667eea; color: white; width: 28px; height: 28px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: bold; flex-shrink: 0;">1</span>
                    <div>
                        <strong><?php echo esc_html__('Search & Select Posts:', 'ai-auto-tool'); ?></strong> <?php echo esc_html__('Find and select multiple posts with duplicate or similar content', 'ai-auto-tool'); ?>
                    </div>
                </div>
                <div style="display: flex; gap: 12px; align-items: start;">
                    <span style="background: #667eea; color: white; width: 28px; height: 28px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: bold; flex-shrink: 0;">2</span>
                    <div>
                        <strong><?php echo esc_html__('Set Canonical URL:', 'ai-auto-tool'); ?></strong> <?php echo esc_html__('Define the primary URL that should receive all SEO credit', 'ai-auto-tool'); ?>
                    </div>
                </div>
                <div style="display: flex; gap: 12px; align-items: start;">
                    <span style="background: #667eea; color: white; width: 28px; height: 28px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: bold; flex-shrink: 0;">3</span>
                    <div>
                        <strong><?php echo esc_html__('Schedule Auto-Delete (Optional):', 'ai-auto-tool'); ?></strong> <?php echo esc_html__('Set a timeframe (1 day to 1 month) to automatically delete duplicate posts', 'ai-auto-tool'); ?>
                    </div>
                </div>
                <div style="display: flex; gap: 12px; align-items: start;">
                    <span style="background: #667eea; color: white; width: 28px; height: 28px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: bold; flex-shrink: 0;">4</span>
                    <div>
                        <strong><?php echo esc_html__('Auto 301 Redirect:', 'ai-auto-tool'); ?></strong> <?php echo esc_html__('When posts are deleted, automatic 301 redirects ensure visitors and search engines find the canonical URL', 'ai-auto-tool'); ?>
                    </div>
                </div>
            </div>
        </div>

        <h1 class="wp-heading-inline" style="display: flex; align-items: center; gap: 10px; margin-bottom: 20px;">
            <img src="<?php echo esc_url(defined('AIAUTOTOOL_URI') ? AIAUTOTOOL_URI . 'images/logo.svg' : plugins_url('../../../images/logo.svg', __FILE__)); ?>" width="24px" height="24px" /> 
            <?php echo esc_html__('Canonical Management Dashboard', 'ai-auto-tool'); ?>
        </h1>
        <div >
            <div  id="aiautotool_post_form" class="wrap aiautotool_container">
                <?php self::render_search_canonical_setting();?>
                <div class="aiautotool_canonical_container">
                    <div class="aiautotool_canonical_box_left">
                        <h3 style="display: flex; align-items: center; gap: 10px; margin-bottom: 15px;">
                            <i class="fa-solid fa-list"></i> <?php echo esc_html__('Canonical URL List', 'ai-auto-tool'); ?>
                        </h3>
                        <p style="color: #666; margin-bottom: 15px; font-size: 14px;">
                            <i class="fa-solid fa-circle-info"></i> <?php echo esc_html__('View and manage all your canonical URL configurations. Click on any URL to see detailed post information.', 'ai-auto-tool'); ?>
                        </p>
                        <table class="aiautotool_form_canonical_table">
            <thead>
                <tr>
                    <th class="aiautotool_form_canonical_th"><?php echo esc_html__('No.', 'ai-auto-tool'); ?></th>
                    <th class="aiautotool_form_canonical_th">
                        <i class="fa-solid fa-link"></i> <?php echo esc_html__('Target Canonical URL', 'ai-auto-tool'); ?>
                        <div style="font-weight: normal; font-size: 11px; opacity: 0.8;"><?php echo esc_html__('The primary URL receiving all SEO value', 'ai-auto-tool'); ?></div>
                    </th>
                    <th class="aiautotool_form_canonical_th">
                        <i class="fa-solid fa-file-lines"></i> <?php echo esc_html__('Posts', 'ai-auto-tool'); ?>
                        <div style="font-weight: normal; font-size: 11px; opacity: 0.8;"><?php echo esc_html__('(Pending/Processed)', 'ai-auto-tool'); ?></div>
                    </th>
                    <th class="aiautotool_form_canonical_th"><?php echo esc_html__('Action', 'ai-auto-tool'); ?></th>
                </tr>
            </thead>
            <tbody id="postList">
                <!-- Dữ liệu post sẽ được thêm vào đây -->
                <?php
                if(count($canonical_data)>0){
                    foreach($canonical_data as $key=>$item){
                    $post_ids = $item['post_id'];
                    $canonical_url = $item['canonical_url'];
                    if(isset($item['kq'])){
                        $kq = $item['kq'];
                    }else{
                        $kq = array();
                    }
                        ?>
                        <tr>
                            <td><?php echo esc_html($key);?></td>
                            <td><a data-json="<?php echo esc_html($key);?>" href="javascript:void(0);" onclick="showRightBox(this)"><?php echo esc_html($canonical_url);?></a></td>
                            <td>(<?php echo esc_html(count($post_ids)) ;?>/<?php echo esc_html(count($kq));?>) post</td>
                            <td><span data-ids=<?php echo esc_html($key); ?> type="button" class="aiautotool_btn btn_writer canonical_del "><i class="mce-ico mce-i-dashicon dashicons-del"></i> Del</span></td>

                        </tr>
                        <?php
                   }
                }
               
                 ?>
               
            </tbody>
        </table>
                       
                    </div>
                    <div class="aiautotool_canonical_box_right" id="aiautotool_canonical_box_right">
                        <h3 style="display: flex; align-items: center; gap: 10px; margin-bottom: 15px;">
                            <i class="fa-solid fa-circle-info"></i> <?php echo esc_html__('Detailed Post Information', 'ai-auto-tool'); ?>
                        </h3>
                        <p style="color: #666; margin-bottom: 15px; font-size: 14px;">
                            <?php echo esc_html__('Track the status of each post including canonical assignment, deletion status, and redirect setup.', 'ai-auto-tool'); ?>
                        </p>
                        <table  class="aiautotool_form_canonical_table">
                            <thead>
                                <tr>
                                    <th class="aiautotool_form_canonical_th"><?php echo esc_html__('Post ID', 'ai-auto-tool'); ?></th>
                                    <th class="aiautotool_form_canonical_th"><?php echo esc_html__('Post Title', 'ai-auto-tool'); ?></th>
                                    <th class="aiautotool_form_canonical_th">
                                        <?php echo esc_html__('Canonical URL', 'ai-auto-tool'); ?>
                                        <div style="font-weight: normal; font-size: 11px; opacity: 0.8;"><?php echo esc_html__('Target URL', 'ai-auto-tool'); ?></div>
                                    </th>
                                    <th class="aiautotool_form_canonical_th">
                                        <i class="fa-solid fa-trash"></i> <?php echo esc_html__('Deleted', 'ai-auto-tool'); ?>
                                        <div style="font-weight: normal; font-size: 11px; opacity: 0.8;"><?php echo esc_html__('Post removed?', 'ai-auto-tool'); ?></div>
                                    </th>
                                    <th class="aiautotool_form_canonical_th">
                                        <i class="fa-solid fa-arrow-turn-up"></i> <?php echo esc_html__('301 Active', 'ai-auto-tool'); ?>
                                        <div style="font-weight: normal; font-size: 11px; opacity: 0.8;"><?php echo esc_html__('Redirect setup?', 'ai-auto-tool'); ?></div>
                                    </th>
                                    <th class="aiautotool_form_canonical_th">
                                        <?php echo esc_html__('Canonical Set', 'ai-auto-tool'); ?>
                                        <div style="font-weight: normal; font-size: 11px; opacity: 0.8;"><?php echo esc_html__('When applied', 'ai-auto-tool'); ?></div>
                                    </th>
                                    <th class="aiautotool_form_canonical_th">
                                        <?php echo esc_html__('Scheduled Delete', 'ai-auto-tool'); ?>
                                        <div style="font-weight: normal; font-size: 11px; opacity: 0.8;"><?php echo esc_html__('When to remove', 'ai-auto-tool'); ?></div>
                                    </th>
                                </tr>
                            </thead>
                            <tbody id="tablelistkq">
                                <!-- Dữ liệu post sẽ được thêm vào đây -->
                            </tbody>
                            
                            
                            <!-- Thêm dữ liệu cho bảng bên phải ở đây -->
                        </table>
                       
                    </div>
                </div>

                <script>
                    var canonical_data = [<?php echo json_encode($canonical_data);?>]

                    function showRightBox(element) {
                        var jsonData = element.dataset.json;
                        var rightBox = document.getElementById("aiautotool_canonical_box_right");
                        rightBox.style.display = "block";
                        // var decodedData = JSON.parse(jsonData);
                        var kq = canonical_data[0][jsonData]['kq'];
                        const postList = document.getElementById('tablelistkq');
                        postList.innerHTML = '';
                        jQuery.each(kq, function(index, post) {
                        const row = document.createElement('tr');
                        row.innerHTML = `
                            <td>${post.post_id}</td>
                            <td><a href="${post.post_url}">${post.post_title}</a></td>
                            <td>${post.post_canonical}</td>
                            <td>${post.del_post}</td>
                            <td>${post.post_301}</td>
                            <td>${post.canonical_time_execute}</td>
                            <td>${post.time_del_post}</td>
                        `;
                        postList.appendChild(row);
                    }); 
                        console.log(kq);
                    }
               
                </script>
                <hr>
                
                <?php //self::render_search_canonical_setting();?>
</div>
</div>
<!-- xxx -->
</div>
</div>
</div>
</div>
<script>
    jQuery(document).ready(function ($) {

        $('.canonical_del').click(function(event){

            var ids = $(this).data('ids');
            
            if(ids>=0){
                var data = {
                    action: 'aiautotool_del_canonical',
                    ids: ids,
                    security:aiautotool_js_setting.security
                };
                $.post('<?php echo esc_url(admin_url('admin-ajax.php'));?>', data, function(response) {
                if (response.success) {
                        var results = response.data;
                      $(this).remove();
                       // const postList = document.getElementById('postList');
                       //  postList.innerHTML = '';
                       //  jQuery.each(results.data, function(index, item) {
                       //      const row = document.createElement('tr');
                       //      row.innerHTML = `
                       //          <td>${index}</td>
                       //          <td>${item.canonical_url}</td>
                       //          <td>(${item.post_id.length}) post</td>
                       //          <td><span data-ids="${index}" type="button" class="aiautotool_btn btn_writer canonical_del"><i class="mce-ico mce-i-dashicon dashicons-del"></i> Del</span></td>
                       //      `;
                       //      postList.appendChild(row);
                       //  }); 

                        

                       

                    } else {
                       
                    }
                });
            }
        })

    });
    
</script>
        <?php
    }
    public function enqueue_scripts() {
        global $post;
       $setting = new rendersetting();
        $aiautotool_canonical_data = get_option('aiautotool_canonical_data');
// Trong mã PHP của bạn, sau khi có $aiautotool_canonical_data
        wp_register_script('kct_cr_scriptx1', plugin_dir_url( __FILE__ ) .'../../../js/plugin_button.js', array('jquery'), '1.2'.rand(), true);

        if($post){
            wp_localize_script( 'kct_cr_scriptx1', 'aiautotool_data',
            array( 'ajax_url' => admin_url( 'admin-ajax.php') , 'postID' => $post->ID, 'postTitle' => $post->post_title,'security' => wp_create_nonce('aiautotool_nonce'),'languageCodes'=>$setting->languageCodes,
            'aiautotool_canonical_data'=> $aiautotool_canonical_data ));
        }else{
            wp_localize_script( 'kct_cr_scriptx1', 'aiautotool_data',
            array( 'ajax_url' => admin_url( 'admin-ajax.php') , 'security' => wp_create_nonce('aiautotool_nonce'),'languageCodes'=>$setting->languageCodes,
            'aiautotool_canonical_data'=> $aiautotool_canonical_data ));
        }
    


    
    wp_enqueue_script('kct_cr_scriptx1');


    }

    public function canonical_301_redirect(){
        $canonical_redirects_data = get_option('canonical_redirects_data',array());

        
        if(isset($_POST['addnew'])){
            // print_r($_POST);
            $source = sanitize_text_field($_POST['urlRequest']);
            $target = esc_url($_POST['urlDestination']);
            $canonical_redirects_data[$source] = $target;
            
            update_option('canonical_redirects_data', $canonical_redirects_data,null, 'no');

        }

        if(isset($_POST['update'])){
            // print_r($_POST);
            $source = sanitize_text_field($_POST['urlRequest']);
            $target = esc_url($_POST['urlDestination']);
            $canonical_redirects_data[$source] = $target;
            
            update_option('canonical_redirects_data', $canonical_redirects_data,null, 'no');

        }
        if(isset($_POST['del'])){
            // print_r($_POST);
            $source = sanitize_text_field($_POST['urlRequest']);
            $target = esc_url($_POST['urlDestination']);
            // $canonical_redirects_data[$source] = $target;
            unset($canonical_redirects_data[$source]);
            update_option('canonical_redirects_data', $canonical_redirects_data,null, 'no');

        }
        
        $canonical_redirects_data = get_option('canonical_redirects_data', array());

        ?>

        <div style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); padding: 25px; border-radius: 10px; margin-bottom: 25px; color: white; box-shadow: 0 4px 15px rgba(0,0,0,0.1);">
            <h1 style="margin: 0 0 15px 0; color: white; font-size: 28px; display: flex; align-items: center; gap: 12px;">
                <i class="fa-solid fa-arrow-turn-up"></i> <?php echo esc_html__('301 Redirect Manager', 'ai-auto-tool'); ?>
            </h1>
            <p style="margin: 0 0 10px 0; font-size: 16px; line-height: 1.6; opacity: 0.95;">
                <?php echo esc_html__('Manage permanent 301 redirects to preserve SEO value when URLs change. Redirects are automatically created when posts are deleted through the canonical cleanup process, or you can add custom redirects manually.', 'ai-auto-tool'); ?>
            </p>
        </div>

        <div style="background: #f8f9fa; border-left: 4px solid #f093fb; padding: 20px; border-radius: 8px; margin-bottom: 25px;">
            <h3 style="margin: 0 0 10px 0; display: flex; align-items: center; gap: 10px;">
                <i class="fa-solid fa-circle-info"></i> <?php echo esc_html__('About 301 Redirects', 'ai-auto-tool'); ?>
            </h3>
            <p style="margin: 0 0 10px 0; color: #555; font-size: 14px; line-height: 1.6;">
                <?php echo esc_html__('A 301 redirect permanently redirects one URL to another. This is crucial for SEO because it:', 'ai-auto-tool'); ?>
            </p>
            <ul style="margin: 10px 0; padding-left: 20px; color: #555; font-size: 14px; line-height: 1.8;">
                <li><?php echo esc_html__('Transfers 90-99% of link equity (ranking power) to the new URL', 'ai-auto-tool'); ?></li>
                <li><?php echo esc_html__('Prevents 404 errors and maintains user experience', 'ai-auto-tool'); ?></li>
                <li><?php echo esc_html__('Tells search engines the content has permanently moved', 'ai-auto-tool'); ?></li>
                <li><?php echo esc_html__('Consolidates ranking signals from old and new URLs', 'ai-auto-tool'); ?></li>
            </ul>
        </div>

<h1 class="wp-heading-inline" style="display: flex; align-items: center; gap: 10px; margin-bottom: 20px;">
    <img src="<?php echo esc_url(defined('AIAUTOTOOL_URI') ? AIAUTOTOOL_URI . 'images/logo.svg' : plugins_url('../../../images/logo.svg', __FILE__)); ?>" width="24px" height="24px" /> 
    <?php echo esc_html__('Manage 301 Redirects', 'ai-auto-tool'); ?>
</h1>
        <div >
            <div   class="wrap aiautotool_container">
                
                <div class="aiautotool_canonical_container">
                    <div class="aiautotool_canonical_box_left">
                        <div class="aiautotool_301_redirect_form">
                            <div style="background: #fff; border: 1px solid #e0e0e0; padding: 20px; border-radius: 8px; margin-bottom: 20px;">
                                <h2 style="margin: 0 0 15px 0; display: flex; align-items: center; gap: 10px;">
                                    <i class="fa-solid fa-plus-circle"></i> <?php echo esc_html__('Add New 301 Redirect', 'ai-auto-tool'); ?>
                                </h2>
                                <p style="color: #666; font-size: 13px; margin-bottom: 15px;">
                                    <?php echo esc_html__('Create a custom redirect rule. You can use full URLs or just the path (e.g., /old-page/).', 'ai-auto-tool'); ?>
                                </p>
                            </div>
                            <form id="redirectForm" method="POST" action="" class="addnew" style="background: #f8f9fa; padding: 20px; border-radius: 8px; margin-bottom: 20px;">
                                <input type="hidden"  name="addnew" value="addnew">
                                <div class="form-row">
                                    <label for="urlRequest" style="font-weight: 600; margin-bottom: 5px; display: block;">
                                        <i class="fa-solid fa-link-slash"></i> <?php echo esc_html__('Source URL (Old URL):', 'ai-auto-tool'); ?>
                                    </label>
                                    <p style="color: #666; font-size: 12px; margin: 0 0 8px 0;"><?php echo esc_html__('The URL that should be redirected (e.g., /old-post/ or full URL)', 'ai-auto-tool'); ?></p>
                                    
                                    <label for="urlDestination" style="font-weight: 600; margin-bottom: 5px; display: block;">
                                        <i class="fa-solid fa-link"></i> <?php echo esc_html__('Destination URL (New URL):', 'ai-auto-tool'); ?>
                                    </label>
                                    <p style="color: #666; font-size: 12px; margin: 0 0 8px 0;"><?php echo esc_html__('Where the source URL should redirect to', 'ai-auto-tool'); ?></p>
                                </div>
                                <div class="form-row">
                                    <input type="text" id="urlRequest" name="urlRequest" placeholder="<?php echo esc_attr__('/old-post/ or https://example.com/old-post/', 'ai-auto-tool'); ?>" style="padding: 10px; border: 2px solid #ddd; border-radius: 6px; width: 100%;" required>
                                    <input type="text" id="urlDestination" name="urlDestination" placeholder="<?php echo esc_attr__('/new-post/ or https://example.com/new-post/', 'ai-auto-tool'); ?>" style="padding: 10px; border: 2px solid #ddd; border-radius: 6px; width: 100%; margin-top: 10px;" required>
                                    <button type="submit" id="addNewButtonredirect" name="addnewbtn" class="ft-submit" style="margin-top: 15px;">
                                        <i class="fa-solid fa-plus"></i> <?php echo esc_html__('Add New Redirect', 'ai-auto-tool'); ?>
                                    </button>
                                </div>
                            </form>
                            
                            <h3 style="margin: 20px 0 15px 0; display: flex; align-items: center; gap: 10px;">
                                <i class="fa-solid fa-list"></i> <?php echo esc_html__('Active Redirects', 'ai-auto-tool'); ?>
                            </h3>
                            <p style="color: #666; font-size: 13px; margin-bottom: 15px;">
                                <?php echo esc_html__('Manage your active redirect rules. Redirects marked with 🤖 were automatically created by the canonical cleanup process.', 'ai-auto-tool'); ?>
                            </p>
                            <?php 
                            if (empty($canonical_redirects_data)) {
                                echo '<p style="color: #999; font-style: italic; padding: 20px; background: #f8f9fa; border-radius: 8px;">' . esc_html__('No redirects found. Add your first redirect above.', 'ai-auto-tool') . '</p>';
                            } else {
                                foreach($canonical_redirects_data as $source=>$target){
                                    ?>
                                    <form method="POST" action="" style="background: #fff; border: 1px solid #e0e0e0; padding: 15px; border-radius: 8px; margin-bottom: 15px;">
                                        <input type="hidden" name="addnew" value="update">
                                        <div class="form-row" style="display: grid; grid-template-columns: 1fr 1fr auto auto; gap: 10px; align-items: center;">
                                            <input type="text" name="urlRequest" value="<?php echo esc_attr($source);?>" placeholder="<?php echo esc_attr__('Source URL', 'ai-auto-tool'); ?>" style="padding: 8px; border: 1px solid #ddd; border-radius: 4px;" required>
                                            <input type="text" name="urlDestination" value="<?php echo esc_attr($target);?>" placeholder="<?php echo esc_attr__('Destination URL', 'ai-auto-tool'); ?>" style="padding: 8px; border: 1px solid #ddd; border-radius: 4px;" required>
                                            <button type="submit" name="update" style="padding: 8px 15px; background: #667eea; color: white; border: none; border-radius: 4px; cursor: pointer; white-space: nowrap;"><?php echo esc_html__('Update', 'ai-auto-tool'); ?></button>
                                            <button type="submit" name="del" style="padding: 8px 15px; background: #f5576c; color: white; border: none; border-radius: 4px; cursor: pointer; white-space: nowrap;"><?php echo esc_html__('Delete', 'ai-auto-tool'); ?></button>
                                        </div>
                                    </form>
                                    <?php
                                }
                            }
                            ?>
                        </div>
                    </div>
                    <div class="aiautotool_right"></div>
                </div>
            </div>
        </div>
    

<?php
    }
    public function search_posts() {
        // check_ajax_referer('aiautotool_canonical_nonce', 'security');
        check_ajax_referer('aiautotool_nonce', 'security');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
        }
        
        $search_query = sanitize_text_field($_POST['search_query']);

        if (empty($search_query)) {
            wp_send_json_error(array('message' => 'Vui lòng nhập từ khóa tìm kiếm.'));
        }

        $args = array(
            'post_type' => 'post',
            'posts_per_page' => 100,
            's' => $search_query,
        );

        $posts = new WP_Query($args);
        $results = array();

        if ($posts->have_posts()) {
            while ($posts->have_posts()) {
                $posts->the_post();
                $post_id = get_the_ID();
                $post_title = get_the_title();
                $post_url = get_permalink();

                $results[] = array(
                    'id' => $post_id,
                    'title' => $post_title,
                    'url' => $post_url,
                );
            }
            wp_reset_postdata();

            wp_send_json_success($results);
        } else {
            wp_send_json_error(array('message' => 'Không tìm thấy bài viết nào.'));
        }
    }

    public function save_canonical() {
        
        check_ajax_referer('aiautotool_nonce', 'security');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
        }

        $selected_posts = isset($_POST['selected_posts']) ? $_POST['selected_posts'] : array();
        $canonical_url = esc_url($_POST['canonical_url']);
         $autoDelete = sanitize_text_field($_POST['autoDelete']);
         $deleteSchedule = sanitize_text_field($_POST['deleteSchedule']);
         
        if (empty($selected_posts) || empty($canonical_url)) {
            wp_send_json_error(array('message' => 'Vui lòng chọn bài viết và điền URL Canonical.'));
        }
        $canonical_data = get_option('aiautotool_canonical_data', array());
        $kq = array();
        foreach($selected_posts as $postid){
            $kqnew = array(
                    'post_id'=>$postid,
                    'post_title'=>get_the_title($postid),
                    'post_url'=>get_permalink($postid),
                    'post_canonical'=>$canonical_url,
                    'canonical_time_execute'=>'',
                    'del_post'=>false,
                    'post_301'=>false,
                    'time_del_post'=>''
                );
                $kq[$postid]=$kqnew;
        }
        $canonical_data[] = array('post_id' => $selected_posts, 'canonical_url' => $canonical_url,'autoDelete'=>$autoDelete,'deleteSchedule'=>$deleteSchedule,'kq'=>$kq);
        update_option('aiautotool_canonical_data', $canonical_data,null, 'no');

        wp_send_json_success(array('message' => 'Save Success.'));
    }

    public function schedule_cron_job() {
        if (!wp_next_scheduled('aiautotool_canonical_cron')) {
            wp_schedule_event(time(), 'hourly', 'aiautotool_canonical_cron');
        }
    }


    public function aiautotool_canonical_cron() {
        // Ensure textdomain is loaded (important for cron jobs)
        // Only load if 'init' action has fired (WordPress 6.7.0+ requirement)
        if (!is_textdomain_loaded('ai-auto-tool')) {
            if (did_action('init')) {
                if (function_exists('aiautotool_load_textdomain')) {
                    aiautotool_load_textdomain();
                }
            }
        }
        
        // Lấy danh sách bài viết cần được cập nhật canonical URL
        $canonical_data = get_option('aiautotool_canonical_data');

        if (empty($canonical_data)) {
            return;
        }
        $number_post = get_option('aiautotool_canonical_number_post', 3);
        // Lấy số lượng bài viết cần cập nhật (ví dụ: 3 bài viết)

        foreach($canonical_data as $key=>&$item){
            $post_ids = $item['post_id'];
            $canonical_url = $item['canonical_url'];
            $autoDelete = $item['autoDelete'];
            
            $deleteSchedule = $item['deleteSchedule'];

            if(isset($item['kq'])){
                 $kq = $item['kq'];
            }else{
                $kq = array();
            }
           
            $post_ids = array_slice($post_ids, 0, $number_post);
           
            foreach($post_ids as $postid){
                update_post_meta($postid, '_yoast_wpseo_canonical', $canonical_url);
                update_post_meta($postid, '_yoast_wpseo_canonical_time_execute', date('Y-m-d H:i:s'));

                $canonical_time = strtotime(date('Y-m-d H:i:s'));
                $end_time = strtotime("+".$deleteSchedule." days", $canonical_time);
                $end_time_formatted = date('Y-m-d H:i:s', $end_time);
                $kqnew = array(
                    'post_id'=>$postid,
                    'post_title'=>get_the_title($postid),
                    'post_url'=>get_permalink($postid),
                    'post_canonical'=>$canonical_url,
                    'canonical_time_execute'=>date('Y-m-d H:i:s'),
                    'del_post'=>false,
                    'post_301'=>false,
                    'time_del_post'=>$end_time_formatted
                );
                $kq[$postid]=$kqnew;
            }
            $item['kq'] = $kq;
            $post_ids = array_slice($item['post_id'], $number_post);
            $item['post_id'] = $post_ids;
        }
        update_option('aiautotool_canonical_data', $canonical_data,null, 'no');

        self::checkAndDeletePosts();

        
    }

    public function checkAndDeletePosts() {
        // This function is typically called from cron or admin context
        // Check capability for safety
        if (function_exists('current_user_can') && !current_user_can('delete_posts')) {
            // If called via cron, allow; otherwise require permission
            if (!defined('DOING_CRON') || !DOING_CRON) {
                return;
            }
        }
        
        $canonical_data = get_option('aiautotool_canonical_data');
        
        if (empty($canonical_data)) {
            return;
        }
        
        foreach ($canonical_data as $key => &$canonical) {
            if (isset($canonical['kq'])) {
                $kq = $canonical['kq'];
                $autoDelete = $canonical['autoDelete'];
                $canonical_url = $canonical['canonical_url'];
                
                if ($autoDelete) {
                    $deleteSchedule = $canonical['deleteSchedule'];
                    $current_time = strtotime(date('Y-m-d H:i:s'));
                    
                    foreach ($kq as &$item) {
                        if($item['canonical_time_execute']!==''){
                            $canonical_time = strtotime($item['canonical_time_execute']);
                            $end_time = strtotime("+".$deleteSchedule." days", $canonical_time);
                            
                            if ($end_time < $current_time && $item['del_post'] === false) {
                                $post_id = $item['post_id'];
                                $post_url = $item['post_url'];
                                
                                // Additional check: verify post exists and user can delete it
                                if (function_exists('current_user_can') && !current_user_can('delete_post', $post_id)) {
                                    continue; // Skip this post if no permission
                                }
                                
                                wp_delete_post($post_id, true);
                                $item['del_post'] = true;
                                // update 301_canonical_redirects option
                                $canonical_redirects_data = get_option('canonical_redirects_data');
                                $canonical_redirects_data[$post_url] = $canonical_url;
                                update_option('canonical_redirects_data', $canonical_redirects_data,null, 'no');
                                $item['post_301'] = true;
                            }
                        }
                        
                    }
                    $canonical['kq'] = $kq ;
                }else{

                }
            }
        }
        
        update_option('aiautotool_canonical_data', $canonical_data,null, 'no');
    }


    public function redirect() {
        // this is what the user asked for (strip out home portion, case insensitive)

        $redirects = get_option('canonical_redirects_data');
        if (!empty($redirects)) {
            $userrequest = self::str_ireplace(str_replace('https','http',get_option('home')),'',str_replace('https','http',self::get_address()));

            $userrequest = ltrim($userrequest);
            $param = explode('?', $userrequest, 2);
            $userrequest = current($param);

            $wildcard = false;
            $do_redirect = '';


            // compare user request to each 301 stored in the db
            foreach ($redirects as $storedrequest => $destination) {
                // check if we should use regex search
                $a = $storedrequest;

                $storedrequest1 = $storedrequest;
                $storedrequest =  self::str_ireplace(str_replace('https','http',get_option('home')),'',str_replace('https','http',$storedrequest));

                //self::extractPathFromURL($storedrequest);//str_replace(str_replace('https','http',get_option('home')),'',$storedrequest );
                

                

                if(urldecode(trim($userrequest, '/')) == trim($storedrequest,'/')){
                    // simple comparison redirect
                    if($userrequest!='/'||$userrequest!=''){
                        $do_redirect = $destination;
                   }
                    

                }

               
 
                if($userrequest==$storedrequest){
                   if($userrequest!='/'||$userrequest!=''){
                        $do_redirect = $destination;
                   }
                    
                }
                // redirect. the second condition here prevents redirect loops as a result of wildcards.
                if ($do_redirect !== '' && trim($do_redirect,'/') !== trim($userrequest,'/')) {
                    // check if destination needs the domain prepended
                    if (strpos($do_redirect,'/') === 0){
                        $do_redirect = home_url().$do_redirect;
                    }

                    

                    header ('HTTP/1.1 301 Moved Permanently');
                    header ('Location: ' . $do_redirect);
                    exit();
                }
                else { unset($redirects); }
            }
        }
    } // end funcion redirect

    public function extractPathFromURL($url) {
    $parsedUrl = parse_url($url);

    if (isset($parsedUrl['path'])) {
        return $parsedUrl['path'];
    } else {
        // Trường hợp không có path trong URL
        return "/";
    }
}
    public static function str_ireplace($search, $replace, $subject)
    {
        $token = chr(1);
        $haystack = strtolower($subject);
        $needle = strtolower($search);
        while (($pos=strpos($haystack, $needle))!==false) {
            $subject = substr_replace($subject, $token, $pos, strlen($search));
            $haystack = substr_replace($haystack, $token, $pos, strlen($search));
        }
        $subject = str_replace($token, $replace, $subject);
        return $subject;
    }
    public function get_address() {
            if( !( isset( $_SERVER['HTTP_HOST'] ) && isset( $_SERVER['REQUEST_URI'] ) ) ) return;

            // return the full address
            return self::get_protocol().'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
    }

    public function get_protocol() {
        // Set the base protocol to http
        $protocol = 'http';
        // check for https
        if ( isset( $_SERVER["HTTPS"] ) && strtolower( $_SERVER["HTTPS"] ) == "on" ) {
            $protocol .= "s";
        }

        return $protocol;
    } // end function get_protocol


    public function render_setting() {
        // Cài đặt cho lớp auto_ex_link ở đây
       
        ?>
        <div id="tab-canonical-setting" class="tab-content" style="display:none;">
            <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 20px; border-radius: 8px; margin-bottom: 20px; color: white;">
                <h2 style="margin: 0 0 10px 0; color: white; display: flex; align-items: center; gap: 10px;">
                    <i class="fa-solid fa-sliders"></i> <?php echo esc_html__('Canonical Automation Settings', 'ai-auto-tool'); ?>
                </h2>
                <p style="margin: 0; opacity: 0.95; font-size: 14px;">
                    <?php echo esc_html__('Configure how often the system processes canonical assignments and how many posts to process per run.', 'ai-auto-tool'); ?>
                </p>
            </div>
            <?php
            if (!current_user_can('manage_options')) {
            return;
        }

        // Save settings
        if (isset($_POST['aiautotool_canonical_save_settings'])) {
           
            

            $translate_interval = intval($_POST['aiautotool_canonical_public_time']); 
            update_option('aiautotool_canonical_public_time', $translate_interval,null, 'no');

             $number_post = intval($_POST['aiautotool_canonical_number_post']); 
            update_option('aiautotool_canonical_number_post', $number_post,null, 'no');

            echo '<div class="updated"><p>Settings saved.</p></div>';
        }


        
        

        $current_interval = get_option('aiautotool_canonical_public_time', 5);


        $number_post = get_option('aiautotool_canonical_number_post', 1);
        ?>
        <div class="wrap">
            
            <form method="post" action="">
                <div style="background: #f8f9fa; border-left: 4px solid #667eea; padding: 20px; border-radius: 8px; margin-bottom: 20px;">
                    <h3 style="margin: 0 0 10px 0; display: flex; align-items: center; gap: 10px;">
                        <i class="fa-solid fa-circle-info"></i> <?php echo esc_html__('How Automation Works', 'ai-auto-tool'); ?>
                    </h3>
                    <p style="margin: 0 0 10px 0; color: #555; font-size: 14px; line-height: 1.6;">
                        <?php echo esc_html__('The canonical automation runs as a scheduled background task (cron job). It processes pending canonical assignments and checks for posts that need to be deleted based on your configured schedule.', 'ai-auto-tool'); ?>
                    </p>
                    <p style="margin: 0; color: #555; font-size: 14px; line-height: 1.6;">
                        <strong><?php echo esc_html__('Tip:', 'ai-auto-tool'); ?></strong> <?php echo esc_html__('For sites with many posts, set a longer interval and process fewer posts per run to avoid server load. For smaller sites, you can process more frequently.', 'ai-auto-tool'); ?>
                    </p>
                </div>

                <div style="background: #fff; border: 1px solid #e0e0e0; padding: 20px; border-radius: 8px; margin-bottom: 20px;">
                    <p class="ft-note" style="margin-bottom: 15px; padding: 12px; background: #fff3cd; border-left: 4px solid #ffc107; border-radius: 4px;">
                        <i class="fa-solid fa-clock"></i> <strong><?php echo esc_html__('Cron Job Interval:', 'ai-auto-tool'); ?></strong> <?php echo esc_html__('How often the system checks for pending canonical tasks', 'ai-auto-tool'); ?>
                    </p>
                    <select id="aiautotool_canonical_public_time" name="aiautotool_canonical_public_time" style="padding: 10px; border: 2px solid #ddd; border-radius: 6px; width: 100%; max-width: 400px; font-size: 14px;">
                            <option value="1" <?php selected($current_interval, 1); ?>>1 minute</option>
                            <option value="5" <?php selected($current_interval, 5); ?>>5 minutes</option>
                            <option value="10" <?php selected($current_interval, 10); ?>>10 minutes</option>
                            <option value="15" <?php selected($current_interval, 15); ?>>15 minutes</option>
                            <option value="30" <?php selected($current_interval, 30); ?>>30 minutes</option>
                            <option value="60" <?php selected($current_interval, 60); ?>>1 hour</option>
                            <option value="180" <?php selected($current_interval, 180); ?>>3 hour</option>
                            <option value="300" <?php selected($current_interval, 300); ?>>5 hour</option>
                            <option value="600" <?php selected($current_interval, 600); ?>>10 hour</option>
                            <option value="900" <?php selected($current_interval, 900); ?>>15 hour</option>
                            <option value="1440" <?php selected($current_interval, 1440); ?>>24 hour</option>
                        </select>
                </div>

                <div style="background: #fff; border: 1px solid #e0e0e0; padding: 20px; border-radius: 8px; margin-bottom: 20px;">
                    <p class="ft-note" style="margin-bottom: 15px; padding: 12px; background: #e7f5ff; border-left: 4px solid #4facfe; border-radius: 4px;">
                        <i class="fa-solid fa-hashtag"></i> <strong><?php echo esc_html__('Batch Size:', 'ai-auto-tool'); ?></strong> <?php echo esc_html__('Number of posts to process each time the cron job runs', 'ai-auto-tool'); ?>
                    </p>
                    <p style="color: #666; font-size: 13px; margin-bottom: 10px;">
                        <?php echo esc_html__('Processing posts in batches prevents server overload. Lower values = less server load but slower overall processing.', 'ai-auto-tool'); ?>
                    </p>
                <select id="aiautotool_canonical_number_post" name="aiautotool_canonical_number_post" style="padding: 10px; border: 2px solid #ddd; border-radius: 6px; width: 100%; max-width: 400px; font-size: 14px;">
                            <option value="1" <?php selected($number_post, 1); ?>>1</option>
                            <option value="2" <?php selected($number_post, 2); ?>>2</option>
                            <option value="3" <?php selected($number_post, 3); ?>>3 posts per run (Recommended)</option>
                        </select>
                </div>

                <div style="background: #f0f7ff; border: 1px solid #4facfe; padding: 15px; border-radius: 8px; margin-bottom: 20px;">
                    <h4 style="margin: 0 0 10px 0; color: #333; display: flex; align-items: center; gap: 8px;">
                        <i class="fa-solid fa-calculator"></i> <?php echo esc_html__('Processing Time Estimate', 'ai-auto-tool'); ?>
                    </h4>
                    <p style="margin: 0; color: #555; font-size: 13px;" id="processing-estimate">
                        <?php echo esc_html__('With your current settings, if you have 30 posts to process, it will take approximately 10 intervals to complete.', 'ai-auto-tool'); ?>
                    </p>
                </div>
               
                <p class="submit">
                    <input type="submit" name="aiautotool_canonical_save_settings" class="ft-submit" value="💾 <?php echo esc_attr__('Save Settings', 'ai-auto-tool'); ?>" style="padding: 12px 24px; font-size: 15px; font-weight: 600;" />
                </p>
            </form>
            <hr>
            
        </div>
        <?php
             ?>
        </div>
            <?php
    }

    public function render_search_canonical_setting() {
        ?>
        
        <div class="wrap ">
            <div style="background: #fff; border: 1px solid #e0e0e0; border-radius: 8px; padding: 20px; margin-bottom: 25px; box-shadow: 0 2px 8px rgba(0,0,0,0.05);">
                <h3 style="margin: 0 0 10px 0; display: flex; align-items: center; gap: 10px; color: #333;">
                    <i class="fa-solid fa-plus-circle"></i> <?php echo esc_html__('Add New Canonical Configuration', 'ai-auto-tool'); ?>
                </h3>
                <p style="color: #666; margin: 0 0 15px 0; font-size: 14px; line-height: 1.6;">
                    <?php echo esc_html__('Follow these simple steps to set up canonical URLs for your posts. This will help consolidate duplicate content and improve your SEO.', 'ai-auto-tool'); ?>
                </p>
            </div>
                <!-- start box -->
                <div class="aiautotool_form_canonical_body">
    <div class="aiautotool_form_canonical_tab" id="step1">
        <div class="aiautotool_form_canonical_header" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 15px; border-radius: 8px 8px 0 0; margin: -15px -15px 15px -15px;">
            <i class="fa-solid fa-search"></i> <?php echo esc_html__('Step 1: Search for Posts', 'ai-auto-tool'); ?>
        </div>
        <div style="background: #f8f9fa; padding: 15px; border-radius: 8px; margin-bottom: 15px; border-left: 4px solid #667eea;">
            <p style="margin: 0; color: #555; font-size: 14px; line-height: 1.6;">
                <i class="fa-solid fa-lightbulb"></i> <strong><?php echo esc_html__('Tip:', 'ai-auto-tool'); ?></strong> <?php echo esc_html__('Enter keywords to find posts with similar or duplicate content that you want to canonicalize. For example, search for "product review" to find all review posts.', 'ai-auto-tool'); ?>
            </p>
        </div>
        <h3 class="aiautotool_form_canonical_h2"><?php echo esc_html__('Enter your search keyword:', 'ai-auto-tool'); ?></h3>
        <input onkeydown="handleKeyPress(event)" class="aiautotool_form_canonical_input" type="text" id="searchKeyword" placeholder="<?php echo esc_attr__('e.g., product name, topic, keyword...', 'ai-auto-tool'); ?>" style="padding: 12px; border: 2px solid #ddd; border-radius: 6px;">
        <div class="aiautotool_form_canonical_button_center">
            <button class="ft-submit" onclick="validateStep1()"><?php echo esc_html__('Next', 'ai-auto-tool'); ?></button>
        </div>
        <div class="aiautotool_form_canonical_loading" id="loading1">&#x231B;</div>
    </div>

    <div class="aiautotool_form_canonical_tab" id="step2">
        <div class="aiautotool_form_canonical_header aiautotool_form_canonical_header_step2" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); color: white; padding: 15px; border-radius: 8px 8px 0 0; margin: -15px -15px 15px -15px;">
            <i class="fa-solid fa-list-check"></i> <?php echo esc_html__('Step 2: Select Posts to Canonicalize', 'ai-auto-tool'); ?>
        </div>
        <div style="background: #f8f9fa; padding: 15px; border-radius: 8px; margin-bottom: 15px; border-left: 4px solid #4facfe;">
            <p style="margin: 0; color: #555; font-size: 14px; line-height: 1.6;">
                <i class="fa-solid fa-lightbulb"></i> <strong><?php echo esc_html__('Tip:', 'ai-auto-tool'); ?></strong> <?php echo esc_html__('Select the duplicate or similar posts that should point to the same canonical URL. These are typically older versions, similar content, or posts you want to consolidate.', 'ai-auto-tool'); ?>
            </p>
        </div>
        <h3 class="aiautotool_form_canonical_h2"><?php echo esc_html__('Select posts from search results:', 'ai-auto-tool'); ?></h3>
        <div class="aiautotool_form_canonical_checkbox-label">
            
        </div>
        <table class="aiautotool_form_canonical_table">
            <thead>
                <tr>
                    <th class="aiautotool_form_canonical_th"><input type="checkbox" id="check-all">
            <label class="aiautotool_form_canonical_label" for="check-all"><?php echo esc_html__('Check All', 'ai-auto-tool'); ?></label></th>
                    <th class="aiautotool_form_canonical_th"><?php echo esc_html__('Post ID', 'ai-auto-tool'); ?></th>
                    <th class="aiautotool_form_canonical_th"><?php echo esc_html__('Title', 'ai-auto-tool'); ?></th>
                    <th class="aiautotool_form_canonical_th"><?php echo esc_html__('Action', 'ai-auto-tool'); ?></th>
                </tr>
            </thead>
            <tbody id="postList">
                <div id="loading-icon" class="loader" style="display:block"></div>
                <!-- Dữ liệu post sẽ được thêm vào đây -->
            </tbody>
        </table>
        <div class="aiautotool_form_canonical_button_center">
            <button class="ft-submit" onclick="showStep(1)"><?php echo esc_html__('Previous', 'ai-auto-tool'); ?></button>
            <button class="ft-submit" onclick="validateStep2()"><?php echo esc_html__('Next', 'ai-auto-tool'); ?></button>
        </div>
        <div class="aiautotool_form_canonical_loading" id="loading2">&#x231B;</div>
    </div>

    <div class="aiautotool_form_canonical_tab" id="step3">
        <div class="aiautotool_form_canonical_header aiautotool_form_canonical_header_step3" style="background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%); color: white; padding: 15px; border-radius: 8px 8px 0 0; margin: -15px -15px 15px -15px;">
            <i class="fa-solid fa-cog"></i> <?php echo esc_html__('Step 3: Configure Canonical URL & Auto-Delete', 'ai-auto-tool'); ?>
        </div>
        <div style="background: #f8f9fa; padding: 15px; border-radius: 8px; margin-bottom: 15px; border-left: 4px solid #43e97b;">
            <p style="margin: 0 0 10px 0; color: #555; font-size: 14px; line-height: 1.6;">
                <i class="fa-solid fa-lightbulb"></i> <strong><?php echo esc_html__('Canonical URL:', 'ai-auto-tool'); ?></strong> <?php echo esc_html__('This is the primary, authoritative URL that search engines should index. All selected posts will point to this URL.', 'ai-auto-tool'); ?>
            </p>
            <p style="margin: 0; color: #555; font-size: 14px; line-height: 1.6;">
                <i class="fa-solid fa-lightbulb"></i> <strong><?php echo esc_html__('Auto-Delete:', 'ai-auto-tool'); ?></strong> <?php echo esc_html__('Optionally schedule deletion of duplicate posts after the canonical is set. A 301 redirect will automatically be created to preserve SEO value.', 'ai-auto-tool'); ?>
            </p>
        </div>
        <h3 class="aiautotool_form_canonical_h2" style="margin-bottom: 10px;">
            <i class="fa-solid fa-link"></i> <?php echo esc_html__('Primary Canonical URL:', 'ai-auto-tool'); ?>
        </h3>
        <p style="color: #666; font-size: 13px; margin: 0 0 8px 0;"><?php echo esc_html__('Enter the URL of the page that should be considered the original/primary version', 'ai-auto-tool'); ?></p>
        <input class="aiautotool_form_canonical_input" type="text" id="canonicalUrl" placeholder="<?php echo esc_attr__('https://example.com/primary-post-url', 'ai-auto-tool'); ?>" style="padding: 12px; border: 2px solid #ddd; border-radius: 6px; margin-bottom: 20px;">
        
        <div style="background: #fff; border: 2px solid #e0e0e0; border-radius: 8px; padding: 20px; margin-bottom: 15px;">
            <h4 style="margin: 0 0 15px 0; display: flex; align-items: center; gap: 8px;">
                <i class="fa-solid fa-clock"></i> <?php echo esc_html__('Automatic Post Cleanup (Optional)', 'ai-auto-tool'); ?>
            </h4>
            <div class="aiautotool_form_canonical_checkbox-label" style="margin-bottom: 15px;">
                <input class="aiautotool_form_canonical_checkbox" type="checkbox" id="autoDelete" style="width: 18px; height: 18px;">
                <label class="aiautotool_form_canonical_label" for="autoDelete" style="margin-left: 8px; font-weight: 600;">
                    <?php echo esc_html__('Enable automatic post deletion with 301 redirect', 'ai-auto-tool'); ?>
                </label>
            </div>
            <p style="color: #666; font-size: 13px; margin: 0 0 10px 0;">
                <?php echo esc_html__('If enabled, selected posts will be automatically deleted after the specified time period, and visitors will be redirected to the canonical URL via 301 redirect.', 'ai-auto-tool'); ?>
            </p>
            <label class="aiautotool_form_canonical_label" for="deleteSchedule" style="display: block; margin-bottom: 8px; font-weight: 600;">
                <i class="fa-solid fa-calendar-days"></i> <?php echo esc_html__('Delete posts after:', 'ai-auto-tool'); ?>
            </label>
            <select class="aiautotool_form_canonical_select" id="deleteSchedule" style="padding: 10px; border: 2px solid #ddd; border-radius: 6px; width: 100%; max-width: 300px;">
                <option value="1"><?php echo esc_html__('1 Day (Quick cleanup)', 'ai-auto-tool'); ?></option>
                <option value="7"><?php echo esc_html__('7 Days (1 Week - Recommended)', 'ai-auto-tool'); ?></option>
                <option value="10"><?php echo esc_html__('10 Days', 'ai-auto-tool'); ?></option>
                <option value="30"><?php echo esc_html__('30 Days (1 Month - Conservative)', 'ai-auto-tool'); ?></option>
            </select>
        </div>
        <div class="aiautotool_form_canonical_button_center">
            <button class="ft-submit" onclick="showStepWithLoading(2, 'loading3')"><?php echo esc_html__('Previous', 'ai-auto-tool'); ?></button>
            <button class="ft-submit" onclick="validateStep3()"><?php echo esc_html__('Save Configuration', 'ai-auto-tool'); ?></button>
        </div>
        <div class="aiautotool_form_canonical_loading" id="loading3">&#x231B;</div>
    </div>

    <script>
       
        function handleKeyPress(event) {
            // Kiểm tra xem phím Enter đã được nhấn và mã phím là 13
            if (event.key === 'Enter' || event.keyCode === 13) {
                // Gọi hàm validateStep1()
                validateStep1();
            }
        }
        var searchData = []; 

        // Mô phỏng dữ liệu post
        for (let i = 1; i <= 10; i++) {
            searchData.push({ id: i, title: `Post ${i}` });
        }

        function showStep(step) {
            // Ẩn tất cả các tab
            document.querySelectorAll('.aiautotool_form_canonical_tab').forEach(tab => tab.style.display = 'none');
            // Hiển thị tab theo step được chọn
            document.getElementById(`step${step}`).style.display = 'block';

            // Ẩn biểu tượng tải
            document.querySelectorAll('.aiautotool_form_canonical_loading').forEach(loading => loading.style.display = 'none');
        }

        function showStepWithLoading(step, loadingId) {
            // Hiển thị biểu tượng tải
            document.getElementById(loadingId).style.display = 'inline-block';
            // Tạm dừng để mô phỏng việc thực hiện code
            setTimeout(function () {
                showStep(step);
                // Ẩn biểu tượng tải
                document.getElementById(loadingId).style.display = 'none';
            }, 1000); // Giả sử 1000ms là thời gian delay
        }

        // Hiển thị danh sách post ở Step 2
        function showPostList(s,loadingId) {
            document.getElementById(loadingId).style.display = 'inline-block';
           
            var data = {
                action: 'aiautotool_search_posts',
                search_query: s,
                security:aiautotool_js_setting.security
            };
            const postList = document.getElementById('postList');
            postList.innerHTML = '';
            document.getElementById(loadingId).style.display = 'inline-block';
            jQuery('#'+loadingId).show();
           console.log(document.getElementById(loadingId).style.display);
            jQuery.post('<?php echo esc_url(admin_url('admin-ajax.php'));?>', data, function(response) {
                if (response.success) {
                    var results = response.data;
                  
                    // document.getElementById(loadingId).style.display = 'none';
                    jQuery('#'+loadingId).hide();
                    jQuery('#loading-icon').hide();
                    jQuery.each(results, function(index, post) {
                        const row = document.createElement('tr');
                        row.innerHTML = `
                            <td><input type="checkbox" class="postCheckbox"  name="postCheckbox[]" value="${post.id}"></td>
                            <td>${post.id}</td>
                            <td><td><a href="${post.url}">${post.title}</a></td>
                        `;
                        postList.appendChild(row);
                    }); 

                    

                   

                } else {
                   const row = document.createElement('tr');
                        row.innerHTML = `
                            <td><input type="checkbox" name="postCheckbox[]" value=""></td>
                            <td>0</td>
                            <td><td>No post for search</td>
                        `;
                        postList.appendChild(row);
                }
            });
            
            
        }

        // Xử lý sự kiện khi nhấn nút "Check All"
        document.getElementById('check-all').addEventListener('change', function () {
            var isChecked = this.checked;
            var postCheckboxes = document.querySelectorAll('.postCheckbox');
            postCheckboxes.forEach(function (checkbox) {
                checkbox.checked = isChecked;
            });
        });
        function validateStep1() {
            const searchKeyword = document.getElementById('searchKeyword').value;
            if (!searchKeyword) {
                alert('Please enter a search keyword.');
                return;
            }else{
                showPostList(searchKeyword,'loading2');
            }
            // Nếu trường hợp kiểm tra thành công, tiếp tục đến Step 2
            showStepWithLoading(2, 'loading1');
        }
        function validateStep2() {
            const checkedPostIds = Array.from(document.querySelectorAll('.postCheckbox:checked')).map(checkbox => checkbox.value);
             if (checkedPostIds.length === 0) {
                    alert('Please select at least one post to Canonical.');
                    // Ẩn biểu tượng tải
                    document.getElementById('loading3').style.display = 'none';
                    return;
                }
            // Nếu trường hợp kiểm tra thành công, tiếp tục đến Step 2
            showStepWithLoading(3, 'loading1');
        }
        function validateStep3() {
            const canonicalUrl = document.getElementById('canonicalUrl').value;
             if (!canonicalUrl) {
                    alert('Please fill input Canonical Url.');
                    // Ẩn biểu tượng tải
                    document.getElementById('loading3').style.display = 'none';
                    return;
                }
            // Nếu trường hợp kiểm tra thành công, tiếp tục đến Step 2
            scheduleDelete() ;
        }
        // Lập lịch xóa post ở Step 3
        function scheduleDelete() {
            // Hiển thị biểu tượng tải
            document.getElementById('loading3').style.display = 'inline-block';

            const canonicalUrl = document.getElementById('canonicalUrl').value;
            const autoDelete = document.getElementById('autoDelete').checked;
            const deleteSchedule = document.getElementById('deleteSchedule').value;

            const checkedPostIds = Array.from(document.querySelectorAll('.postCheckbox:checked')).map(checkbox => checkbox.value);

            console.log(`Canonical URL: ${canonicalUrl}`);
            console.log(`Auto delete posts: ${autoDelete}`);
            console.log(`Delete schedule: ${deleteSchedule} days`);
            console.log(`Checked Post IDs: ${checkedPostIds}`);

            
            var data = {
                action: 'aiautotool_save_canonical',
                selected_posts: checkedPostIds,
                canonical_url: canonicalUrl,
                autoDelete:autoDelete,
                deleteSchedule:deleteSchedule,
                security:aiautotool_js_setting.security

            };

            jQuery.post('<?php echo esc_url(admin_url('admin-ajax.php'));?>', data, function(response) {
                if (response.success) {
                    
                    location.reload();
                } else {
                    
                }
            });
        }

        showStep(1);
        
    </script>
</div>
                <!-- end box -->
            </div>
           <!--  </div>
            </div>
        </div>
        </div> -->
        <?php
    }
     public function render_tab_setting() {
        if ($this->active=='true') {
        // Cài đặt cho lớp auto_ex_link ở đây
        echo '<button href="#tab-canonical-setting" class="nav-tab  sotab"><i class="fa-solid fa-link"></i> '.esc_html__('Canonical Manager', 'ai-auto-tool').'</button>';
        }
    }
     public function render_feature(){
        // Load feature descriptions
        require_once plugin_dir_path(dirname(__FILE__)) . 'lib/feature-descriptions.php';
        
        $autoToolBox = new AutoToolBox(
            $this->icon.' '.$this->name_plan, 
            AiAutoTool_Feature_Descriptions::get('canonical'), 
            "https://doc.aiautotool.com/canonical-manager", 
            $this->active_option_name, 
            $this->active,
            defined('AIAUTOTOOL_URI') ? AIAUTOTOOL_URI . 'images/logo.svg' : plugins_url('../../../images/logo.svg', __FILE__)
        );

         echo ($autoToolBox->generateHTML());
        
    }
}
} // End of class_exists check
