<?php

namespace SEOAIC;

use DateInterval;
use DatePeriod;
use DateTime;
use DateTimeZone;
use Exception;
use SEOAIC\loaders\PostsGenerationLoader;
use SEOAIC\posts_mass_actions\LeadsFormGenerate;
use SeoaicAjaxValidation;
use WP_Error;
use WP_Query;

class SEOAIC_ONBOARDING
{
    private $seoaic;
    const VIEWS_DIR = SEOAIC_DIR . 'inc/view/onboarding/';
    private const CRON_HOOK = 'seoaic_onboarding_cron_publish';
    private const NEXT_POST_OPTION = 'seoaic_onboarding_next_post_date';
    private const SEND_PAGES_PROGRESS = 'seoaic_onboarding_send_pages_progress';
    private const CLUSTERS_GENERATED_STATUS = 'seoaic_onboarding_clusters_generated_status';
    private const CURRENT_STEP = 'seoaic_onboarding_current_step';
    private const LOADING_PROGRESS = 'seoaic_onboarding_loading_progress';
    private const CREATE_IDEAS_STATUS = 'seoaic_onboarding_ideas_status';
    private const CLUSTERS_CACHE = 'seoaic_store_clusters_cache';
    private const KEYWORDS_CATEGORIES_KEY = 'keywords_categories';
    private $sidebar_template_file;
    private $options = '';
    private $send_pages_progress;
    private $clusters_generated_status;
    private $current_step;
    private $steps;

    function __construct($_seoaic)
    {
        $this->seoaic = $_seoaic;
        $this->sidebar_template_file = self::VIEWS_DIR . 'seoaic-wizard-steps-sidebar-view.php';

        global $SEOAIC_OPTIONS;
        $this->options = $SEOAIC_OPTIONS;
        $this->send_pages_progress = $this->send_pages_progress();
        $this->clusters_generated_status = $this->clusters_generated_status();
        $this->current_step = $this->current_step();

        add_action('init', [$this, 'init']);

        add_action('wp_ajax_seoaic_onboarding_scan_pages', [$this, 'onboarding_scan_pages']);
        add_action('wp_ajax_seoaic_onboarding_check_status', [$this, 'onboarding_check_status']);
        add_action('wp_ajax_seoaic_onboarding_get_clusters_list', [$this, 'get_clusters_list']);
        add_action('wp_ajax_seoaic_onboarding_get_ideas', [$this, 'get_ideas']);
        add_action('wp_ajax_seoaic_onboarding_cluster_ideas_generate', [$this, 'cluster_ideas_generate']);
        // add_action('wp_ajax_seoaic_onboarding_add_idea_to_cluster', [$this, 'add_idea_to_cluster']);
        add_action('wp_ajax_seoaic_onboarding_cluster_ideas_remove', [$this, 'cluster_ideas_remove']);
        add_action('wp_ajax_seoaic_onboarding_cluster_ideas_update', [$this, 'cluster_ideas_update']);
        add_action('wp_ajax_seoaic_onboarding_get_services_and_audience', [$this, 'get_services_and_audience']);
        add_action('wp_ajax_seoaic_cluster_update', [$this, 'cluster_update']);
        add_action('wp_ajax_seoaic_cluster_delete', [$this, 'cluster_delete']);
        add_action('wp_ajax_seoaic_create_cluster', [$this, 'create_cluster']);
        add_action('wp_ajax_seoaic_remove_page_from_cluster', [$this, 'remove_page_from_cluster']);
        add_action('wp_ajax_seoaic_onboarding_step', [$this, 'process_onboarding_step']);
        add_action('wp_ajax_seoaic_add_page_to_cluster', [$this, 'add_page_to_cluster']);
        add_action('wp_ajax_seoaic_clear_onboarding_progress', [$this, 'clear_onboarding_progress']);
        add_action('wp_ajax_seoaic_onboarding_google_integration_check', [$this, 'google_integration_check']);
        add_action('wp_ajax_seoaic_onboarding_content_strategy_html', [$this, 'content_strategy_html_ajax']);
        add_action('wp_ajax_seoaic_get_onboarding_schedule_ideas', [$this, 'get_onboarding_schedule_ideas']);
        add_action('wp_ajax_seoaic_onboarding_accept_ideas', [$this, 'accept_ideas']);
        add_action('wp_ajax_seoaic_load_post_content_to_editor', [$this, 'load_post_content_to_editor']);
        add_action('wp_ajax_seoaic_load_post_editor_html', [$this, 'load_post_editor_html']);
        add_action('wp_ajax_seoaic_ob_load_generated_posts_html', [$this, 'ob_load_generated_posts_html']);
        add_action('wp_ajax_seoaic_ob_save_and_accept_post', [$this, 'ob_save_and_accept_post']);
        add_action('wp_ajax_seoaic_ob_save_and_accept_mass_posts', [$this, 'ob_save_and_accept_mass_posts']);
        add_action('wp_ajax_seoaic_ob_view_remote_ideas', [$this, 'view_remote_ideas']);
        add_action('wp_ajax_seoaic_get_all_clustered_posts_batched', [$this, 'get_all_clustered_posts_batched']);
        add_action('wp_ajax_seoaic_get_posted_date_range', [$this, 'seoaic_get_posted_date_range']);
        add_action('wp_ajax_seoaic_create_cluster_transition_queue', [$this, 'create_cluster_transition_queue']);
        add_action('wp_ajax_seoaic_get_all_posts_clusters_batched', [$this, 'get_all_posts_clusters_batched']);
        add_action('wp_ajax_seoaic_cluster_pages_and_ideas', [$this, 'cluster_pages_and_ideas']);
        add_action('wp_ajax_seoaic_get_clusters_options', [$this, 'get_clusters_options']);
        add_action('admin_enqueue_scripts', function () {
            if (isset($_GET['page']) && in_array($_GET['page'], [
                    'seoaic-streamlined-onboarding',
                    'seoaic-calendar',
                    'seoaic-content-improvement',
                    'seoaic-keywords',
                ])) {
                wp_enqueue_editor();
            }
        });
    }

    public function init()
    {
        $this->initSteps();
    }

    public function get_gsc_suggested_pages_data()
    {
        global $SEOAIC;

        $params = array (
            'currentPage' => '1',
            'limit' => '10',
            'publishedMonth' => 'all',
            'brandedKeywords' => 'all',
            'statusKeyword' => 'all',
            'search' => [],
            'orderBy' => 'clicks',
            'order' => 'DESC',
            'dateFrom' => date('Y-m', strtotime('-1 months')),
            'dateTo' => date('Y-m', strtotime('-3 days')),
            'compareKeywordPositionFrom' => '1',
            'compareKeywordPositionTo' => '3',
            'seoaicPost' => 'include',
            'dateMode' => 'months',
            'redirectSuggestion' => 'all',
            'redirectFilter' => 'all',
            'postTypeFilter' => 'all',
            'trendStatus' => '',
        );

        $urls = $SEOAIC->curl->initWithReturn('api/pruning/google/inspection', $params, true, true, true);

        $front_page_id = get_option('page_on_front');
        $published_ids = [];

        if ($front_page_id) {
            if (is_array($front_page_id)) {
                $front_page_id = $front_page_id[0];
            }
            $published_ids[] = $front_page_id;
        }

        if(!empty($urls['message'])) {
            return $published_ids;
        }

        $urls = array_column($urls['links'], 'url');

        $data = $SEOAIC->content_improvement->processBatch($urls, 100, false);
        
        $ids = array_values($data);
        
        foreach ($ids as $id) {
            $status = get_post_status($id);
            if (in_array($status, ['publish', 'draft', 'future'])) {
                $published_ids[] = $id;
            }
        }

        return array_unique($published_ids);
    }

    /**
     * @throws Exception
     */
    public function load_post_editor_html()
    {
        check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);

        $post = wp_unslash($_POST);

        $post_ids_raw = !empty($post['post_ids']) && !is_array($post['post_ids']) ? [$post['post_ids']] : $post['post_ids'];

        $post_ids = array_map('intval', $post_ids_raw);

        $editors = [];
        wp_enqueue_editor();

        foreach ($post_ids as $post_id) {
            $post = get_post($post_id);
            if (!$post) {
                continue;
            }

            $needs_review = get_post_meta($post_id, 'seoaic_ob_needs_review', true);
            if ($needs_review) {
                $save_button_label = esc_html__('Save and accept', 'seoaic');
            } else {
                $save_button_label = esc_html__('Save', 'seoaic');
            }

            $ob_posting_date = get_post_meta($post_id, 'seoaic_ob_posting_date', true);
            $status = $post->post_status;
            $publish_date = $this->get_date_based_on_status($status, $post->post_date, $ob_posting_date);
            $datetime = new DateTime($publish_date, new DateTimeZone('UTC'));
            $utc_publish_date = $datetime->format('Y-m-d\TH:i');

            $editors[$post_id] = sprintf(
                '
                <input id="seoaic-ob-save_edited_content_' . $post_id . '" value="1" type="checkbox" class="seoaic-checkbox d-none" checked>
                <label class="text-label seoaic_ob_preview_post_label">' . esc_html__('Generated Post Preview', 'seoaic') . '</label><div class="seoaic-editor-container" data-post-id="%1$d">
                <textarea id="seoaic_ob_editor_%1$d" name="seoaic_ob_editor_content_%1$d" class="seoaic-wp-editor" rows="10">%2$s</textarea>
                <div class="seoaic-editor-controls d-flex ai-end mt-10">
                    <a href="#" class="seoaic_ob_editor_preview_close accent accent-underline">' . esc_html__('Close editor', 'seoaic') . '</a>
                    <a href="#" class="seoaic_ob_editor_hide_from_list accent accent-underline seoaic-ml-20 d-none">' . esc_html__('Hide from list', 'seoaic') . '</a>
                    <div class="seoaic-controls-date">
                        <label for="seoaic_ob_publish_date_%1$d" class="seoaic_text_nowrap mb-5">' . esc_html__('Schedule Date:', 'seoaic') . '</label>
                        <input type="datetime-local" class="seoaic-form-item form-input" id="seoaic_ob_publish_date_%1$d" name="seoaic_publish_date_%1$d" value="%3$s" />
                        <input type="hidden" class="seoaic-form-item form-input hide-ob-date-on-auto-scheduled-checked" id="seoaic_ob_publish_date_utc_%1$d" name="seoaic_publish_date_utc_%1$d" value="%4s"/>
                    </div>
                    <button type="button" class="seoaic_ob_save_post_btn seoaic-branded-button" data-saving="' . esc_html__('Saving', 'seoaic') . '" data-save="' . $save_button_label . '" data-post-id="%1$d" data-editor-id="seoaic_ob_editor_' . $post_id . '">' . esc_html__('Save and accept', 'seoaic') . '</button>
                </div>
                <div class="mt-10 seoaic-text-right">
                    <label for="seoaic-leave-as-a-draft" class="seoaic_text_nowrap mr-15">' . esc_html__('Leave as a draft', 'seoaic') . '</label><input id="seoaic-ob-leave-as-a-draft_%1$d" data-status="' . esc_attr('draft') . '" type="checkbox" class="seoaic-checkbox" checked>
                </div>
            </div>',
                $post_id,
                esc_textarea($post->post_content),
                date('Y-m-d\TH:i', strtotime($utc_publish_date)),
                strtotime($utc_publish_date)
            );
        }

        wp_send_json_success(['editors' => $editors]);
    }

    public function load_post_content_to_editor()
    {
        check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);

        $post = wp_unslash($_POST);
        $post_id = isset($post['post_id']) ? intval($post['post_id']) : 0;
        $has_remote_idea = isset($_POST['remote_idea']) && $_POST['remote_idea'] === 'true';
        if ($post_id) {
            $post = get_post($post_id);

            if ($post && !is_wp_error($post)) {
                $needs_review = get_post_meta($post_id, 'seoaic_ob_needs_review', true);
                $auto_scheduled = get_post_meta($post_id, 'seoaic_auto_scheduled', true);
                $checked = '';
                $value = '';
                $display = '';
                if (!empty($auto_scheduled)) {
                    $checked = esc_attr('checked');
                    $value = esc_attr('1');
                    $display = esc_attr('display:none');
                }

                if (!empty($needs_review)) {
                    $save_button_label = esc_html__('Save and accept', 'seoaic');
                } else {
                    $save_button_label = esc_html__('Save', 'seoaic');
                }

                $publish_date = $post->post_date;
                $publish_date_utc = $post->post_date_gmt;

                wp_send_json_success([
                    'content' => $post->post_content,
                    'actions' => '
                        <div class="seoaic-editor-controls d-flex ai-end mt-40">
                        <div class="seoaic-popup__field mt-10">
                            <label for="seoaic_auto_schedule_post_' . $post_id . '" class="text-label d-flex ">' . esc_html__('Auto schedule', 'seoaic') . '<span class="seoaic-help-icon ml-10" data-seoaic-tooltip-info="' . esc_html__('If Auto schedule, the posts will be published according to the post schedule in the plugin Settings.', 'seoaic') . '">?</span></label>
                            <div class="seoaic_toggle_selector mt-10">
                                <input ' . $checked . ' id="seoaic_auto_schedule_post_' . $post_id . '" value="' . $value . '" data-hide-on-checked=".hide-ob-date-on-auto-scheduled-checked"
                                       value="" type="checkbox" class="d-none seoaic_checkbox_toggle_selector seoaic-form-item"
                                       name="seoai_auto_schedule">
                                <label for="seoaic_auto_schedule_post_' . $post_id . '" class="toggler"><span></span></label>
                            </div>
                        </div>
                            <div class="seoaic-controls-date">
                                <label for="seoaic_ob_publish_date_' . $post_id . '" class="seoaic_text_nowrap mb-5 hide-ob-date-on-auto-scheduled-checked" style="' . $display . '">' . esc_html__('Schedule Date:', 'seoaic') . '</label>
                                <input type="text" class="seoaic-form-item form-input hide-ob-date-on-auto-scheduled-checked" id="seoaic_ob_publish_date_' . $post_id . '" name="seoaic_publish_date_' . $post_id . '" value="' . date('Y-m-d\TH:i', strtotime($publish_date_utc)) . '" style="' . $display . '" />
                                <input type="hidden" class="seoaic-form-item form-input hide-ob-date-on-auto-scheduled-checked" id="seoaic_ob_publish_date_utc_' . $post_id . '" name="seoaic_publish_date_utc_' . $post_id . '" value="' . strtotime($publish_date_utc) . '" style="' . $display . '" />
                            </div>
                            <button type="button" class="seoaic_ob_save_post_btn seoaic-branded-button" data-saving="' . esc_html__('Saving', 'seoaic') . '" data-save="' . $save_button_label . '" data-post-id="' . $post_id . '" data-editor-id="seoaic-calendar-post-editor">' . $save_button_label . '</button>
                        </div>
                        <div class="mt-10 seoaic-text-right">
                            <label for="seoaic-ob-save_edited_content_' . $post_id . '" class="seoaic_text_nowrap mr-15 d-none">' . esc_html__('Save this content', 'seoaic') . '</label><input id="seoaic-ob-save_edited_content_' . $post_id . '" type="checkbox" class="seoaic-checkbox d-none">
                            <span> </span>
                            <label for="seoaic-ob-leave-as-a-draft_' . $post_id . '" class="seoaic_text_nowrap mr-15">' . esc_html__('Leave as a draft', 'seoaic') . '</label><input id="seoaic-ob-leave-as-a-draft_' . $post_id . '" data-status="' . esc_attr('draft') . '" type="checkbox" class="seoaic-checkbox">
                        </div>'
                ]);
            }
        }

        if ($has_remote_idea) {
            wp_send_json_success([
                'content' => __('The post idea is scheduled and no content generated yet.', 'seoaic')
            ]);
        }

        wp_send_json_success([
            'content' => __('No content', 'seoaic')
        ]);

        wp_die();
    }

    private function send_pages_progress()
    {
        $name = self::SEND_PAGES_PROGRESS;
        return !empty($this->options[$name]) ? intval($this->options[$name]) : 0;
    }

    private function clusters_generated_status()
    {
        global $SEOAIC_OPTIONS;
        return !empty($SEOAIC_OPTIONS[self::CLUSTERS_GENERATED_STATUS]) ? $SEOAIC_OPTIONS[self::CLUSTERS_GENERATED_STATUS] : '';
    }

    public function current_step()
    {
        $name = self::CURRENT_STEP;
        return !empty($this->options[$name]) ? intval($this->options[$name]) : 1;
    }

    private function create_ideas_status()
    {
        global $SEOAIC_OPTIONS;
        return !empty($SEOAIC_OPTIONS[self::CREATE_IDEAS_STATUS]) ? $SEOAIC_OPTIONS[self::CREATE_IDEAS_STATUS] : '';
    }

    private function loading_progress()
    {
        $name = self::LOADING_PROGRESS;
        return !empty($this->options[$name]) ? intval($this->options[$name]) : 0;
    }

    private function initSteps()
    {
        $this->steps = [
            [
                "title" => esc_html__('Connect Google Search Console (GSC)', 'seoaic'),
                "callback" => "step_connect_google_console_html",
                "subtitle" => ""
            ],
            [
                "title" => esc_html__('Select Key Pages & Scan Your Site', 'seoaic'),
                "callback" => "step_crawl_sitemap_html",
                "subtitle" => esc_html__('Please select at least one page that represents your business — like Home, About Us, or Services. Multiple pages give better results.', 'seoaic'),
            ],
            [
                "title" => esc_html__('Monthly Rollout Plan', 'seoaic'),
                "callback" => "step_generate_content_plan_html",
                "subtitle" => esc_html__('Automatically schedule content creation. Ideas will be generated for each selected cluster and content type.', 'seoaic')
            ],
            [
                "title" => esc_html__('Content Cluster Mind Map', 'seoaic'),
                "callback" => "step_content_cluster_mind_map_html",
                "subtitle" => esc_html__('Visualizing content clusters and ideas published up to and including this month. Use the timeline selector to change the view.', 'seoaic'),
                "last" => true
            ],
        ];
    }

    public function process_onboarding_step()
    {
        check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);

        $post = wp_unslash($_POST);

        if (!empty($post)) {
            if (!empty($post['callback'])) {
                call_user_func([$this, $post['callback']]);
            }

            $data = [];
            $step = $post['step'];

            if (intval($step) === count($this->steps)) {
                return;
            }

            $next_step = intval($step) + 1;

            if (empty($this->steps[$next_step - 1])) {
                $next_step = 1;
            }

            $data['data'] = $this->run_streamline_onboarding($next_step, false, true);
            $data['next_step'] = $next_step;

            wp_send_json($data);
        }
    }

    public function run_streamline_onboarding($step = 1, $sidebar = true, $steps = true)
    {

        $step_content = '';

        if ($sidebar) {
            $step_content .= $this->makeStepsSidebar($step);
        }

        if ($steps) {
            $step_content .= $this->makeStepContent($step);
        }

        return $step_content;
    }

    private function makeStepsSidebar($step = 1)
    {
        if ($this->isValidStep($step)) {
            foreach ($this->steps as $i => &$s) {
                if ($i < $step - 1) {
                    $s['passed'] = true;
                } elseif ($i == $step - 1) {
                    $s['is_active'] = true;
                } else {
                    $s['passed'] = false;
                }
            }
        }

        ob_start();

        if (file_exists($this->sidebar_template_file)) {
            $steps = $this->steps;
            include_once($this->sidebar_template_file);
        }

        return ob_get_clean();
    }

    private function isValidStep($step)
    {
        if ($step >= 1
            && $step > $this->getStepsCount()
        ) {
            return false;
        }

        return true;
    }

    private function getStepsCount()
    {
        return count($this->steps);
    }

    private function makeStepContent(int $step = 1): string
    {
        $index = $step - 1;

        if (!isset($this->steps[$index])) {
            return '';
        }

        $stepData = $this->steps[$index];
        $this->save_option(self::CURRENT_STEP, $step);

        $title = $stepData['title'];
        $subtitleText = $stepData['subtitle'] ?? '';
        $subtitleHtml = $subtitleText
            ? '<p class="step-subtitle mb-40 mt-0 fs-16">' . esc_html($subtitleText) . '</p>'
            : '';

        $callback = $stepData['callback'] ?? null;
        $stepContent = (is_string($callback) && method_exists($this, $callback))
            ? call_user_func([$this, $callback])
            : '';

        return '
        <div class="step-container keywords" data-step="' . esc_attr($step) . '">
            <p class="step-number">' . __('Step ', 'seoaic') . esc_html($step) . '</p>
            <p class="step-header seoaic-mb-15">' . esc_html($title) . '</p>
            ' . $subtitleHtml . '
            <div class="step-content wait-for-ajaxcontent">
                ' . $stepContent . '
            </div>
            ' . $this->renderButtonsRow($step) . '
            <span id="seoaic_back_to_first_step" class="seoaic-ajax-form seoaic-ajax-submit">
                <input type="hidden" class="seoaic-ajax-field" name="action" value="seoaic_onboarding_step">
                <input type="hidden" class="seoaic-ajax-field" name="step" value="' . esc_attr($index) . '">
            </span>
        </div>';
    }


    private function save_option($key, $value)
    {
        global $SEOAIC_OPTIONS;
        $SEOAIC_OPTIONS[$key] = $value;
        update_option('seoaic_options', $SEOAIC_OPTIONS);
    }

    private function renderButtonsRow($step)
    {
        $index = $step - 1;
        $applyButton = '';
        $disabled = '';

        if (empty($this->clusters_generated_status) && intval($step) === 2) {
            $disabled = 'disabled';
        }

        $backButton = $step > 1 ? $this->renderButton('Back', 'transparent-button-primary outline ml-auto', $step - 2) : '';

        if (empty($this->steps[$index]['last'])) {
            $applyButton = $this->renderButton('Apply', 'button-primary seoaic-button-primary generate-keyword-based ' . $disabled . ($backButton ? ' ml-15' : ''), $step, 'seoaic_submit_next_step');
        }

        return "<div class='buttons-row mt-40 d-flex jc-e'>{$backButton}{$applyButton}</div>";
    }

    private function renderButton($label, $class, $step, $id = '')
    {
        $id = $id ? 'id="' . $id . '"' : '';
        return '<button ' . $id . ' title="' . esc_attr($label) . '" type="button"
                    class="' . $class . ' seoaic-ajax-form seoaic-ajax-submit">
                    <input type="hidden" class="seoaic-ajax-field" name="action" value="seoaic_onboarding_step">
                    <input type="hidden" class="seoaic-ajax-field" name="step" value="' . intval($step) . '">
                ' . esc_attr($label) . '</button>';
    }

    public function clear_onboarding_progress()
    {
        check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);

        if (!current_user_can('edit_posts')) {
            SEOAICAjaxResponse::alert("Permission denied")->wpSend();
        }

        $post = wp_unslash($_POST);
        $this->save_option(self::CURRENT_STEP, 0);
        $this->save_option(self::LOADING_PROGRESS, 0);
        $this->save_option(self::SEND_PAGES_PROGRESS, '0');
        $this->save_option(self::CLUSTERS_GENERATED_STATUS, '');

        wp_send_json([
            'status' => 'success',
            'step' => $post['step'],
        ]);
    }

    public function get_generated_services()
    {
        $data = [
            "limit" => 9
        ];

        $result = $this->seoaic->curl->init('/api/clusters/list-stats', $data, true, true, true);
        wp_send_json($result);
    }

    public function onboarding_scan_pages()
    {
        check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);

        if (!current_user_can('edit_posts')) {
            SEOAICAjaxResponse::alert("Permission denied")->wpSend();
        }

        $post = wp_unslash($_POST);

        $page = isset($post['page']) ? intval($post['page']) : 1;
        $simplified = !empty($post['simplified']);
        $include_ids = !empty($post['include_ids']) && !is_array($post['include_ids']) ? explode(',', $post['include_ids']) : [];

        if (empty($include_ids)) {
            SEOAICAjaxResponse::alert('Select at least one page that clearly represents your business focus')->wpSend();
        }

        $limit = 50;
        $offset = ($page - 1) * $limit;

        $site_links = $this->get_requested_posts($offset, $limit, [], $include_ids);

        $total_pages = max(1, intval($site_links['pages']));
        $status = ($page === $total_pages) || $simplified ? 'done' : 'in-progress';
        $progress = min(100, round(($page / $total_pages) * 100));

        $data = [
            'status' => $status,
            'language' => $this->seoaic->multilang->get_selected_language(),
            'location' => SEOAIC_SETTINGS::getLocation(),
            'pages' => $site_links['data'],
            'company_name' => SEOAIC_SETTINGS::getBusinessName(),
        ];

        $this->seoaic->curl->init('api/clusters', $data, true, true, true);
        $this->save_option(self::SEND_PAGES_PROGRESS, $page);
        $this->save_option(self::LOADING_PROGRESS, $progress / 2);

        wp_send_json([
            'status' => $status,
            'page' => $page - 1,
            'total_pages' => $total_pages,
            'progress' => $progress,
        ]);
    }

    public function get_requested_posts($offset, $limit, $exclude_ids, $included_ids)
    {
        global $SEOAIC;
        $response = $SEOAIC->audit_data->get_all_site_links($offset, $limit, false, false, true, $exclude_ids, $included_ids);
        return $this->filter_posts_array($response);
    }

    private function filter_posts_array($response)
    {
        global $SEOAIC;

        $transformed = [
            'total' => $response['total'],
            'pages' => $response['pages'],
            'data' => []
        ];

        foreach ($response['data'] as $item) {
            $post_id = $item['id'];
            $post = get_post($post_id);

            if (!$post) {
                continue;
            }

            $meta_data = $SEOAIC->content_improvement->get_seo_meta_data($post_id);
            $description = $meta_data['description'];
            $seo_title = $meta_data['title'];
            $title = get_the_title($post);
            $headings = $seo_title ? $seo_title : $title;
            $content = apply_filters('the_content', $post->post_content);
            $clean_text = wp_strip_all_tags($content);
            $clean_text = preg_replace('/^\s*[\r\n]+/m', '', $clean_text);

            $transformed['data'][] = [
                'id' => intval($post_id),
                'title' => esc_html($title),
                'type' => 'post',
                'description' => trim($clean_text) ? trim($clean_text) : $description,
                'headings' => esc_html($headings),
                'url' => get_permalink($post),
                'keyPage' => true,
            ];
        }

        return $transformed;
    }

    public function onboarding_check_status()
    {
        check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);

        $data = [];
        $progress = wp_unslash($_POST['progress']);

        $result = $this->seoaic->curl->init('/api/clusters/status', $data, true, true, true);
        $this->save_option(self::CLUSTERS_GENERATED_STATUS, $result['status']);
        $this->save_option(self::LOADING_PROGRESS, $progress);
        wp_send_json($result);
    }

    public function get_clusters_list()
    {
        check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);

        global $SEOAIC;

        $page = wp_unslash($_POST['page']);

        $data = [
            "page" => !empty($page) ? $page : 1,
        ];

        $result = $this->seoaic->curl->init('/api/clusters/list', $data, true, true, true);
        $this->validate_status($result);

        if (empty($result['data'])) {
            return;
        }

        $current = $result['current_page'];

        wp_send_json([
            'clusters_cards' => $this->clusters_cards($result['data']),
            'clusters_pagination' => $SEOAIC->explorer->inline_pagination(intval($current), intval($result['total_pages']), 'seoaic_onboarding_get_clusters_list')
        ]);
    }

    private function validate_status($result)
    {
        if (empty($result['status']) || $result['status'] != 'success') {
            SEOAICAjaxResponse::alert('Something went wrong, please try again. "Error: bad server status"')->wpSend();
        }
    }

    private function clusters_cards($clusters, $mode = 'pages', $toggle = false, $create_new = false)
    {
        $get_clusters =
            [
                [
                    "id" => esc_attr("cloneID"),
                    "name" => esc_html__("cluster name", "seoaic"),
                ]
            ];

        $toggle_class = 'no-toggle';
        $toggle_icon = '';

        if ($toggle) {
            $toggle_class = '';
            $toggle_icon = '<div class="cluster-toggle-icon"></div>';
        }

        $get_clusters = !$create_new ? array_merge($get_clusters, $clusters) : $clusters;
        $create_new_class = $create_new ? esc_attr(' new_cluster') : '';
        $html = '';
        foreach ($get_clusters as $i => $cluster) {
            $isClone = $cluster['id'] === 'cloneID';
            $class = $isClone ? 'seoaic-cluster-card-clone' : '';
            $hide = $isClone ? 'style="display:none"' : '';
            $pages = '';
            $pagesHtml = '<div class="inner-card inner-card-pages opacity-3">
                    <div id="seoaic_cluster_graph_id_' . esc_attr($i) . '" class="graph-chart">
                            <div class="chart-container"></div>
                            <div class="hiden-border-offset"></div>
                        </div>
                        <div class="article-row summary-articles">
                            <div class="count"><p></p><span>' . esc_html__('Posts', 'seoaic') . '</span></div>
                            <div class="views"><p>' . esc_html('0') . '</p><span>' . esc_html__('views', 'seoaic') . '</span></div>
                            <div class="clicks"><p>' . esc_html('0') . '</p><span>' . esc_html__('clicks', 'seoaic') . '</span></div>
                        </div>
                        <div class="seoaic-scroll-vertical text-center">
                            <div class="loader-cluster-content loader-ellipsis small mt-20"></div>
                        </div>
                        <button title="Apply" type="button" class="d-none" data-cluster-id="' . esc_attr($cluster['id']) . '" data-cluster-name="' . esc_attr($cluster['name']) . '" class="add-page-to-cluster-modal seoaic-button-small modal-button position-relative" data-modal="#seoaic-alert-modal" data-title="' . esc_html__('Select page', 'seoaic') . '" data-content="' . esc_attr($this->get_pages_list()) . '">
                            ' . esc_html__('Add page', 'seoaic') . '
                        </button>
                    </div>';

            $ideas = '';
//            if (!empty($cluster['ideas'])) {
//                foreach ($cluster['ideas'] as $page) {
//                    $ideas .= '
//                    <div class="article-row" data-id="' . esc_attr($page['id']) . '">
//                        <div class="title">' . esc_html($page['title']) . '</div>
//                        <div class="clicks">
//                            <span class="remove dashicons dashicons-no-alt red seoaic-ajax-form seoaic-ajax-submit">
//                                <input type="hidden" class="seoaic-ajax-field" name="action" value="seoaic_onboarding_cluster_ideas_remove">
//                                <input type="hidden" class="seoaic-ajax-field" name="id" value="' . esc_attr($page['id']) . '">
//                                <input type="hidden" class="seoaic-ajax-field" name="cluster_id" value="' . esc_attr($cluster['id']) . '">
//                            </span>
//                        </div>
//                    </div>';
//                }
//            }

            $ideasHtml = '<div class="inner-card inner-card-ideas seoaic-pt-0 opacity-3">
                                <div class="article-row summary-articles">
                                    <div class="count">
                                        <p></p><span>' . esc_html__('Ideas', 'seoaic') . '</span>
                                    </div>
                                </div>
                                <div class="seoaic-scroll-vertical text-center">
                                    <div class="loader-cluster-content loader-ellipsis small mt-20"></div>
                                </div>
                                <button title="Apply" type="button" class="seoaic-magic-button seoaic-ajax-form seoaic-ajax-submit d-none">
                                    <input type="hidden" class="seoaic-ajax-field" name="action" value="seoaic_onboarding_cluster_ideas_generate">
                                    <input type="hidden" class="seoaic-ajax-field" name="id" value="' . esc_attr($cluster['id']) . '">
                                    <input type="hidden" class="seoaic-ajax-field" name="quantity" value="10">
                                    ' . esc_html__('Generate more ideas', 'seoaic') . '
                                </button>
                            </div>';

            $html .= '
            <div class="seoaic-cluster-card ' . $class . $create_new_class . '" ' . $hide . ' data-id="' . esc_attr($cluster['id']) . '" data-name="' . esc_attr($cluster['name']) . '">
                <div class="inner">
                    <div class="top-card ' . $toggle_class . '">
                        <input class="seoaic-checkbox" data-id="' . esc_attr($cluster['id']) . '" type="checkbox" id="seoaic_check_cluster_id_' . esc_attr($cluster['id']) . '">
                        <form id="seoaic_cluster-name-update-form-' . esc_attr($cluster['id']) . '" class="claster-name-form d-flex seoaic-ajax-form w-100">
                            <input type="hidden" class="seoaic-ajax-field" name="action" value="seoaic_cluster_update">
                            <input type="hidden" class="seoaic-ajax-field" name="desc" value="">
                            <input type="hidden" class="seoaic-ajax-field" name="id" value="' . esc_attr($cluster['id']) . '">
                            <input class="seoaic-ajax-field seoaic-w-50" name="name" id="seoaic_check_cluster_id_' . esc_attr($cluster['id']) . '" value="' . esc_attr($cluster['name']) . '">
                            <input type="submit" class="accent ml-15 seoaic-ajax-submit" value="update">
                        </form>
                        ' . $toggle_icon . '
                        <span class="edit ml-auto"></span>
                        <span class="save idea-btn dashicons dashicons-yes seaoic_color-green seoaic-ajax-form seoaic-ajax-submit">
                            <input type="hidden" class="seoaic-ajax-field" name="action" value="seoaic_cluster_update">
                            <input id="seoaic_check_cluster_id_change_' . esc_attr($cluster['id']) . '" type="hidden" class="seoaic-ajax-field" name="name" value="' . esc_attr($cluster['name']) . '">
                            <input type="hidden" class="seoaic-ajax-field" name="desc" value="">
                            <input type="hidden" class="seoaic-ajax-field" name="id" value="' . esc_attr($cluster['id']) . '">
                        </span>
                        <span class="remove dashicons dashicons-no-alt red seoaic-ajax-form seoaic-ajax-submit">
                            <input type="hidden" class="seoaic-ajax-field" name="action" value="seoaic_cluster_delete">
                            <input type="hidden" class="seoaic-ajax-field" name="id" value="' . esc_attr($cluster['id']) . '">
                        </span>
                    </div>
                    ' . $pagesHtml . '
                    ' . $ideasHtml . '
                </div>
            </div>';
        }

        return $html;
    }

    public function get_pages_list($hide_if_scanned = false, $suggested_pages = false)
    {
        $display_style = '';

        if ($hide_if_scanned) {
            if ($this->clusters_generated_status() || $this->send_pages_progress()) {
                $display_style = esc_attr('display: none');
            }
        }

        $suggested_pages = implode(',', $this->get_gsc_suggested_pages_data());

        $post_types = seoaic_get_post_types();
        $get['paged'] = 1;

        ob_start();
        ?>
        <div id="seoaic_pages_filter_section"
             class="ai-start jc-sb mb-19 seoaic-flex-column" style="<?php echo $display_style; ?>">
            <div class="filters-switcher mt-15">
                <div class="seoaic-filter-rows">
                    <div class="seoaic-filter-row top">
                        <div class="filter-row-wrap">
                            <div class="d-flex ai-center">
                                <label class="mr-15"><?php echo esc_html__('Select the post type:', 'seoaic'); ?></label>
                                <a href="#" data-post-type="" class="seoaic-filter-btn active">
                                    <?php echo esc_html__('Any', 'seoaic'); ?>
                                </a>
                                <?php foreach ($post_types as $post_type) : ?>
                                    <a href="#" data-post-type="<?php echo esc_attr($post_type) ?>"
                                       class="seoaic-filter-btn">
                                        <?php echo esc_html($post_type); ?>
                                    </a>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="search seoaic-search-box">
                <div class="seoaic-breath-loading search-box-loading"></div>
                <label class="text-label mr-15"><?php echo esc_html__('Search pages', 'seoaic'); ?></label>
                <input id="seoaic_search_pages_wizard_step" autocomplete="off" name="keyword" data-default=""
                       class="form-input" type="text"
                       data-placeholder="<?php echo esc_attr__('Filter by keyword', 'seoaic'); ?>"
                       placeholder="<?php echo esc_attr__('Enter keyword', 'seoaic'); ?>">
                <div class="clear"></div>
            </div>

            <div class="seoaic-filter-rows seoaic-mt-minus-35 ml-auto seoaic-pt-0">
                <div class="seoaic-filter-row d-none">
                    <label for="seoaic_display_full_pages_list" id="seoaic-selected-pages-step" data-selected-pages="<?php echo esc_attr($suggested_pages); ?>"
                           href="#" class="seoaic-filter-btn"></label>
                </div>
                <label for="seoaic_onboarding_show_selected_key_pages"><?php echo esc_html__('View selected ', 'seoaic'); ?>
                    <span class="data-selected-pages-count"><?php echo esc_html__('(0)', 'seoaic'); ?></span></label>
                <div class="seoaic_toggle_selector">
                    <input id="seoaic_onboarding_show_selected_key_pages" type="checkbox"
                           class="d-none seoaic_checkbox_toggle_selector seoaic-form-item"
                           name="seoai_auto_schedule" value="" disabled>
                    <label for="seoaic_onboarding_show_selected_key_pages" class="toggler"><span></span></label>
                </div>
            </div>
        </div>

        <div id="seoaic_all_pages_table"
             class="flex-table onboarding-table-pages seoaic-scroll-vertical mb-40" <?php echo $display_style; ?>>
            <div id="seoaic_load_more_pages" class="seoaic-ajax-submit seoaic-ajax-form text-center mt-10">
                <div id="seoaic-loader-auto-scheduled-posts" class="loader-ellipsis small"></div>
                <input type="hidden" class="seoaic-ajax-field" name="action" value="seoaic_get_all_site_links">
                <input type="hidden" class="seoaic-ajax-field" name="offset" value="0">
                <input type="hidden" class="seoaic-ajax-field" name="limit" value="10">
                <input type="hidden" class="seoaic-ajax-field" name="post_type" value="">
                <input type="hidden" class="seoaic-ajax-field" name="search" value="">
                <input type="hidden" class="seoaic-ajax-field" name="include_ids" value="">
                <input type="hidden" class="seoaic-ajax-field" name="exclude_ids" value="">
                <input type="hidden" class="seoaic-ajax-field" name="cluster_name" value="">
                <input type="hidden" class="seoaic-ajax-field" name="select_key_pages" value="1">
                <input type="hidden" class="seoaic-ajax-field" name="suggested_pages" value="<?php echo esc_attr($suggested_pages); ?>">
            </div>
        </div>
        <?php
        return ob_get_clean();
    }

    private function request_clusters($page = 1, $limit = false)
    {
        $data = [
            "page" => !empty($page) ? $page : 1,
        ];
        if (!empty($limit)) {
            $data['limit'] = $limit;
        }

        return $this->seoaic->curl->init('/api/clusters/list', $data, true, true, true);
    }

    public function get_ideas()
    {
        check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);

        global $SEOAIC;

        $page = wp_unslash($_POST['page']);

        $result = $this->request_clusters($page, false);

        if (empty($result['data'])) {
            return;
        }

        $current = $result['current_page'];
        wp_send_json([
            'clusters_cards' => $this->clusters_cards($result['data'], 'ideas'),
            'clusters_pagination' => $SEOAIC->explorer->inline_pagination(intval($current), intval($result['total_pages']), 'seoaic_onboarding_get_ideas')
        ]);
    }

    public function cluster_update()
    {
        check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);

        if (!current_user_can('edit_posts')) {
            SEOAICAjaxResponse::alert("Permission denied")->wpSend();
        }

        $post = wp_unslash($_POST);
        $data = [
            "id" => $post['id'],
            "name" => $post['name'],
            "description" => $post['desc'],
        ];

        $result = $this->seoaic->curl->init('api/clusters/update', $data, true, true, true);
        $cluster = !empty($result['data']) ? $result['data'] : [];
        $this->updateOrRemoveKeywordsCluster($cluster['id'], $cluster['name']);
        $this->clearKeywordsClustersTransient();
        wp_send_json($result);
    }

    public function cluster_delete()
    {
        check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);
        if (!current_user_can('edit_posts')) {
            SEOAICAjaxResponse::alert("Permission denied")->wpSend();
        }
        $post = wp_unslash($_POST);
        $ids_string = !empty($post['id']) ? $post['id'] : '';
        $ids_array = array_filter(array_map('trim', explode(',', $ids_string)));
        $ids = array_map('intval', $ids_array);
        $data = [
            "ids" => $ids
        ];
        $result = $this->seoaic->curl->init('api/clusters/remove', $data, true, true, true);
        foreach ($ids as $id) {
            $this->updateOrRemoveKeywordsCluster($id, null);
        }
        $this->clearKeywordsClustersTransient();
        wp_send_json($result);
    }

    private function insertClusters($names, $return = false) {
        $post = wp_unslash($_POST);
        $data = [];
        foreach ($names as $name) {
            $cluster = [
                "name"     => $name,
                "language" => $this->seoaic->multilang->get_selected_language(),
                "location" => SEOAIC_SETTINGS::getLocation(),
                "pages"    => []
            ];
            $data[] = $cluster;
        }

        $result = $this->seoaic->curl->init('api/clusters/create', $data, true, true, true);
        $clusters = !empty($result['data']) ? $result['data'] : [];

        if ($return) {
            return $clusters;
        }

        foreach ($clusters as $cluster) {
            $this->addKeywordsCluster($cluster['id'], $cluster['name']);
        }
        $this->clearKeywordsClustersTransient();
        $new_clusters = [];
        $toggle = true;

        if(!empty($post['no_toggle'])) {
            $toggle = false;
        }
        foreach ($clusters as $cluster) {
            $new_clusters[] = [
                'id'   => $cluster['id'],
                'name' => $cluster['name'],
                'html' => $this->clusters_cards([$cluster], '', $toggle, true)
            ];
        }

        wp_send_json($new_clusters);
    }

    public function create_cluster($insert_names = null)
    {
        check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);

        if (!current_user_can('edit_posts')) {
            SEOAICAjaxResponse::alert("Permission denied")->wpSend();
        }

        $post = wp_unslash($_POST);

        if (empty($post['clusters']) && empty($post['names'])) {
            return;
        }

        $names = [];
        if(!empty($post['names'])) {
            $names = explode("\n", $post['names']);
            $names = array_filter(array_map('trim', $names));
        }

        if (!empty($post['clusters'])) {
            foreach ($post['clusters'] as $i => $cluster) {
                $post['clusters'][$i]['pages'] = [];
            }
            $created = $this->seoaic->curl->initWithReturn('api/clusters/create', $post['clusters'], true, true, true);
            $clusters = !empty($created['data']) ? $created['data'] : [];
            foreach ($clusters as $cluster) {
                $this->addKeywordsCluster($cluster['id'], $cluster['name']);
            }
            wp_send_json_success();
        }

        $this->insertClusters($names);
    }

    public function add_page_to_cluster()
    {
        check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);

        if (!current_user_can('edit_posts')) {
            SEOAICAjaxResponse::alert("Permission denied")->wpSend();
        }

        $post = wp_unslash($_POST);
        $id = $post['cluster_id'];
        $cluster_name = !empty($post['cluster_name']) ? $post['cluster_name'] : '';
        $included_ids = !empty($post['selected_pagest_ids']) ? explode(',', $post['selected_pagest_ids']) : [];

        if (empty($included_ids)) {
            return;
        }

        $data = [
            "cluster_id" => $id,
            "pages" => $this->get_requested_posts(0, 100, [], $included_ids)['data']
        ];

        $result = $this->seoaic->curl->init('api/clusters/' . $id . '/add-pages', $data, true, true, true);

        if (empty($result['status']) || $result['status'] != 'success') {
            SEOAICAjaxResponse::alert('Something went wrong, please try again. "Error: response status"')->wpSend();
        }

        if ($cluster_name) {
            foreach ($included_ids as $post_id) {
                $posted_value = get_post_meta($post_id, 'seoaic_posted', true);
                if (!empty($posted_value)) {
                    update_post_meta($post_id, 'seoaic_cluster', $cluster_name);
                }
            }
        }

        wp_send_json($result);
    }

    public function remove_page_from_cluster()
    {
        check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);

        if (!current_user_can('edit_posts')) {
            SEOAICAjaxResponse::alert("Permission denied")->wpSend();
        }

        $cluster_id = $_POST['cluster_id'];
        $page_id = $_POST['page_id'];
        $data = [
            "ids" => [$page_id]
        ];

        $result = $this->seoaic->curl->init('api/clusters/' . $cluster_id . '/remove-pages', $data, true, true, true);

        delete_post_meta($page_id, 'seoaic_cluster');

        wp_send_json($result);
    }

    private function cluster_cards_preload()
    {
        $card = '
        <div class="seoaic-cluster-card seoaic-animate-pulse seoaic-cluster-card-preload">
            <div class="inner">
                <div class="top-card">
                    <label class="title">' . esc_html('Loading') . '</label>
                </div>
                <div class="inner-card">
                    <div class="article-row summary-articles">
                        <div class="count"><p>' . esc_html('0') . '</p><span>' . esc_html('Articles') . '</span></div>
                        <div class="views"><p>' . esc_html('0') . '</p><span>' . esc_html('views') . '</span></div>
                        <div class="clicks"><p>' . esc_html('0') . '</p><span>' . esc_html('clicks') . '</span></div>
                    </div>
                    <div class="seoaic-scroll-vertical"></div>
                    <button title="Apply" type="button" data-cluster-id="0" class="add-page-to-cluster-modal seoaic-button-small modal-button position-relative" data-modal="#seoaic-alert-modal" data-title="Select page">' . esc_html('Loading') . '</button>
                </div>
            </div>
        </div>
        ';

        $html = '
        <div class="seoaic-cluster-card seoaic-cluster-card-clone" data-graph-searches="[]" style="display:none">
                <div class="inner">
                    <div class="top-card">
                        <input class="seoaic-checkbox" type="checkbox" id="seoaic_check_cluster_id_cloneID">
                        <label class="title" for="seoaic_check_cluster_id_cloneID">' . esc_html('cluster name') . '</label>
                        <div class="edit"></div>
                        <span class="save idea-btn dashicons dashicons-yes seaoic_color-green seoaic-ajax-form seoaic-ajax-submit">
                            <input type="hidden" class="seoaic-ajax-field" name="action" value="seoaic_cluster_update">
                            <input id="seoaic_check_cluster_id_change_cloneID" type="hidden" class="seoaic-ajax-field" name="name" value="cluster name">
                            <input type="hidden" class="seoaic-ajax-field" name="desc" value="">
                            <input type="hidden" class="seoaic-ajax-field" name="id" value="cloneID">
                        </span>
                        <span class="remove dashicons dashicons-no-alt red seoaic-ajax-form seoaic-ajax-submit">
                            <input type="hidden" class="seoaic-ajax-field" name="action" value="seoaic_cluster_delete">
                            <input type="hidden" class="seoaic-ajax-field" name="id" value="cloneID">
                        </span>
                    </div>
                    <div class="inner-card">
                        <div id="seoaic_cluster_graph_id_0" class="graph-chart">
                            <div class="chart-container"></div>
                            <div class="hiden-border-offset"></div>
                        </div>
                        <div class="article-row summary-articles">
                            <div class="count"><p>' . esc_html('0') . '</p><span>' . esc_html('articles') . '</span></div>
                            <div class="views"><p>' . esc_html('0') . '</p><span>' . esc_html('views') . '</span></div>
                            <div class="clicks"><p>' . esc_html('0') . '</p><span>' . esc_html('clicks') . '</span></div>
                        </div>
                        <div class="seoaic-scroll-vertical"></div>
                        <button title="Apply" type="button" data-cluster-id="cloneID" class="add-page-to-cluster-modal seoaic-button-small modal-button position-relative" data-modal="#seoaic-alert-modal" data-title="Select page" data-content="' . esc_attr($this->get_pages_list()) . '">
                            ' . esc_html('Add page') . '
                        </button>
                    </div>
                </div>
            </div>
        ';
        for ($i = 0; $i < 9; $i++) {
            $html .= $card;
        }

        return $html;
    }

    public function content_strategy_html_ajax()
    {
        check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);

        $html = $this->content_strategy_html();

        wp_send_json($html);
    }

    public function content_strategy_html($return = false)
    {
        global $SEOAIC_OPTIONS;

        $labels = [
            'heading' => esc_html__('Content Strategy for:', 'seoaic'),
            'industry' => esc_html__('Identified Industry', 'seoaic'),
            'description' => esc_html__('Company description', 'seoaic'),
            'target' => esc_html__('Target Audience Insights', 'seoaic'),
            'services' => esc_html__('Services Insights', 'seoaic'),
            'clusters' => esc_html__('Core Topic Pillars (Content Clusters)', 'seoaic'),
            'addCluster' => esc_html__('+ Add cluster', 'seoaic'),
            'monthlyBtn' => esc_html__('Generate 12-Month Rollout Plan', 'seoaic'),
            'remove' => esc_html__('Remove selected', 'seoaic'),
            'select_all' => esc_html__('Select all', 'seoaic'),
        ];
        $industryName = SEOAIC_SETTINGS::getIndustry();
        $companyUrl = SEOAIC_SETTINGS::getCompanyWebsite();
        $companyExistingDesc = !empty($SEOAIC_OPTIONS['seoaic_business_description']) ? $SEOAIC_OPTIONS['seoaic_business_description'] : '';
        $targetAudience = array_slice($this->get_services_and_audience('seoaic_target_audience') ?? [], 0, 3);
        $services = array_slice($this->get_services_and_audience('seoaic_services') ?? [], 0, 3);
        $clusterIdeas = $this->request_clusters(1, 100);
        $industryGenerated = !empty($industryName) ? $industryName : ($clusterIdeas['data_info']['industry'] ?? '');
        $descriptionGenerated = $companyExistingDesc ? $companyExistingDesc : ($clusterIdeas['data_info']['company_description'] ?? '');
        $companyDescription = $this->step_company_description_html($descriptionGenerated, $industryGenerated);

        $html = '<h3>' . $labels['heading'] . ' <a href="' . esc_url($companyUrl) . '" target="_blank" rel="noopener noreferrer" class="accent accent-underline">' . esc_html($companyUrl) . '</a></h3>';

        if ($industryGenerated) {
            $input = '<input id="seoaic_industry_field" type="text" class="form-input light seoaic_industry_field" name="seoaic_services-input" value="' . $industryGenerated . '">';
            $html .= $this->render_info_box($labels['industry'], $input);
        }
        if ($companyDescription) {
            $html .= $this->render_info_box($labels['description'], $companyDescription);
        }
        if ($targetAudience) {
            $html .= $this->render_info_box($labels['target'], $this->step_service_offerings_html('seoaic_target_audience'), true);
        }
        if ($services) {
            $html .= $this->render_info_box($labels['services'], $this->step_service_offerings_html('seoaic_services'), true);
        }

        $clusters_section = <<<HTML
        <div class="ai-center d-flex jc-sb mt-0 top-cluster-section">
            <input class="ml-15 seoaic-checkbox" type="checkbox" id="seoaic_check_all_clusters">
            <label for="seoaic_check_all_clusters" class="h3 mb-5 ml-10 mt-0">{$labels['select_all']}</label>
            <div class="ml-auto seoaic-ajax-form seoaic-ajax-submit">
                <button title="{$labels['remove']}" type="button" id="seoaic_clusters_to_remove_label" class="d-none seoaic-remove"></button>
                <input type="hidden" class="seoaic-ajax-field" name="action" value="seoaic_cluster_delete">
                <input id="seoaic_clusters_to_remove_input" type="hidden" class="seoaic-ajax-field" name="id" value="">
            </div>
        </div>
        <div id="seoaic_clusterized_articles_table">
            <div class="seoaic-grid-view seoaic-grid-view-list">
                {$this->clusters_cards($clusterIdeas['data']['data'], 'pages', true)}
                <button id="seoaic_add_new_service_cluster" class="add-new-service-button mt-20 modal-button" data-modal="#seoaic-add-clusters-modal">
                    <span>{$labels['addCluster']}</span>
                </button>
            </div>
        </div>
        <div class="text-center seoaic-mb-80 mt-40 d-none">
            <button type="button" id="seoaic_generate_rollout_plan" class="button-primary seoaic-button-primary generate-keyword-based">{$labels['monthlyBtn']}</button>
        </div>
        HTML;

        if ($clusterIdeas) {
            $html .= $this->render_info_box($labels['clusters'], $clusters_section, true);
        }

        return $html;
    }

    private function seoaic_get_onboarding_schedule_ideas($how_many_month, $posts_per_month_per_cluster, $selected_clusters, $selected_content_types, $starting_date)
    {
        global $SEOAIC, $SEOAIC_OPTIONS;
        $post = wp_unslash($_POST);
        $months = max(1, (int)$how_many_month);
        $posts_per_month = max(1, (int)$posts_per_month_per_cluster);
        $clusters = array_filter(array_map('intval', $selected_clusters ?? []));
        $content_types = array_filter(array_map('trim', $selected_content_types ?? []));

        if (empty($clusters)) {
            SEOAICAjaxResponse::alert('No clusters selected.')->wpSend();
        }

        $total_posts = $months * $posts_per_month * count($clusters);
        $days = $months * 30;

        $max_allowed_posts = floor($days * 5);

        if ($total_posts > $max_allowed_posts) {
            SEOAICAjaxResponse::alert("Too many posts for that period.<br><br>For {$months} month(s) max {$max_allowed_posts} posts are allowed or 5 per day.")->wpSend();
        }

        if (empty($content_types)) {
            $content_types = ['default'];
        }

        $ideas = [];

        foreach ($clusters as $cluster_id) {
            $total_ideas = $months * $posts_per_month;
            $content_type_ideas = [];

            if ($total_ideas >= count($content_types)) {
                $base = intdiv($total_ideas, count($content_types));
                $remainder = $total_ideas % count($content_types);

                foreach ($content_types as $type) {
                    $content_type_ideas[$type] = $base;
                }

                $shuffled = $content_types;
                shuffle($shuffled);
                for ($i = 0; $i < $remainder; $i++) {
                    $content_type_ideas[$shuffled[$i]]++;
                }
            } else {
                $shuffled = $content_types;
                shuffle($shuffled);
                $selected = array_slice($shuffled, 0, $total_ideas);

                foreach ($selected as $type) {
                    if (!isset($content_type_ideas[$type])) {
                        $content_type_ideas[$type] = 0;
                    }
                    $content_type_ideas[$type]++;
                }
            }

            $ideas[] = [
                'clusterId' => $cluster_id,
                'contentType' => $content_type_ideas,
            ];
        }

        $date = new DateTime('@' . $starting_date);
        $date->setTimezone(new DateTimeZone('UTC'));
        $iso8601 = $date->format('Y-m-d\TH:i:s') . '.000Z';

        $data = [
            'title' => !empty($SEOAIC_OPTIONS['seoaic_business_name']) ? $SEOAIC_OPTIONS['seoaic_business_name'] : get_option('blogname', true),
            'description' => get_option('blogdescription', true),
            'monthsNumber' => $months,
            'startingDate' => $iso8601,
            'startingTime' => SEOAIC_SETTINGS::getScheduledPostingTime(),
            'ideasToGenerate' => $ideas,
            "language" => $SEOAIC->multilang->filter_request_multilang(),
            'selectedServices' => '',
            "generateKeywordsSeparately" => false
        ];

        if (!empty($post['seoaic-ob-select-services'])) {
            $data['selectedServices'] = SEOAIC_SETTINGS::getSelectedRepeaterValues('seoaic_services', $post['seoaic-ob-select-services'], true);
        }

        if (!empty($post['seoaic-ob-select-targets'])) {
            $data['selectedTargetAudience'] = SEOAIC_SETTINGS::getSelectedRepeaterValues('seoaic_target_audience', $post['seoaic-ob-select-targets'], true);
        }

        if (!empty($post['seoaic-select-ob-keywords'])) {
            $data['keywords'] = implode(', ', $post['seoaic-select-ob-keywords']);
        }

        if (!empty($post['CustomPrompt'])) {
            $data['prompt'] = $post['CustomPrompt'];
        }

        $request = $this->seoaic->curl->init('api/cluster-ideas/bulk-generate', $data, true, true, true);

        if ($request['status'] === 'success') {
            return [
                'status' => 'in_progress'
            ];
        }

        return false;
    }

    private function mini_toggle($label, $input_name = null, $is_radio = false, $radio_name = 'radio_name', $is_checked = false, $custom_class = '')
    {
        $slug = sanitize_title($label);
        $name = $is_radio ? $radio_name : ($input_name ? $input_name : $slug);
        $type = $is_radio ? 'radio' : 'checkbox';
        $id = esc_attr(sanitize_title($label) . '_' . rand(100, 999999));
        $checked = $is_checked ? 'checked' : '';
        $radio_class = $is_radio ? 'radio' : '';
        $value = $is_radio ? ($input_name ? $input_name : $slug) : '';
        return '<div class="seoiac-toggle-mini">
                <label for="seoaic-mini_toggle-' . $id . '">' . esc_html($label) . '</label>
                <input ' . esc_attr($checked) . ' id="seoaic-mini_toggle-' . $id . '" type="' . esc_attr($type) . '" name="' . esc_attr($name) . '" value="' . esc_attr($value) . '" class="' . esc_attr($custom_class) . '" />
                <label for="seoaic-mini_toggle-' . $id . '" class="toggler ' . esc_attr($radio_class) . '"><span></span></label>
                </div>';
    }

    private function optimzed_flow_selections()
    {
        return '<select
                    name="seoaic_optimize_post_type"
                    class="seoaic-form-item form-select seoaic-ajax-field"
                    title="' . esc_html__("Optimized flow type", "seoaic") . '">
                    <option value="base">' . esc_html__("Base", "seoaic") . '</option>
                    <option value="humanize">' . esc_html__("Humanize", "seoaic") . '</option>
                    <option value="internal_links">' . esc_html__("Internal links", "seoaic") . '</option>
                </select>';
    }

    private function leads_form_selections($idea_id)
    {
        return wp_kses(LeadsFormGenerate::formElements('post-mass-creation-form', $idea_id, 'seoaic-ajax-field'), [
            'div' => [
                'id' => [],
                'class' => [],
            ],
            'label' => [
                'id' => [],
                'class' => [],
            ],
            'input' => [
                'id' => [],
                'class' => [],
                'name' => [],
                'type' => [],
                'form' => [],
            ],
            'select' => [
                'id' => [],
                'class' => [],
                'name' => [],
                'form' => [],
            ],
            'option' => [
                'value' => [],
                'selected' => [],
                'class' => [],
            ],
            'textarea' => [
                'name' => [],
                'class' => [],
            ],
        ]);
    }

    private function generate_attributes($idea_id, $class = '')
    {
        global $SEOAIC, $SEOAIC_OPTIONS;

        $currentDate = date('Y-m-d');
        $date = new DateTime($currentDate);
        $publish_delay = !empty($SEOAIC_OPTIONS['seoaic_publish_delay']) ? intval($SEOAIC_OPTIONS['seoaic_publish_delay']) : 0;
        $date->modify("+$publish_delay hours");
        $delayDate = $date->format('Y-m-d');

        $html = '<div class="idea-ob-selections seoaic-ajax-form ' . esc_attr($class) . '">';
        $html .= '<input type="hidden" class="seoaic-ajax-field" name="action" value="seoaic_posts_mass_create">';
        $html .= '<input type="hidden" class="seoaic-ajax-field" name="idea-mass-create" value="' . esc_attr($idea_id) . '">';
        $html .= '<input type="hidden" class="seoaic-ajax-field" name="thumbnail_generation_prompt">';
        $html .= '<input type="hidden" class="seoaic-ajax-field" name="thumbnail_generation_width" value="' . esc_attr(SEOAIC_SETTINGS::getImageGenerateWidthDefault()) . '">';
        $html .= '<input type="hidden" class="seoaic-ajax-field" name="thumbnail_generation_height" value="' . esc_attr(SEOAIC_SETTINGS::getImageGenerateHeightDefault()) . '">';
        $html .= '<input type="hidden" class="seoaic-ajax-field" name="generate_thumbnail_style" value="' . esc_attr(SEOAIC_SETTINGS::getImageGenerateStyle()) . '">';
        $html .= '<input type="hidden" class="seoaic-ajax-field" name="seoaic_subtitles_range_min" value="' . esc_attr(SEOAIC_SETTINGS::getSubtitlesRangeMin()) . '">';
        $html .= '<input type="hidden" class="seoaic-ajax-field" name="seoaic_subtitles_range_max" value="' . esc_attr(SEOAIC_SETTINGS::getSubtitlesRangeMax()) . '">';
        $html .= '<input type="hidden" class="seoaic-ajax-field" name="seoaic_words_range_min" value="' . esc_attr(SEOAIC_SETTINGS::getWordsRangeMin()) . '">';
        $html .= '<input type="hidden" class="seoaic-ajax-field" name="seoaic_words_range_max" value="' . esc_attr(SEOAIC_SETTINGS::getWordsRangeMax()) . '">';
        if ($SEOAIC->multilang->is_multilang()) {
            $html .= '<input type="hidden" class="seoaic-ajax-field" name="seoaic-translate-from-origin" value="' . esc_attr('yes') . '">';
        }
        //$html .= '<input type="hidden" class="seoaic-ajax-field" name="seoaic_post_status" value="' . esc_attr('draft') . '">';
        $html .= '<div class="seoaic-left-col">';
        $html .= '<div class="seoaic-popup__field">';
        $html .= '<label class="mb-5">' . esc_html__('Custom prompt', 'seoaic') . '</label>';
        $html .= '<textarea name="mass_prompt" class="seoaic-form-item mt-0 seoaic-ajax-field"></textarea>';
        $html .= '<div class="d-flex">';
        $html .= '<div class="d-flex flex-column">';
        $html .= $this->mini_toggle('Generate image', 'seoaic_generate_thumbnail');
        $html .= $this->mini_toggle('New content generation flow (experimental)', 'seoaic_experimental_generation_post');
        $html .= $this->mini_toggle('Optimized flow', 'seoaic_optimize_post');
        $html .= '<div class="display-none mb-13 mt-5 seoaic-show-on-toggle">' . $this->optimzed_flow_selections() . '</div>';
        $html .= $this->mini_toggle('Add FAQ section', 'seoaic_add_faq');
        $html .= $this->mini_toggle('Generate Leads Form', 'generate_leads_form');
        $html .= '<div class="display-none mb-13 mt-5 seoaic-show-on-toggle">' . $this->leads_form_selections($idea_id) . '</div>';
        $html .= $this->mini_toggle('Make article interactive', 'interactive_article');
        $html .= '</div>';
        $html .= '<div class="d-flex flex-column seoaic-w-50">';
        $html .= '<label class="seoaic-mt-auto">' . esc_html__('Schedule options', 'seoaic') . '</label>';
        $html .= $this->mini_toggle('Leave draft', 'draft', true, 'seoaic_post_status', false, 'not-send-ajax');
        $html .= $this->mini_toggle('Publish immediately', 'publish', true, 'seoaic_post_status');
        $html .= $this->mini_toggle('Delay publication', 'delay', true, 'seoaic_post_status');
        $html .= $this->mini_toggle('Schedule publication', 'schedule', true, 'seoaic_post_status');
        $html .= '<div class="display-none mb-13 mt-5 seoaic-show-on-toggle"><input name="seoaic-mass-idea-date" type="date" class="seoaic-ajax-field" min="' . esc_attr($delayDate) . '" value="' . esc_attr($delayDate) . '"></div>';
        $html .= '</div>';
        $html .= '</div>';
        $html .= '</div>';
        $html .= '</div>';
        $html .= '<div class="seoaic-right-col">';
        $html .= seoaic_get_categories(SEOAIC_SETTINGS::getSEOAICPostType(), 0, true);
        $html .= SEOAIC_SETTINGS::createRepeaterHTML('seoaic_services', true, false, false, 'seoaic-ajax-field');
        $html .= SEOAIC_SETTINGS::createRepeaterHTML('seoaic_target_audience', true, false, false, 'seoaic-ajax-field');
        $html .= '<label class="mb-15 mt-10">' . esc_html__('Select knowledge base', 'seoaic') . '</label>';
        $html .= '<select name="seoaic_knowledge_base" class="seoaic-form-item form-select seoiac-ob-select-knowledge-base seoaic-ajax-field" data-placeholder=' . esc_html__('Knowledge base', 'seoaic') . '">';
        $html .= '<option value="" class="seoiac-ob-select-knowledge-base-placeholder" selected disabled hidden>' . esc_html__('Choose here knowledge base', 'seoaic') . '</option>';
        $html .= '</select>';
        $html .= '</div>';
        $html .= '<span class="seoaic-ajax-submit d-none"></span>';
        $html .= '</div>';

        return $html;
    }

    public function get_mass_generate_selections()
    {
        return $this->generate_attributes(0, 'w-100 mb-19 mass_generate_ob_ideas_selections');
    }

    private function generate_post_button($ideaId)
    {
        $html = '<button data-idea-id="' . $ideaId . '" class="seoaic_edit_meta_generate seoaic-branded-button" data-generating="' . esc_attr__('Generating', 'seoaic') . '" data-generate="' . esc_attr__('Generate', 'seoaic') . '" type="button">';
        $html .= esc_html__('Generate', 'seoaic');
        $html .= '</button>';

        return $html;
    }

    private function ideasListHtml($ideaId, $title, $clusterName, $contentType, $postingDate, $status = null, $language = null, $keywords = null, $accepting_ideas = null, $postGenerationOption = null)
    {
        global $SEOAIC;

        $current_flag_safe = '';
        $is_accepted = '';
        $get_post = false;
        if ($accepting_ideas) {
            $get_post = get_post($ideaId);
            $post_language = $SEOAIC->multilang->get_post_language($ideaId);
            $current_flag_safe = $SEOAIC->multilang->get_language_flag_img($post_language);
            $is_accepted = esc_attr('is_accepted ');
        }
        $idea_status = 'idea';
        $process_ideas = !empty($postGenerationOption['total']) ? $postGenerationOption['total'] : [];
        $process_posts = !empty($postGenerationOption['done']) ? $postGenerationOption['done'] : [];
        $generating_status = in_array($ideaId, $process_ideas) && !in_array($ideaId, $process_posts) ? ' post-is-generating' : '';
        $seoaic_generate_status = get_post_meta($ideaId, 'seoaic_generate_status', true);
        $failed_status = $seoaic_generate_status === 'failed' ? ' failed' : '';
        $generate_button_label = $generating_status ? esc_attr__('Generating', 'seoaic') : esc_attr__('Generate', 'seoaic');
        $button_label = $generate_button_label ?: esc_attr__('View post', 'seoaic');
        $lang = $SEOAIC->multilang->get_language_by($language);
        $data_lang_code = '';
        if (is_array($lang) && isset($lang['code'])) {
            $data_lang_code = esc_attr($lang['code']);
        }
        if ($get_post && $get_post->post_date_gmt != '3000-01-01 00:00:00' && $status != 'seoaic-idea') {
            $idea_status = 'generated';
        }
        if ($generating_status) {
            $idea_status = $generating_status;
        }

        $cluster_field = '';
        if($clusterName) {
            $cluster_field = '<span><b>' . esc_html__('Cluster: ', 'seoaic') . '</b>' . esc_html($clusterName) . '</span>';
        }

        $html = '<li
        id="' . esc_attr('seoaic-ob-list-idea-' . $ideaId) . '"
        data-language-code="' . esc_attr($data_lang_code) . '"
        data-cluster="' . esc_attr($clusterName) . '"
        data-id="' . esc_attr($ideaId) . '"
        data-date="' . esc_attr($postingDate) . '"
        data-idea-type="' . esc_attr($contentType) . '"
        data-language="' . esc_attr($language) . '"
        data-keywords="' . esc_attr(json_encode($keywords)) . '"
        data-title="' . esc_attr($title) . '"
        class="seoaic-schedule-idea-list seoaic-schedule-ob-idea-list ' . $is_accepted . esc_attr($generating_status . ' ' . $failed_status) . '">';

        $html .= '<div class="seoaic-ob-idea-top d-flex">';
        if ($accepting_ideas) {
            $html .= '<div class="seoaic_pre_title_checkbox"><input data-status="' . esc_attr(trim($idea_status)) . '" data-id="' . esc_attr($ideaId) . '" type="checkbox" class="seoaic-checkbox"></div>';
        }
        $html .= '  <div class="seoaic_pre_title_wrap">';
        $html .= '    <span class="seoaic_pre_title_id">' . esc_html($ideaId) . '</span>';
        $html .= $current_flag_safe;
        $html .= '  </div>';
        $html .= '  <div class="seoaic-mr-20 ml-10 w-100 seoaic-scheduled-idea-details">';
        $html .= '    <span id="seoaic_ob_post_title_' . $ideaId . '" class="seoaic-scheduled-idea-title seoaic-fw-500 fs-16">' . esc_html($title) . '</span>';
        $html .= '    <p class="mt-5 mb-0 seoaic-fs-13 seoaic-opacity-medium lh-1"><b>' . esc_html__('Schedule date: ', 'seoaic') . '</b>' . esc_html($postingDate) . '</p>';
        $html .= '    <div class="seoaic-schedule-post-info seoaic-fs-13 seoaic-opacity-medium">';
        $html .= $cluster_field;
        $html .= '      <span><b>' . esc_html__('Content type: ', 'seoaic') . '</b>' . esc_html($contentType) . '</span>';
        //$html .= '      <span><b>' . esc_html__('Status: ', 'seoaic') . '</b>' . esc_html($status) . '</span>';
        $html .= '    </div>';
        $html .= '  </div>';

        $html .= '  <div class="seoaic-edit-scheduled-idea-buttons d-flex">';

        if ($accepting_ideas) {
            if ($get_post && $get_post->post_date_gmt != '3000-01-01 00:00:00' && $status != 'seoaic-idea') {
                $html .= '  <a href="' . get_edit_post_link($ideaId) . '" data-id="' . $ideaId . '" title="' . esc_attr__('Opens in a new window', 'seoaic') . '" target="_blank" class="seoaic_edit_meta_open_editor seoai-border-0 seoai-color-white seoai-bg-black seoaic-button-small position-relative">'
                    . esc_html__('Open editor', 'seoaic') . '</a>';
            }
        }

        $html .= '    <button data-idea-id="' . esc_attr($ideaId) . '" class="seoaic_edit_service" type="button"></button>';

        $html .= '    <button data-idea-id="' . esc_attr($ideaId) . '" class="seoaic_edit_meta_save seoaic-ajax-form seoaic-ajax-submit ml-0" type="button">
                    <input type="hidden" class="seoaic-ajax-field" name="action" value="seoaic_onboarding_cluster_ideas_update">
                    <input type="hidden" class="seoaic-ajax-field" name="id" value="' . esc_attr($ideaId) . '">
                    <input type="hidden" class="seoaic-ajax-field" name="title" value="' . esc_attr($title) . '">
                  </button>';

        $html .= '    <button data-idea-id="' . esc_attr($ideaId) . '" class="seoaic_edit_meta_cancel seoaic-ajax-form seoaic-ajax-submit" type="button">
                    <input type="hidden" class="seoaic-ajax-field" name="action" value="seoaic_onboarding_cluster_ideas_remove">
                    <input type="hidden" class="seoaic-ajax-field" name="remove_accepted" value="' . $accepting_ideas . '">
                    <input type="hidden" class="seoaic-ajax-field" name="id" value="' . esc_attr($ideaId) . '">
                  </button>';

        $html .= '<a href="#" class="seoaic_edit_meta_stop_all accent accent-underline">' . esc_html__('Stop All', 'seoaic') . '</a>';

        if ($accepting_ideas) {
            $html .= '<button data-idea-id="' . esc_attr($ideaId) . '" class="seoaic_edit_meta_settings dashicons dashicons-admin-generic" type="button"></button>';

            if ($get_post && $get_post->post_date_gmt != '3000-01-01 00:00:00' && $status != 'seoaic-idea') {
                $html .= '<button data-idea-id="' . esc_attr($ideaId) . '" data-accepted="' . esc_attr__('Accepted', 'seoaic') . '" class="seoaic_edit_meta_edit_post seoaic_edit_meta_generate seoaic-branded-button" type="button">'
                    . esc_html__('Review Post', 'seoaic') . '</button>';
            } else {
                $html .= '<button id="seoaic_generate_post_from_idea_' . esc_attr($ideaId) . '" data-idea-id="' . esc_attr($ideaId) . '" class="seoaic_edit_meta_generate seoaic-branded-button" data-generating="' . esc_attr__('Generating', 'seoaic') . '" data-generate="' . esc_attr__('Generate', 'seoaic') . '" type="button">'
                    . esc_html($button_label) . '</button><span class="loader-ellipsis extra-small"></span>';
            }
        }

        $html .= '  </div>';
        $html .= '</div>';

        if ($accepting_ideas) {
            if ($get_post && $get_post->post_date_gmt != '3000-01-01 00:00:00' && $status != 'seoaic-idea') {
                $html .= '<div id="seoaic_editor_review_' . esc_attr($ideaId) . '" data-idea-id="' . esc_attr($ideaId) . '" class="seoaic_editor_review"></div>';
            } else {
                $html .= '<div id="seoaic_settings_review_' . esc_attr($ideaId) . '" data-idea-id="' . esc_attr($ideaId) . '" class="seoaic_ob_settings_review">'
                    . $this->generate_attributes($ideaId, $postingDate) . '</div>';
            }
        }

        $html .= '</li>';

        return $html;
    }

    /**
     * @throws Exception
     */
    private function createIdeasHTML($clusters, $get_created = false, $postGenerationOption = null, $generate_for_cluster = false)
    {
        if (empty($clusters)) {
            return '<ul><li>' . esc_html__('No content plan data found.', 'seoaic') . '</li></ul>';
        }

        $html = '<div class="seoaic-scroll-vertical seoaic-created-ob-ideas">';
        //$html .= '<div class="seoaic-top-actions-on-ideas mb-10"><label id="seoaic-select-all-ob-ideas" class="accent accent-underline">' . esc_html__('Select all', 'seoaic') . '</label></div>';
        $html .= '<ul class="seoaic-space-between-vertical-12px overflow-hidden seoaic-pt-3 table pb-10">';

        if ($get_created) {
            usort($clusters, function ($a, $b) {
                $dateA = isset($a['posting_date']) ? strtotime($a['posting_date']) : 0;
                $dateB = isset($b['posting_date']) ? strtotime($b['posting_date']) : 0;
                return $dateA <=> $dateB;
            });
        }

        foreach ($clusters as $idea) {
            if ($get_created && $idea['status'] != 'created' && !$generate_for_cluster) {
                continue;
            }
            $ideaId = $idea['id'];
            $title = htmlspecialchars($idea['title'], ENT_QUOTES, 'UTF-8');
            $clusterName = !empty($idea['cluster_name']) ? htmlspecialchars($idea['cluster_name'], ENT_QUOTES, 'UTF-8') : '';
            $contentType = htmlspecialchars(ucwords($idea['type']), ENT_QUOTES, 'UTF-8');
            $postingDate = isset($idea['posting_date']) && !empty($idea['posting_date'])
                ? date('Y-m-d H:i', strtotime($idea['posting_date']))
                : date('Y-m-d H:i');

            $datetime = new DateTime($postingDate, new DateTimeZone('UTC'));
            $datetime->setTimezone(new DateTimeZone(wp_timezone_string()));
            $local_publish_date = $datetime->format('Y-m-d\TH:i');

            $status = get_post_status($ideaId);
            if($status) {
                $post_date = get_post_field('post_date', $ideaId);
                $local_publish_date = $this->get_date_based_on_status($status, $post_date, $postingDate, true);
            }

            $status = !empty($idea['status']) ? $idea['status'] : '';
            $language = !empty($idea['language']) ? $idea['language'] : '';
            $keywords = !empty($idea['keywords']) ? $idea['keywords'] : '';

            $html .= $this->ideasListHtml($ideaId, $title, $clusterName, $contentType, $local_publish_date, $status, $language, $keywords, !$get_created, $postGenerationOption);
        }

        $html .= '</ul></div>';
        return $html;
    }

    private function validateUtcDateTime($input)
    {
        $normalized = preg_replace('/\.\d{3}Z$/', 'Z', $input);

        try {
            return new DateTime($normalized, new DateTimeZone('UTC'));
        } catch (Exception $e) {
            error_log('validateUtcDateTime(): invalid date - ' . $input);
            return null;
        }
    }

    public function cluster_ideas_remove()
    {
        check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);

        if (!current_user_can('edit_posts')) {
            SEOAICAjaxResponse::alert("Permission denied")->wpSend();
        }

        global $SEOAIC_OPTIONS;
        $post = wp_unslash($_POST);

        $raw_ids = is_array($post['id']) ? $post['id'] : explode(',', $post['id']);
        $ids = array_map('intval', array_filter($raw_ids));

        if (!empty($post['remove_accepted'])) {
            $deleted_ids = [];

            foreach ($ids as $id) {
                $get_post = get_post($id);
                $seoaic_posted = get_post_meta($id, 'seoaic_posted', true);

                if ($id && $get_post && (
                        $get_post->post_status === 'seoaic-idea' ||
                        $get_post->post_type === 'seoaic-post' ||
                        $seoaic_posted
                    )) {
                    wp_delete_post($id, true);
                    $deleted_ids[] = $id;
                } else {
                    SEOAICAjaxResponse::alert("Not WP SEO AI post")->wpSend();
                    return;
                }
            }

            wp_send_json_success($deleted_ids);
            return;
        }

        $data = [
            "ids" => $ids,
        ];

        if (!empty($post['remove_all'])) {
            $SEOAIC_OPTIONS[self::CREATE_IDEAS_STATUS] = 'ideas_accepted';
            update_option('seoaic_options', $SEOAIC_OPTIONS);
        }

        $result = $this->seoaic->curl->init('api/cluster-ideas/remove', $data, true, true, true);

        wp_send_json_success(!empty($result) ? $result : 0);
    }

    public function cluster_ideas_update()
    {
        check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);

        if (!current_user_can('edit_posts')) {
            SEOAICAjaxResponse::alert("Permission denied")->wpSend();
        }

        $post = wp_unslash($_POST);

        $id = !empty($post['id']) ? intval($post['id']) : (!empty($post['selected_posts']) ? intval($post['selected_posts']) : 0);
        $title = sanitize_text_field($post['title'] ?? '');

        if ($id && get_post($id)) {
            wp_update_post([
                'ID' => $id,
                'post_title' => $title,
            ]);
            wp_send_json_success(['id' => $id, 'updated_title' => get_post($id)->post_title]);
        }

        $data = [
            "id" => $id,
            "title" => $title,
            "keywords" => [],
        ];

        if (!empty($post['date']) || !empty($post['reschedule_posting_date_UTC'])) {
            $data['posting_date'] = !empty($post['date']) ? $post['date'] : $post['reschedule_posting_date_UTC'];
        }

        $result = $this->seoaic->curl->init('api/cluster-ideas/update', $data, true, true, true);

        wp_send_json($result);
    }

    /**
     * @throws Exception
     */
    public function get_onboarding_schedule_ideas($return = false)
    {
        global $SEOAIC_OPTIONS;

        $post = wp_unslash($_POST);

        if (!empty($post['posts_per_month_per_cluster']) && empty($post['posts_per_month_per_cluster'])) {
            SEOAICAjaxResponse::alert('A posts count cannot be less than 1')->wpSend();
        }

        $is_in_progress = !empty($SEOAIC_OPTIONS[self::CREATE_IDEAS_STATUS]) && $SEOAIC_OPTIONS[self::CREATE_IDEAS_STATUS] === 'in_progress';
        $is_completed = !empty($SEOAIC_OPTIONS[self::CREATE_IDEAS_STATUS]) && $SEOAIC_OPTIONS[self::CREATE_IDEAS_STATUS] === 'completed';
        $is_pending = !empty($SEOAIC_OPTIONS[self::CREATE_IDEAS_STATUS]) && $SEOAIC_OPTIONS[self::CREATE_IDEAS_STATUS] === 'pending';
        $is_ideas_accepted = !empty($SEOAIC_OPTIONS[self::CREATE_IDEAS_STATUS]) && $SEOAIC_OPTIONS[self::CREATE_IDEAS_STATUS] === 'ideas_accepted';

        if (empty($post['generate_more_flag'])) {
            if ($is_in_progress || $is_completed || $is_pending || $is_ideas_accepted || !empty($post['get_scheduled_flag'])) {
                $response = $this->seoaic->curl->init('api/cluster-ideas/bulk-status', [], true, true, true);
                $response_status = !empty($response['status']) ? $response['status'] : '';
                $scheduled = ['status' => 'success'];
                $scheduled['response_status'] = $response_status;

                if ($response_status === 'No active jobs') {
                    $SEOAIC_OPTIONS[self::CREATE_IDEAS_STATUS] = false;
                    update_option('seoaic_options', $SEOAIC_OPTIONS);
                }

                if ($SEOAIC_OPTIONS[self::CREATE_IDEAS_STATUS] === 'in_progress' && $response_status === 'completed') {
                    $scheduled['content_plan'] = $this->createIdeasHTML($response['data']['cluster_ideas'], true);
                }

                wp_send_json($scheduled);
            }
        }

        $data = $this->seoaic_get_onboarding_schedule_ideas(
            $post['how_many_month'] ?? 1,
            $post['posts_per_month_per_cluster'] ?? 2,
            $post['selected_clusters'] ?? [],
            $post['selected_content_types'] ?? [],
            $post['starting_schedule_date_utc'] ?? []
        );

        if (isset($data['status'])) {
            $SEOAIC_OPTIONS[self::CREATE_IDEAS_STATUS] = $data['status'];
            update_option('seoaic_options', $SEOAIC_OPTIONS);
        }

        if ($return) {
            return $data;
        }

        wp_send_json($data);

        wp_die();
    }

    public function accept_ideas()
    {
        check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);

        if (!current_user_can('edit_posts')) {
            SEOAICAjaxResponse::alert("Permission denied")->wpSend();
        }

        global $SEOAIC;
        $post = wp_unslash($_POST);
        $this->save_option(self::CREATE_IDEAS_STATUS, 'ideas_accepted');
        if (!empty($post['data']['content'])) {
            $this->seoaic->curl->init('api/cluster-ideas/submit', [], true, true, true);
            $request = !empty($post['request']) ? $post['request'] : [];
            $inserted_ideas = $SEOAIC->ideas->generateIdeasNewKeywords(true, 1, $post['data'], $request);
        }
        $inserted_ideas = !empty($inserted_ideas) ? $inserted_ideas : [];
        if(!empty($post['data']['keyword_id']) && !empty($post['data']['keyword'])) {
            foreach ($inserted_ideas as $id) {
                $this->seoaic->ideas->setRelation(intval($id), [$post['data']['keyword_id']], [$post['data']['keyword']]);
            }
        }
        wp_send_json_success(['inserted_ideas' => $inserted_ideas]);
    }

    /**
     * @throws Exception
     */
    public function cluster_ideas_generate()
    {
        check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);

        if (!current_user_can('edit_posts')) {
            SEOAICAjaxResponse::alert("Permission denied")->wpSend();
        }

        $post = wp_unslash($_POST);

        $data = [
            "clusterId" => $post['id'],
            "quantity" => $post['posts_per_month_per_cluster'] ?? 1,
            "startingDate" => gmdate('Y-m-d H:i:s', time() + 60) . ' UTC',
            "contentType" => $post['selected_content_types'] ?? [],
            "monthsNumber" => 1,
            "language" => $this->seoaic->multilang->filter_request_multilang(),
        ];

        if (!empty($post['seoaic-ob-select-services'])) {
            $data['selectedServices'] = SEOAIC_SETTINGS::getSelectedRepeaterValues('seoaic_services', $post['seoaic-ob-select-services'], true);
        }

        if (!empty($post['seoaic-ob-select-targets'])) {
            $data['selectedTargetAudience'] = SEOAIC_SETTINGS::getSelectedRepeaterValues('seoaic_target_audience', $post['seoaic-ob-select-targets'], true);
        }

        if (!empty($post['seoaic-select-ob-keywords'])) {
            $data['keywords'] = implode(', ', $post['seoaic-select-ob-keywords']);
        }

        if (!empty($post['CustomPrompt'])) {
            $data['CustomPrompt'] = $post['CustomPrompt'];
        }

        $result = $this->seoaic->curl->init('api/cluster-ideas/generate', $data, true, true, true);
        foreach ($result['data'] as &$item) {
            $item['cluster_name'] = $post['cluster_name'];
        }
        unset($item);

        $formated = $this->createIdeasHTML($result['data'], true, false, true);

        wp_send_json($formated);
    }

    private function render_info_box($label, $content, $is_collapse = false, $selector_id = '', $custom_class = '')
    {
        $is_collapse        = !empty($is_collapse);
        $collapse           = $is_collapse ? '<div class="collapse"></div>' : '';
        $collapse_display   = $is_collapse ? esc_attr('display:none') : '';
        $collapse_class     = $is_collapse ? esc_attr('collapsable') : '';
        $collapse_counter   = $is_collapse ? '<div class="accent collapse_counter fs-16 fw-500 ml-auto mr-15">' . esc_html('(0)') . '</div>' : '';
        $selector_id        = $selector_id ? esc_attr($selector_id) : '';
        $display            = $selector_id ? esc_attr('display:none') : '';
        $custom_class       = $custom_class ? esc_attr($custom_class) : '';

        return <<<HTML
        <div class="seoaic_content_box_info {$custom_class}" class="seoaic-checkbox-block-switcher" data-sliding-block="{$selector_id}" style="{$display}">
            <div class="d-flex jc-sb seoaic-collapse-content-box"><h3 class="mb-0">{$label}</h3>{$collapse_counter}{$collapse}</div>
            <div class="p-6 seoaic-pt-25 {$collapse_class}" style="{$collapse_display}">{$content}</div>
        </div>
        HTML;
    }

    private function render_list_box($label, $items)
    {
        if (empty($items) && !is_array($items)) {
            return '';
        }

        $listItems = '';

        foreach ($items as $item) {
            $name = esc_html($item['name']);
            $text = esc_html($item['description']);
            $listItems .= "<li><strong>{$name}</strong> {$text}</li>";
        }

        return <<<HTML
        <div class="seoaic_content_box_info">
            <div><h3>{$label}</h3></div>
            <div><ul>{$listItems}</ul></div>
        </div>
    HTML;
    }


    public function google_integration_check()
    {
        check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);

        global $SEOAIC, $SEOAIC_OPTIONS;
        $is_integrated = $SEOAIC->content_improvement->checkIntegratedSiteWithGoogle();
        $currentSiteUrl = !empty($SEOAIC_OPTIONS['seoaic_gsc_url']) ? esc_url($SEOAIC_OPTIONS['seoaic_gsc_url']) : get_home_url();
        $disabled = 'disabled';
        $button_text = esc_html__('You are authorized', 'seoaic');
        $button_class = '';
        $button_action = '';

        if (empty($is_integrated)) {
            $disabled = '';
            $button_class = esc_attr('seoaic-ajax-form seoaic-ajax-submit');
            $button_action = '<input type="hidden" class="seoaic-ajax-field" name="action" value="seoaic_add_site_to_google_console">';
            $button_text = esc_html__('Integrate site with google search console', 'seoaic');
        }

        $html = '<button ' . $disabled . ' title="Apply" type="button" class="button-primary seoaic-button-primary generate-keyword-based ' . $button_class . '">
                    ' . $button_action . '
                    <input type="hidden" class="seoaic-ajax-field" name="isScan" value="yes">
                    <input type="hidden" class="seoaic-ajax-field" name="url" value="' . esc_url($currentSiteUrl) . '">
                    <input type="hidden" class="seoaic-ajax-field" name="verificationMethod" value="meta">
                    ' . $button_text . '
                </button>';

        wp_send_json($html);
    }

    public function get_all_clustered_posts_batched()
    {
        global $wpdb;

        check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);

        $post = wp_unslash($_POST);

        $per_page = max(1, isset($post['per_page']) ? (int)$post['per_page'] : 50);
        $paged = max(1, isset($post['paged']) ? (int)$post['paged'] : 1);

        $ten_years_later = (new DateTime('+10 years'))->format('Y-m-d H:i:s');

        $query = new WP_Query([
            'post_type' => 'any',
            'post_status' => 'any',
            'posts_per_page' => $per_page,
            'paged' => $paged,
            'orderby' => 'date',
            'order' => 'DESC',
            'meta_query' => [
                [
                    'key'     => 'seoaic_posted',
                    'compare' => 'EXISTS',
                ],
            ],
            'date_query' => [[
                'before' => $ten_years_later,
                'inclusive' => true,
            ]],
            'fields' => 'ids',
            'no_found_rows' => false,
        ]);

        $wp_posts = [];
        foreach ($query->posts as $post_id) {
            $wp_posts[] = [
                'ID' => $post_id,
                'post_type' => get_post_type($post_id),
                'post_date' => get_post_field('post_date', $post_id),
            ];
        }

        $offset = ($paged - 1) * $per_page;

        $seoaic_posts = $wpdb->get_results($wpdb->prepare("
        SELECT p.ID, p.post_type, pm.meta_value AS meta_date
        FROM {$wpdb->posts} p
        INNER JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id
        WHERE p.post_type = 'seoaic-post'
          AND pm.meta_key = 'seoaic_ob_posting_date'
          AND pm.meta_value <> ''
        ORDER BY STR_TO_DATE(pm.meta_value, '%%Y-%%m-%%dT%%H:%%i') DESC
        LIMIT %d OFFSET %d
    ", $per_page, $offset), ARRAY_A);

        $formatted_seoaic = [];
        foreach ($seoaic_posts as $row) {
            $formatted_seoaic[] = [
                'ID' => (int)$row['ID'],
                'post_type' => $row['post_type'],
                'post_date' => date('Y-m-d H:i:s', strtotime($row['meta_date'])),
            ];
        }

        $all_posts = array_merge($wp_posts, $formatted_seoaic);

        usort($all_posts, function ($a, $b) {
            return strtotime($b['post_date']) <=> strtotime($a['post_date']);
        });

        $all_posts = array_slice($all_posts, 0, $per_page * 2);

        $total = $wpdb->get_var( $wpdb->prepare(
            "
            SELECT COUNT(p.ID)
            FROM {$wpdb->posts} p
            LEFT JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id
            WHERE pm.meta_key = 'seoaic_posted'
              AND pm.meta_value = '1'
              AND p.post_date <= %s
            ",
            $ten_years_later
        ));

        $count_wp = (int)$total;

        $count_seoaic = (int)$wpdb->get_var("
        SELECT COUNT(1)
        FROM {$wpdb->posts} p
        INNER JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id
        WHERE p.post_type = 'seoaic-post'
          AND pm.meta_key = 'seoaic_ob_posting_date'
          AND pm.meta_value <> ''
    ");

        $total_posts = $count_wp + $count_seoaic;

        $loaded_posts = min($paged * $per_page, $total_posts);
        $progress = $total_posts > 0 ? round(($loaded_posts / $total_posts) * 100) : 100;
        $finished = $loaded_posts >= $total_posts;

        $clusters = $this->build_clusters_from_posts(array_column($all_posts, 'ID'));

        wp_send_json([
            'clusters' => $clusters,
            'total_posts' => $total_posts,
            'loaded_posts' => $loaded_posts,
            'progress' => $progress,
            'finished' => $finished,
        ]);
    }

    public function get_all_posts_clusters_batched()
    {
        global $wpdb;

        check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);
        $post = wp_unslash($_POST);

        $per_page = max(1, isset($post['per_page']) ? (int)$post['per_page'] : 100);
        $paged    = max(1, isset($post['paged']) ? (int)$post['paged'] : 1);
        $selected = !empty($post['selected']) ? $post['selected'] : '';
        $offset   = ($paged - 1) * $per_page;

        $clusters = $wpdb->get_col($wpdb->prepare("
        SELECT DISTINCT pm.meta_value
        FROM {$wpdb->postmeta} pm
        INNER JOIN {$wpdb->posts} p ON p.ID = pm.post_id
        WHERE pm.meta_key = 'seoaic_cluster'
          AND pm.meta_value <> ''
        LIMIT %d OFFSET %d
    ", $per_page, $offset));

        $total_clusters = (int) $wpdb->get_var("
        SELECT COUNT(DISTINCT pm.meta_value)
        FROM {$wpdb->postmeta} pm
        INNER JOIN {$wpdb->posts} p ON p.ID = pm.post_id
        WHERE pm.meta_key = 'seoaic_cluster'
          AND pm.meta_value <> ''
    ");

        $loaded_clusters = min($paged * $per_page, $total_clusters);
        $progress        = $total_clusters > 0 ? round(($loaded_clusters / $total_clusters) * 100) : 100;
        $finished        = $loaded_clusters >= $total_clusters;

        $options_html = '';

        foreach ($clusters as $cluster) {
            $slug = sanitize_title($cluster);
            $selected = urldecode($selected);
            $selected = sanitize_text_field($selected);
            $escaped = esc_html($cluster);
            $checked = $cluster === $selected ? 'selected' : '';
            $options_html .= sprintf('<option ' . $checked . ' value="%s">%s</option>', $escaped, $escaped);
        }

        wp_send_json_success([
            'options_html'     => $options_html,
            'total_clusters'   => $total_clusters,
            'loaded_clusters'  => $loaded_clusters,
            'progress'         => $progress,
            'finished'         => $finished,
        ]);
    }

    private function build_clusters_from_posts($post_ids)
    {
        $clusters = [];

        foreach ($post_ids as $post_id) {
            $cluster_name = get_post_meta($post_id, 'seoaic_cluster', true) ?: 'no cluster';
            $clusters[$cluster_name][] = $this->render_post_html($post_id);
        }

        $result = [];
        foreach ($clusters as $name => $items) {
            $result[] = [
                'cluster_name' => $name,
                'cluster_slug' => sanitize_title($name),
                'posts' => implode("\n", $items),
            ];
        }

        return $result;
    }

    private function render_post_html(int $post_id)
    {
        $post = get_post($post_id);

        $title = get_the_title($post_id);
        $excerpt = wp_trim_words(get_the_excerpt($post_id), 5, '...');

        if ($post->post_status === 'seoaic-idea') {
            $meta_date = get_post_meta($post_id, 'seoaic_ob_posting_date', true);
            if ($meta_date) {
                try {
                    $dt = new DateTime($meta_date);
                    $date = $dt->format('jS F, Y');
                    $timestamp = $dt->getTimestamp();
                } catch (Exception $e) {
                    $date = get_the_date('jS F, Y', $post_id);
                    $timestamp = get_the_date('U', $post_id);
                }
            } else {
                $date = get_the_date('jS F, Y', $post_id);
                $timestamp = get_the_date('U', $post_id);
            }
        } else {
            $date = get_the_date('jS F, Y', $post_id);
            $timestamp = get_the_date('U', $post_id);
        }

        $status = $post->post_status === 'seoaic-idea' ? esc_html('Idea') : ucfirst($post->post_status);
        $status_class = sanitize_html_class($post->post_status);
        $permalink = $post->post_status === 'seoaic-idea' ? esc_url('#') : get_permalink($post_id);
        $modal_class = $post->post_status === 'seoaic-idea' ? 'modal-button' : '';
        $modal_id = $post->post_status === 'seoaic-idea' ? '#seoaic-review-onboarding-ideas' : '';
        $_blank = $post->post_status === 'seoaic-idea' ? '_self' : '_blank';
        $modal_content = $post->post_status === 'seoaic-idea' ? '<div id="seoaic-loader-auto-scheduled-posts" class="loader-ellipsis small"></div>' : '';

        return '<li class="seoaic-mind-map-clusters-card-inner-posts-timeline-post ' . esc_attr($status_class) . '" data-mind-map-id="' . esc_attr($post_id) . '" data-date="' . esc_attr($date) . '" data-month="' . esc_attr($timestamp) . '" style="display: none">
        <div class="seoaic-mind-map-clusters-card-inner-posts-timeline-post-activity ' . esc_attr($status_class) . '"></div>
        <div class="seoaic-mind-map-clusters-card-inner-posts-timeline-post-info">
            <div class="d-flex jc-sb ai-center">
                <p class="seoaic-mind-map-clusters-card-inner-posts-timeline-post-date">' . esc_html($date) . '</p>
                <span class="seoaic-mind-map-clusters-card-inner-posts-timeline-post-status">' . esc_html($status) . '</span>
            </div>
            <h4 class="seoaic-mind-map-clusters-card-inner-posts-timeline-post-title" data-mind-map-title-id="' . esc_attr($post_id) . '">' . esc_html($title) . '</h4>
            <p class="seoaic-mind-map-clusters-card-inner-posts-timeline-post-excerpt">' . esc_html($excerpt) . '</p>
            <a href="' . esc_url($permalink) . '" target="' . esc_attr($_blank) . '" data-content="' . esc_html($modal_content) . '" class="view-mind-map-post ' . esc_attr($modal_class) . '" data-id="' . esc_attr($post_id) . '" data-modal="' . esc_attr($modal_id) . '"></a>
        </div>
    </li>';
    }


    public function seoaic_get_posted_date_range()
    {
        global $wpdb;

        check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);

        $regularPosts = $wpdb->get_row("
        SELECT MIN(p.post_date) AS start_date, MAX(p.post_date) AS end_date
        FROM {$wpdb->posts} p
        INNER JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id
        WHERE pm.meta_key = 'seoaic_posted'
          AND pm.meta_value = '1'
          AND p.post_status NOT IN ('auto-draft', 'inherit', 'trash')
          AND p.post_date > '1970-01-01'
          AND p.post_type <> 'seoaic-post'
    ");

        $seoaicPosts = $wpdb->get_row("
        SELECT 
            MIN(STR_TO_DATE(pm.meta_value, '%Y-%m-%dT%H:%i')) AS start_date,
            MAX(STR_TO_DATE(pm.meta_value, '%Y-%m-%dT%H:%i')) AS end_date
        FROM {$wpdb->posts} p
        INNER JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id
        WHERE p.post_type = 'seoaic-post'
          AND pm.meta_key = 'seoaic_ob_posting_date'
          AND pm.meta_value <> ''
    ");

        $startDate = null;
        $endDate   = null;

        if (!empty($regularPosts->start_date)) {
            $startDate = $regularPosts->start_date;
        }
        if (!empty($seoaicPosts->start_date) && (!$startDate || $seoaicPosts->start_date < $startDate)) {
            $startDate = $seoaicPosts->start_date;
        }

        if (!empty($regularPosts->end_date)) {
            $endDate = $regularPosts->end_date;
        }
        if (!empty($seoaicPosts->end_date) && (!$endDate || $seoaicPosts->end_date > $endDate)) {
            $endDate = $seoaicPosts->end_date;
        }

        if (empty($startDate) || empty($endDate)) {
            wp_send_json_error(['error' => 'No valid posts found'], 404);
        }

        $postStart = new DateTime($startDate);
        $postEnd   = new DateTime($endDate);

        $start = (clone $postStart)->modify('-12 months')->modify('first day of this month');
        $end   = (clone $postEnd)->modify('first day of next month')->modify('+12 months');

        $months = [];
        foreach (new DatePeriod($start, new DateInterval('P1M'), $end) as $dt) {
            $endOfMonth = (clone $dt)->modify('first day of next month')->modify('-1 second');
            $timestamp  = (string)$endOfMonth->getTimestamp();
            $months[$timestamp] = $dt->format('F Y');
        }

        $now = new DateTime('now');

        wp_send_json([
            'months' => $months,
            'default_selected' => $now->format('F Y'),
        ]);
    }

    public function create_cluster_transition_queue()
    {
        if (!current_user_can('edit_posts')) {
            SEOAICAjaxResponse::alert("Permission denied")->wpSend();
        }

        $request = wp_unslash($_POST);

        if (empty($request['ids']) || !is_array($request['ids'])) {
            wp_send_json_success([]);
        }

        $data = ['content' => []];

        $location = SEOAIC_SETTINGS::getLocation();
        $language = SEOAIC_SETTINGS::getLanguage();
        $getLocationsWithLanguages = [];

        if ($this->seoaic->multilang->is_multilang()) {
            $getLocationsWithLanguages = $this->seoaic->multilang->getLocationsWithLanguages();
        }

        foreach ($request['ids'] as $post_id) {
            $post_obj = get_post($post_id);
            if (!$post_obj) {
                continue;
            }

            $seoaic_posted  = get_post_meta($post_id, 'seoaic_posted', true);
            $seoaic_cluster = get_post_meta($post_id, 'seoaic_cluster', true);

            if (empty($seoaic_posted) || !empty($seoaic_cluster)) {
                continue;
            }

            if ($this->seoaic->multilang->is_multilang()) {
                $language = $this->seoaic->multilang->get_post_language($post_id) ?: SEOAIC_SETTINGS::getLanguage();
                $lang = $this->seoaic->multilang->get_language_by($language);

                $location_code = !empty($SEOAIC_OPTIONS['language_locations'][$lang['code']])
                    ? $SEOAIC_OPTIONS['language_locations'][$lang['code']]
                    : null;

                $location = $this->seoaic->also_ask_ideas->getCountryNameByCode($getLocationsWithLanguages, $location_code)
                    ?: SEOAIC_SETTINGS::getLocation();
            }

            $data['content'][] = [
                'title'       => get_the_title($post_obj),
                'description' => wp_trim_words($post_obj->post_content, 15, ''),
                'language'    => $language,
                'location'    => $location,
                'id'          => $post_obj->ID,
            ];
        }

        if (empty($data['content'])) {
            wp_send_json_success([]);
        }

        $response = $this->seoaic->curl->init('/api/clusters/clusterize-content', $data, true, true, true);

        $clusters = array_merge(
            $response['data']['oldClusters'] ?? [],
            $response['data']['newClusters'] ?? []
        );

        $ids = [];
        foreach ($clusters as $cluster) {
            $cluster_name = $cluster['name'] ?? '';
            if (!empty($cluster['content']) && is_array($cluster['content'])) {
                foreach ($cluster['content'] as $post_item) {
                    $post_id = intval($post_item['id']);
                    if ($post_id > 0) {
                        $ids[] = $post_id;
                        update_post_meta($post_id, 'seoaic_cluster', $cluster_name);
                    }
                }
            }
        }

        wp_send_json_success($ids);
    }

    public function step_connect_google_console_html()
    {
        return '<div id="seoaic_step_connect_google_console">
                    <div id="seoaic_onboarding_google_integration_check" class="seoaic-ajax-form seoaic-ajax-submit">
                        <input type="hidden" class="seoaic-ajax-field" name="action" value="seoaic_onboarding_google_integration_check">
                    </div>
                </div>';
    }

    public function step_crawl_sitemap_html()
    {
        global $SEOAIC_OPTIONS;

        $checked = 'checked';
        $active = '';
        $disabled = '';
        $progress = $this->loading_progress();
        $loaded = '';
        $hide = 'd-none';
        $content_strategy_generated = '';
        $status = $this->clusters_generated_status();

        if ($this->send_pages_progress()) {
            $active = 'active sending-pages';
        }

        if (!empty($status)) {
            if ($status === 'completed' || $status === 'failed') {
                $active = 'active';
                $progress = '100';
                $loaded = ($status === 'failed') ? 'failed' : 'loaded';
                $hide = ($status === 'completed') ? 'd-none' : '';
                $content_strategy_generated = ($status === 'completed') ? $this->content_strategy_html(true) : '';
            } elseif ($status === 'pending') {
                $active = 'active pending-status';
                $loaded = $status;
            } elseif ($status !== 'completed') {
                $loaded = $status;
            }
        }

        $html = '<input style="display: none" type="checkbox" id="seoaic_display_full_pages_list" ' . $checked . '>';
        $html .= '<input style="display: none" type="checkbox" id="seoaic_is_scan_started_step" ' . $checked . '>';

        if (!$this->clusters_generated_status()) {
            $html .= $this->get_pages_list(true, true);
        }

        $html .= '<div class="seoaic-start-scanning mt-80 ' . $active . '" data-status="' . $this->clusters_generated_status . '">
                    <div class="seoaic-loader-container">
                        <div class="loader-text seoaic-loading-label accent">' . esc_html__('Scanning website ', 'seoaic') . '<span class="loader-value-percentage" data-progress="' . $progress . '">' . $progress . '%</span></div>

                        <div class="loader-icon seoaic-breath-loading ' . $loaded . '"></div>

                        <div class="seoaic-progress-bar seoaic-ml-20"><span style="width: ' . $progress . '%"></span></div>

                        <span class="remove dashicons dashicons-no-alt red modal-button seoaic-ml-20" data-modal="#seoaic-confirm-modal" data-content="Are you sure you want to restart the onboarding process?" data-action="seoaic_clear_onboarding_progress">
                            <input type="hidden" class="seoaic-ajax-field" name="action" value="seoaic_clear_onboarding_progress">
                        </span>
                    </div>

                    <button disabled id="seoaic_start_scanning_button" for="seoaic_is_scan_started_step" title="Apply" type="button" class="button-primary seoaic-button-primary generate-keyword-based hide-on-checked">
                        ' . esc_html__('Let’s start scanning!', 'seoaic') . '
                    </button>
                </div>
                <div class="seoaic-hidden-actions d-none">
                    <span id="seoaic_onboarding_check_status" class="d-none seoaic-ajax-form seoaic-ajax-submit">
                        <input type="hidden" class="seoaic-ajax-field" name="action" value="seoaic_onboarding_check_status">
                        <input type="hidden" class="seoaic-ajax-field" name="progress" value="">
                    </span>
                    <span id="seoaic_onboarding_content_strategy_init" class="d-none seoaic-ajax-form seoaic-ajax-submit">
                        <input type="hidden" class="seoaic-ajax-field" name="action" value="seoaic_onboarding_content_strategy_html">
                    </span>
                    <span id="seoaic_start_scanning_data" class="d-none seoaic-ajax-form seoaic-ajax-submit">
                        <input type="hidden" class="seoaic-ajax-field" name="action" value="seoaic_onboarding_scan_pages">
                        <input type="hidden" class="seoaic-ajax-field" name="page" value="' . $this->send_pages_progress() . '">
                        <input type="hidden" class="seoaic-ajax-field" name="include_ids" value="">
                        <input type="hidden" class="seoaic-ajax-field" name="select_key_pages" value="1">
                    </span>
                </div>
                ';

        $html .= '
        <div class="seoaic-content-strategy mt-40">
            <div class="inner">' . $content_strategy_generated . '</div>
            <div class="seoaic-content-strategy-loader ' . $hide . '">
                <h3 class="text-lg font-semibold mb-2">' . esc_html__('Building Content Strategy...', 'seoaic') . '</h3>
                <div class="seoaic-animate-pulse seoaic_content_box_info seoaic-w-50"></div>
                <div class="seoaic-animate-pulse seoaic_content_box_info"></div>
                <div class="seoaic-animate-pulse seoaic_content_box_info"></div>
            </div>
        </div>';

        return $html;
    }

    public function manage_clusters_html($selector_id, $clusters_data = false, $visible = false, $toggle = true)
    {
        $display = esc_attr('display:none');

        if($visible) {
            $display = esc_attr('');
        }

        $labels = [
            'clusters' => esc_html__('Core Topic Pillars (Content Clusters)', 'seoaic'),
            'addCluster' => esc_html__('+ Add cluster', 'seoaic'),
            'remove' => esc_html__('Remove selected', 'seoaic'),
            'select_all' => esc_html__('Select all', 'seoaic'),
        ];
        if($clusters_data) {
            $clusterIdeas = $clusters_data;
        } else {
//            $request = $this->request_clusters(1, 100);
//            $clusterIdeas = !empty($request['data']['data']) ? $request['data']['data'] : [];
            $clusterIdeas = $this->getOrSetClustersTransient();
        }

        $html = '';

        $clusters_section = <<<HTML
        <div class="ai-center d-flex jc-sb mt-0 top-cluster-section">
            <input class="ml-15 seoaic-checkbox" type="checkbox" id="seoaic_check_all_clusters">
            <label for="seoaic_check_all_clusters" class="h3 mb-5 ml-10 mt-0">{$labels['select_all']}</label>
            <div class="ml-auto seoaic-ajax-form seoaic-ajax-submit">
                <button title="{$labels['remove']}" type="button" id="seoaic_clusters_to_remove_label" class="d-none seoaic-remove"></button>
                <input type="hidden" class="seoaic-ajax-field" name="action" value="seoaic_cluster_delete">
                <input id="seoaic_clusters_to_remove_input" type="hidden" class="seoaic-ajax-field" name="id" value="">
            </div>
        </div>
        <div id="seoaic_clusterized_articles_table">
            <div class="seoaic-grid-view seoaic-grid-view-list">
                {$this->clusters_cards($clusterIdeas, 'pages', $toggle)}
                <button id="seoaic_add_new_service_cluster" class="add-new-service-button mt-20 modal-button" data-modal="#seoaic-add-clusters-modal">
                    <span>{$labels['addCluster']}</span>
                </button>
            </div>
        </div>
        HTML;

//        if ($clusterIdeas) {
//            $html .= $this->render_info_box($labels['clusters'], $clusters_section, false, $selector_id, 'mb-40 mr-10');
//        }

        $html .= $this->render_info_box($labels['clusters'], $clusters_section, false, $selector_id, 'mb-40 mr-10');

        return $html;
    }

//    public function get_clusters_options() {
//        global $SEOAIC, $SEOAIC_OPTIONS;
//        $clusters_options = [];
//        $clusters_data = [];
//        $manage_clusters_html = '';
//        if (!empty($SEOAIC_OPTIONS[self::CLUSTERS_GENERATED_STATUS])) {
//            $clusters_options = $this->request_clusters(1, 100);
//            $manage_clusters_html = $this->manage_clusters_html('seoiac-open-manage-clusters-ob-ideas', $clusters_options);
//        }
//
//        if (!empty($clusters_options['data']['data'])) {
//            $clusters_data = $clusters_options['data']['data'];
//            $options_html = '';
//            foreach ($clusters_data as $option) {
//                $options_html .= '<option value="' . $option['id'] . '">' . $option['name'] . '</option>';
//            }
//        }
//
//        wp_send_json_success([
//            'clusters_data' => $clusters_data,
//            'clusters_options_html' => $options_html,
//            'manage_clusters_html' => $manage_clusters_html,
//        ]);
//
//    }

    public function get_clusters_options() {
        global $SEOAIC, $SEOAIC_OPTIONS;

        $clusters_data   = [];
        $clusters_options = [];
        $manage_clusters_html = '';
        $options_html = '';

        $clusters_options = $this->getOrSetClustersTransient();
        //$this->syncTaxClustersWithBackend($clusters_options);

        $manage_clusters_html = $this->manage_clusters_html(
            'seoiac-open-manage-clusters-ob-ideas',
            $clusters_options
        );

        if (!empty($clusters_options)) {
            $clusters_data = $clusters_options;

            foreach ($clusters_data as $option) {
                $options_html .= '<option value="' . esc_attr($option['id']) . '">' . esc_html($option['name']) . '</option>';
            }
        }

        wp_send_json_success([
            'clusters_data'        => $clusters_data,
            'clusters_options_html'=> $options_html,
            'manage_clusters_html' => $manage_clusters_html,
        ]);
    }

    public function generate_ob_ideas_form($form_class = 'mb-30', $form_title = '')
    {
        global $SEOAIC, $SEOAIC_OPTIONS;
        $keywords = $SEOAIC->keywords->getKeywords();
//        $clusters_options = [];
//        if (!empty($SEOAIC_OPTIONS[self::CLUSTERS_GENERATED_STATUS])) {
//            $clusters_options = $this->request_clusters(1, 100);
//        }
        $options_html = '';
        $button_text = __('Generate', 'seoaic');
        $modal_button = '';
        $modal_data = '';
        $generate_more_flag = '';
//        if (!empty($clusters_options['data']['data'])) {
//            $data = $clusters_options['data']['data'];
//            foreach ($data as $option) {
//                $options_html .= '<option value="' . $option['id'] . '">' . $option['name'] . '</option>';
//            }
//        }

        $status = !empty($SEOAIC_OPTIONS[self::CREATE_IDEAS_STATUS]) ? $SEOAIC_OPTIONS[self::CREATE_IDEAS_STATUS] : '';

        if ($status === 'in_progress') {
            $button_text = __('Creating', 'seoaic');
        } elseif ($status === 'completed') {
            $button_text = __('View generated', 'seoaic');
            $modal_button = 'modal-button';
            $modal_data = '#seoaic-accept-onboarding-ideas';
        } elseif ($status === 'ideas_accepted') {
            $generate_more_flag = '<input type="hidden" class="seoaic-ajax-field" name="generate_more_flag" value="1">';
            $button_text = __('Generate more', 'seoaic');
        }

        ?>
        <div id="seoaic-generate_ob_ideas_form">
            <?php if ($form_title) : ?>
                <h2 class="fs-18 fw-700 seoaic-mb-15"><?php esc_html($form_title) ?></h2>
            <?php endif; ?>
            <div id="seoaic-calculate-onboarding-ideas" class="fs-16 mb-30">
                <?php
                echo __('Total will be created <span class="will-be-created fw-700"></span> ideas. <span class="per-month fw-700"></span> per month.', 'seoaic');
                ?>
            </div>
            <div id="seoaic_get_onboarding_schedule_ideas"
                 class="seoaic-onboarding-selects seoaic-ajax-form <?php echo esc_attr($form_class) ?> <?php echo esc_attr($status) ?>">
                <input type="hidden" class="seoaic-ajax-field" name="action"
                       value="seoaic_get_onboarding_schedule_ideas">
                <?php echo $generate_more_flag; ?>
                <div class="inner">
                    <label class="mb-5"><?php _e('How many month', 'seoaic'); ?></label>
                    <select id="seoaic-onboarding-select-how_many_month" name="how_many_month" class="seoaic-ajax-field"
                            data-placeholder="<?php _e('Not Selected', 'seoaic'); ?>">
                        <option value="1"><?php esc_html_e('1 month', 'seoaic'); ?></option>
                        <option value="3"><?php esc_html_e('3 month', 'seoaic'); ?></option>
                        <option value="6" selected><?php esc_html_e('6 month', 'seoaic'); ?></option>
                        <option value="12"><?php esc_html_e('12 month', 'seoaic'); ?></option>
                    </select>
                </div>
                <div class="inner inner-posts-per-month-per-cluster">
                    <label class="mb-5"
                           data-seoaic-tooltip-info="<?php esc_attr_e('Posts per month per cluster', 'seoaic'); ?>"><?php _e('Posts', 'seoaic'); ?></label>
                    <input type="number" id="seoaic-onboarding-input-posts_per_month_per_cluster"
                           min="1"
                           max="3700"
                           name="posts_per_month_per_cluster"
                           class="seoaic-form-item form-input light seoaic-ajax-field"
                           value="1" placeholder="<?php _e('Set number of posts', 'seoaic'); ?>">
                </div>
                <div class="inner select-clusters-inner-block loading">
                    <label class="mb-5"><?php _e('Selected clusters', 'seoaic'); ?></label>
                    <select multiple id="seoaic-onboarding-select-selected_clusters" name="selected_clusters"
                            class="clusters seoaic-ajax-field"
                            data-placeholder="<?php _e('Not Selected', 'seoaic'); ?>">
                    </select>
                </div>
                <div class="inner">
                    <label class="mb-5"><?php _e('Selected content types', 'seoaic'); ?></label>
                    <select multiple id="seoaic-onboarding-select-selected_content_types" name="selected_content_types"
                            class="clusters seoaic-ajax-field"
                            data-placeholder="<?php _e('Not Selected', 'seoaic'); ?>">
                        <?php
                        foreach (seoaic_get_prompt_template_types() as $key => $template_type) {
                            ?>
                            <option value="<?php echo esc_attr($key);?>"><?php echo esc_html($template_type);?></option>
                            <?php
                        }
                        ?>
                    </select>
                </div>
                <div class="inner">
                    <label class="mb-5"><?php esc_html_e('Starting date', 'seoaic'); ?></label>
                    <input type="hidden" id="seoaic-onboarding-input-starting_schedule_date_utc"
                           name="starting_schedule_date_utc" class="seoaic-ajax-field" value="">
                    <input type="text" id="seoaic-onboarding-input-starting_schedule_date"
                           name="starting_schedule_date" class="seoaic-form-item form-input light seoaic-ajax-field"
                           value="" placeholder="<?php esc_attr_e('Starting date', 'seoaic'); ?>">
                </div>
                <div class="inner d-flex ai-end seoaic-self-end position-relative">
                    <button
                            id="seoaic-onboarding-button-generate_content_plan"
                            type="button"
                            data-in-progress="<?php esc_attr_e('Creating', 'seoaic') ?>"
                            data-success="<?php esc_attr_e('View generated', 'seoaic') ?>"
                            data-generate="<?php esc_attr_e('Generate more', 'seoaic') ?>"
                            data-title="<?php esc_attr_e('Generated ideas plan', 'seoaic') ?>"
                            data-content="<?php echo esc_attr('<div id="seoaic-loader-auto-scheduled-posts" class="loader-ellipsis small"></div>') ?>"
                            class="seoaic-branded-button seoaic-ajax-submit ml-auto <?php echo esc_attr($status) ?> <?php echo esc_attr($modal_button) ?>"
                            data-modal="<?php echo esc_attr($modal_data) ?>"><?php echo $button_text; ?></button>
                    <span class="seoaic-info-on-creating fs-small accent"><?php esc_html_e('Might take a minute', 'seoaic'); ?></span>
                </div>
                <div class="inner seoiac-advanced-options mt-20">
                    <label class="accent accent-underline mb-19"
                           for="seoiac-open-advanced-options-generate-ob-ideas"><?php esc_html_e(' Advanced Options (Optional)', 'seoaic'); ?></label>
                    <label class="accent accent-underline mb-19 ml-15 seoaic-ml-25"
                           data-seoaic-open-block="seoiac-open-manage-clusters-ob-ideas"
                           for="seoiac-open-manage-clusters-ob-ideas"><?php esc_html_e(' Manage clusters', 'seoaic'); ?></label>
                    <input type="checkbox" id="seoiac-open-advanced-options-generate-ob-ideas">
                    <div id="seoiac-advanced-options-generate-ob-ideas">
                        <div class="d-flex">
                            <div class="d-flex seoaic-flex-column seoaic-ob-left-col-options">
                                <label class="mb-10 mt-20"
                                       for="custom-prompt"><?php esc_html_e('Custom Prompt / Instructions', 'seoaic'); ?></label>
                                <textarea class="seoaic-form-item form-input light light seoaic-ajax-field"
                                          id="seoaic-ob-custom-prompt"
                                          name="CustomPrompt"
                                          placeholder="<?php esc_attr_e('Enter any specific instructions or themes for the AI...', 'seoaic') ?>"
                                          rows="3"></textarea>
                            </div>
                            <div class="d-flex seoaic-flex-column mb-19 seoaic-ob-center-col-options">
                                <div class="d-flex seoaic-flex-column seoaic-ob-select-options">
                                    <label for="seoaic-ob-select-keywords"
                                           class="mb-10 mt-20"><?php esc_html_e('Select keywords', 'seoaic'); ?></label>
                                    <select multiple id="seoaic-ob-select-keywords" name="seoaic-select-ob-keywords"
                                            class="seoaic-ajax-field">
                                        <?php
                                        foreach ($keywords as $keyword) {
                                            echo '<option value="' . esc_attr($keyword['slug']) . '">' . esc_html($keyword['name']) . '</option>';
                                        }
                                        ?>
                                    </select>
                                </div>
                                <div class="d-flex seoaic-flex-column seoaic-ob-select-options">
                                    <?php
                                    echo SEOAIC_SETTINGS::createRepeaterHTML('seoaic_services', true, false, false, 'seoaic-ajax-field', 'seoaic-ob-select-services', false);
                                    ?>
                                </div>
                                <div class="d-flex seoaic-flex-column seoaic-ob-select-options">
                                    <?php
                                    echo SEOAIC_SETTINGS::createRepeaterHTML('seoaic_target_audience', true, false, false, 'seoaic-ajax-field', 'seoaic-ob-select-targets', false);
                                    ?>
                                </div>
                            </div>
                            <div class="d-flex seoaic-flex-column mb-19 seoaic-ob-right-col-options">
                                <div class="mb-10 mt-20"><?php echo $SEOAIC->multilang->get_multilang_checkboxes(); ?></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php echo $this->manage_clusters_html('seoiac-open-manage-clusters-ob-ideas'); ?>
            <div class="seoaic-loader-container pr-10" id="seoaic_saving_ideas_progress"
                 style="<?php echo esc_attr('display:none') ?>">
                <h3 class="loader-text seoaic-loading-label accent seoaic-text-nowrap"><?php _e('Saving ideas ', 'seoaic'); ?>
                    <span class="loader-value-percentage" data-progress="0"><?php _e('0%', 'seoaic'); ?></span></h3>
                <div class="seoaic-progress-bar seoaic-ml-20"><span style="width: 0"></span></div>
            </div>
            <span id="seoaic_check_status_generation_ob_ideas" class="d-none seoaic-ajax-form seoaic-ajax-submit">
            <input type="hidden" class="seoaic-ajax-field" name="action" value="seoaic_get_onboarding_schedule_ideas">
            </span>
        </div>
        <?php
    }

    private function step_generate_content_plan_html()
    {
        global $SEOAIC_OPTIONS;

        ob_start();
        $this->generate_ob_ideas_form();
        $hide_calendar = 'd-none';
        if (!empty($SEOAIC_OPTIONS[self::CREATE_IDEAS_STATUS]) && $SEOAIC_OPTIONS[self::CREATE_IDEAS_STATUS] === 'ideas_accepted') {
            $hide_calendar = '';
        }
        ?>
        <div class="inner-calendar seoaic-onboarding-calendar-inner">
            <div class="sidebar <?php echo $hide_calendar; ?>">
                <h3><?php _e('Monthly summary', 'seoaic'); ?></h3>
                <div id="seoaic_calendar_view_sidebar"></div>
            </div>
            <div class="weeks_numbers">
                <div class="height-adjustment"></div>
                <div id="seoaic_weeks_numbers"></div>
            </div>
            <div id="seoaic_calendar_view" class="inner"
                 data-single-post="<?php _e('&nbsp;post', 'seoaic'); ?>"
                 data-many-posts="<?php _e('&nbsp;posts', 'seoaic'); ?>"
                 data-mode-onboarding="<?php echo esc_html('1'); ?>"
                 data-mode-onboarding-month-length="<?php echo esc_html(12); ?>"
                 data-default-posting-time=""></div>
            <div id="seoaic_open_draft_list_canvas" class="open-draft-list-canvas"
                 data-button="<?php _e('Show Drafts', 'seoaic'); ?>"
                 data-button-active="<?php _e('Hide Drafts', 'seoaic'); ?>">
                <div class="inner">
                    <h3><?php _e('Unscheduled Draft Posts', 'seoaic'); ?></h3>
                    <a href="#" class="hide-clusters-filters active d-none"
                       data-button="<?php _e('Show Filters', 'seoaic'); ?>"
                       data-button-active="<?php _e('Hide Filters', 'seoaic'); ?>"><span></span></a>
                    <div class="sort-clusters d-none">
                        <p><?php _e('Sort by cluster:', 'seoaic'); ?></p>
                        <a href="#" class="seoaic-cluster-post-draft green"><?php _e('cluster name:', 'seoaic'); ?></a>
                    </div>
                    <div class="draft-posts-list" id="seoaic_draggable_draft_posts"></div>
                </div>
            </div>
        </div>
        <?php
        return ob_get_clean();
    }

    private function step_content_cluster_mind_map_html()
    {
        ob_start();
        ?>
        <div class="seoaic-loader-container">
            <h3 class="loader-text seoaic-loading-label accent seoaic-text-nowrap"><?php _e('Indexing posts ', 'seoaic'); ?>
                <span class="loader-value-percentage" data-progress="0"><?php _e('0%', 'seoaic'); ?></span></h3>
            <div class="seoaic-progress-bar seoaic-ml-20"><span style="width: 0"></span></div>
        </div>
        <div class="seoaic-mind-map mt-80 d-none" data-per-page="<?php echo esc_attr('99'); ?>">
            <div class="seoaic-mind-map-current-date"
                 id="seoaic-mind-map-current-date"><?php _e('December 2024', 'seoaic'); ?></div>
            <div class="seoaic-mind-map-scroller-section">
                <div class="seoaic-mind-map-scroller-section-buttons mb-40">
                    <button class="seoaic-mind-map-scroller-button-left"></button>
                    <button class="seoaic-mind-map-scroller-button-right"></button>
                </div>
                <div class="seoaic-mind-map-scroller-selector">
                    <div id="seoaic-mind-map-scroller-selector-init"
                         class="seoaic-mind-map-scroller-selector-init"></div>
                    <div class="seoaic-mind-map-scroller-selector-label fw-600 mt-10 text-center"><?php _e('Drag to select month or use arrows', 'seoaic'); ?></div>
                </div>
            </div>
            <div class="mb-30 mt-40 position-relative text-center w-100">
                <h3 class="mb-5"><?php _e('Website Hub', 'seoaic'); ?></h3>
                <span><?php _e('Content Structure Overview', 'seoaic'); ?></span>
                <div class="check-if-ideas">
                    <input id="seoaic_set_to_display_ob_ideas" type="checkbox" class="seoaic-checkbox">
                    <label for="seoaic_set_to_display_ob_ideas"><?php _e('Show ideas', 'seoaic'); ?></label>
                </div>
            </div>
            <div class="seoaic-mind-map-clusters"></div>
        </div>
        <?php
        return ob_get_clean();
    }

    public function step_generated_ideas_for_clusters_html()
    {
        return $this->step_generated_content_clusters_html('seoaic_onboarding_get_ideas');
    }

    public function step_generated_content_clusters_html($clusters_type = 'seoaic_onboarding_get_clusters_list')
    {
        $html = '<div id="seoaic_clusterized_articles_table" class="clusterized_articles_table">';
        $html .= '<div class="seoaic-grid-view">' . $this->cluster_cards_preload() . '</div>';
        $html .= '<div class="seoaic-grid-view-pagination"></div>';
        $html .= '<span id="' . $clusters_type . '" class="seoaic-ajax-form seoaic-ajax-submit">
                        <input type="hidden" class="seoaic-ajax-field" name="action" value="' . $clusters_type . '">
                        <input type="hidden" class="seoaic-ajax-field" name="page" value="1">
                      </span>';
        $html .= '</div>';
        $html .= '<button id="seoaic_add_new_service_cluster" class="add-new-service-button mt-20 modal-button" data-modal="#seoaic-add-clusters-modal"><span>' . esc_html__('+ Add Cluster', 'seoaic') . '</span>';
        $html .= '</button>';

        return $html;
    }

    private function step_company_description_html($BusinessDescription = '', $industry = '')
    {
        $BusinessName = SEOAIC_SETTINGS::getBusinessName();
        //$BusinessDescription = SEOAIC_SETTINGS::getBusinessDescription();
        $preview_display = empty($BusinessDescription) ? ' style="display: none"' : '';
        $base_prompt = esc_attr__('Highlight the main areas of expertise, key services or products, unique selling points, and what sets the company apart in its industry. The description should be well-structured and clear.', 'seoaic');

        return SEOAIC_SETTINGS::createRepeaterHTML('seoaic_business_description', false, true, true, false, false, true, $BusinessDescription, false) . '
            <div id="seoaic_step_hidden_params">
                <input type="hidden" class="seoaic-ajax-field" name="callback" value="seoaic_save_company_data">
                <input type="hidden" class="seoaic-ajax-field" name="description" value="' . esc_attr($BusinessDescription) . '">
                <input type="hidden" class="seoaic-ajax-field" name="industry" value="' . esc_attr($industry) . '">
            </div>
        ';
    }

    public function step_target_audiences_html()
    {
        return $this->step_service_offerings_html('seoaic_target_audience');
    }

    public function step_service_offerings_html($optionKey = 'seoaic_services')
    {
        $services = $this->options[$optionKey] ?? [];
        $type = $optionKey === 'seoaic_services' ? 'service' : 'target';

        if (empty($services)) {
            $key = $optionKey === 'seoaic_services' ? 'services' : 'targets';
            $services = $this->get_services_and_audience($key);
        }

        ob_start();
        echo SEOAIC_SETTINGS::createRepeaterHTML($optionKey, false, true, false, false, false, true, $services, false);
        ?>
<!--        <div id="seoaic_services_wrap_--><?php //echo esc_attr($optionKey); ?><!--" class="services-wrap">-->
<!--            --><?php //foreach ($services as $i => $service) : ?>
<!--                --><?php
//                $isClone = ($i === 0);
//                $templateClass = $isClone ? 'service-clone-template' : '';
//                $dataId = $isClone ? 'uniqueID' : $i;
//                $title = esc_html($service['name'] ?? $service['title'] ?? '');
//                $description = esc_html($service['text'] ?? $service['description'] ?? '');
//                ?>
<!--                <div data-id="--><?php //= esc_attr($dataId) ?><!--"-->
<!--                     class="generated_content-card service-card meta-data not-empty mt-20 active --><?php //echo esc_attr($templateClass) ?><!--">-->
<!--                    <div class="inner-text">-->
<!--                        <button data-id="--><?php //echo esc_attr($dataId) ?><!--" class="seoaic_edit_service service-card-action"-->
<!--                                type="button"></button>-->
<!--                        <button data-id="--><?php //echo $dataId ?><!--" class="seoaic_edit_meta_cancel service-card-action"-->
<!--                                type="button"></button>-->
<!--                        <button data-id="--><?php //echo $dataId ?><!--" class="seoaic_edit_meta_save service-card-action"-->
<!--                                type="button"></button>-->
<!--                        <div class="d-flex seoaic-mb-15">-->
<!--                            <input type="checkbox" class="seoaic-checkbox" checked>-->
<!--                            <div class="dynamic-label input-label">--><?php //echo esc_html__('Title:', 'seoaic') ?><!--</div>-->
<!--                            <h4 id="seo_title_preview_--><?php //echo esc_attr($dataId) ?><!--">--><?php //echo esc_html($title) ?><!--</h4>-->
<!--                        </div>-->
<!--                        <div class="dynamic-label text-area-label">--><?php //= esc_html__('Description:', 'seoaic') ?><!--</div>-->
<!--                        <p id="seo_description_preview_--><?php //echo esc_attr($dataId) ?><!--">--><?php //echo esc_html($description) ?><!--</p>-->
<!--                    </div>-->
<!--                    <a href="#"-->
<!--                       data-type="--><?php //echo esc_attr($type) ?><!--"-->
<!--                       data-service-id="--><?php //echo esc_attr($dataId) ?><!--"-->
<!--                       data-service-title="--><?php //echo esc_attr($title) ?><!--"-->
<!--                       data-service-description="--><?php //echo esc_attr($description) ?><!--"-->
<!--                       data-base-prompt="Create a more detailed definition of the website's Company --><?php //echo esc_attr($type) ?><!-- called --><?php //echo esc_html($title) ?><!--"-->
<!--                       class="seoaic-magic-button modal-button ob-generate-service-description-modal position-relative"-->
<!--                       data-modal="#settings-description-generate-modal"-->
<!--                       data-action="seoaic_settings_generate_description">--><?php //echo esc_html__('Generate Description', 'seoaic') ?><!--</a>-->
<!--                </div>-->
<!--            --><?php //endforeach; ?>
<!--        </div>-->
<!--        <button id="seoaic_add_new_service_--><?php //echo esc_attr($optionKey); ?><!--"-->
<!--                class="add-new-service-button seoaic-add-services mt-20">-->
<!--            <span>--><?php //= esc_html__('+ Generate more', 'seoaic') ?><!--</span>-->
<!--        </button>-->
        <div id="seoaic_step_hidden_params">
            <input type="hidden" class="seoaic-ajax-field" name="callback" value="seoaic_save_services">
            <input type="hidden" class="seoaic-ajax-field" name="option_name" value="<?php echo esc_attr($optionKey) ?>">
        </div>
        <?php
        return ob_get_clean();
    }


    private function get_services_and_audience($key)
    {
        $data = [
            "offset" => 0,
            "limit" => 5
        ];

        $key = $key === 'services' ? 'services' : 'targets';

        $result = $this->seoaic->curl->init('api/blog-' . $key . '/list', $data, true, true, true);

        return !empty($result['data']) ? $result['data'] : [];
    }

    private function seoaic_save_company_data()
    {
        check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);

        $post = wp_unslash($_POST);

        $services = $this->decode_json_fields($post['seoaic_services'] ?? []);
        $audience = $this->decode_json_fields($post['seoaic_target_audience'] ?? []);

        $this->save_option('seoaic_services', $services);
        $this->save_option('seoaic_target_audience', $audience);

        if (empty($post['description'])) {
            SEOAICAjaxResponse::alert(__('Company description cannot be empty', 'seoaic'))->wpSend();
        }

        $this->save_option('seoaic_business_description', wp_kses_post($post['description']));
        $this->save_option('seoaic_industry', wp_kses_post($post['industry']));
    }

    private function decode_json_fields($raw)
    {
        $items = is_array($raw) ? $raw : [$raw];

        return array_values(array_filter(array_map(function ($json) {
            $decoded = json_decode($json, true);
            return is_array($decoded) ? $decoded : null;
        }, $items)));
    }

    private function process_post_save_and_accept($post_data)
    {
        $post_id = intval($post_data['post_id'] ?? 0);
        $content = wp_kses_post($post_data['post_content'] ?? '');
        $status = sanitize_key($post_data['post_status'] ?? '');
        $post_date = sanitize_text_field($post_data['post_date'] ?? '');
        $save_edited_content = sanitize_text_field($post_data['save_edited_content'] ?? '');
        $auto_schedule = sanitize_text_field($post_data['auto_schedule'] ?? '');

        $post = get_post($post_id);
        if (!$post) {
            return new WP_Error('not_found', 'Post not found');
        }

        if (empty($post_date) || !is_numeric($post_date)) {
            $meta_posting_date = get_post_meta($post_id, 'seoaic_ob_posting_date', true);

            if (!empty($meta_posting_date)) {
                $meta_timestamp = strtotime($meta_posting_date);
                if ($meta_timestamp !== false) {
                    $post_date = $meta_timestamp;
                }
            }
        }

        $update_args = [
            'ID' => $post_id,
            'edit_date' => true,
        ];

        if (intval($save_edited_content)) {
            $update_args['post_content'] = $content;
        }

        if ($post_date && is_numeric($post_date)) {
            $timestamp = intval($post_date);
            $formatted_gmt_date = gmdate('Y-m-d H:i:s', $timestamp);
            $formatted_local_date = get_date_from_gmt($formatted_gmt_date);
            $update_args['post_date_gmt'] = $formatted_gmt_date;
            $update_args['post_date'] = $formatted_local_date;
        } else {
            $update_args['post_date'] = current_time('mysql');
            $update_args['post_date_gmt'] = gmdate('Y-m-d H:i:s');
        }

        $timestamp = strtotime($post_date);

        if (intval($auto_schedule)) {
            update_post_meta($post_id, 'seoaic_auto_scheduled', 1);
            $update_args['post_status'] = 'draft';
            SEOAIC_SETTINGS::setup_auto_publish_cron();
        } else {
            delete_post_meta($post_id, 'seoaic_auto_scheduled');

            if (empty($status)) {
                if ($timestamp && $timestamp > current_time('timestamp')) {
                    $update_args['post_status'] = 'future';
                } else {
                    $update_args['post_status'] = 'publish';
                }
            } else {
                $update_args['post_status'] = $status;
            }
        }

        $result = wp_update_post($update_args, true);

        if (is_wp_error($result)) {
            return $result;
        }

        delete_post_meta($post_id, 'seoaic_ob_needs_review');
        delete_post_meta($post_id, 'seoaic_ob_posting_date');

        return $post_id;
    }

    public function ob_save_and_accept_post()
    {
        check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);

        if (!current_user_can('edit_posts')) {
            SEOAICAjaxResponse::alert("Permission denied")->wpSend();
        }

        $post_data = wp_unslash($_POST);
        $result = $this->process_post_save_and_accept($post_data);

        if (is_wp_error($result)) {
            wp_send_json_error($result->get_error_message());
        }

        wp_send_json_success(['id' => $result]);

//        check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);
//
//        if (!current_user_can('edit_posts')) {
//            SEOAICAjaxResponse::alert("Permission denied")->wpSend();
//        }
//
//        $post_data = wp_unslash($_POST);
//
//        $post_id = intval($post_data['post_id'] ?? 0);
//        $content = wp_kses_post($post_data['post_content'] ?? '');
//        $status = sanitize_key($post_data['post_status'] ?? '');
//        $post_date = sanitize_text_field($post_data['post_date'] ?? '');
//        $save_edited_content = sanitize_text_field($post_data['save_edited_content'] ?? '');
//        $auto_schedule = sanitize_text_field($post_data['auto_schedule'] ?? '');
//
//        $post = get_post($post_id);
//        if (!$post) {
//            wp_send_json_error('Post not found');
//        }
//
//        $update_args = [
//            'ID' => $post_id,
//            'edit_date' => true,
//        ];
//
//        if (intval($save_edited_content)) {
//            $update_args['post_content'] = $content;
//        }
//
//        if ($post_date && is_numeric($post_date)) {
//            $timestamp = intval($post_date);
//            $formatted_gmt_date = gmdate('Y-m-d H:i:s', $timestamp);
//            $formatted_local_date = get_date_from_gmt($formatted_gmt_date);
//            $update_args['post_date_gmt'] = $formatted_gmt_date;
//            $update_args['post_date'] = $formatted_local_date;
//        } else {
//            $update_args['post_date'] = current_time('mysql');
//            $update_args['post_date_gmt'] = gmdate('Y-m-d H:i:s');
//        }
//
//        $timestamp = strtotime($post_date);
//
//        if (intval($auto_schedule)) {
//            update_post_meta($post_id, 'seoaic_auto_scheduled', 1);
//            $update_args['post_status'] = 'draft';
//        } else {
//            delete_post_meta($post_id, 'seoaic_auto_scheduled');
//
//            if (empty($status)) {
//                if ($timestamp && $timestamp > current_time('timestamp')) {
//                    $update_args['post_status'] = 'future';
//                } else {
//                    $update_args['post_status'] = 'publish';
//                }
//            } else {
//                $update_args['post_status'] = $status;
//            }
//        }
//
//        $result = wp_update_post($update_args, true);
//
//        if (is_wp_error($result)) {
//            wp_send_json_error($result->get_error_message());
//        }
//
//        delete_post_meta($post_id, 'seoaic_ob_needs_review');
//        delete_post_meta($post_id, 'seoaic_ob_posting_date');
//
//        wp_send_json_success(['id' => $post_id]);
    }

    public function ob_save_and_accept_mass_posts()
    {
        check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);

        if (!current_user_can('edit_posts')) {
            SEOAICAjaxResponse::alert("Permission denied")->wpSend();
        }

        $posts = $_POST['posts'] ?? [];

        if (!is_array($posts) || empty($posts)) {
            wp_send_json_error('No posts provided');
        }

        $results = [];
        $errors = [];

        foreach ($posts as $post_data) {
//            if (empty($post_data['post_status'])) {
//                $post_data['post_status'] = 'draft';
//            }
            $post = wp_unslash($post_data);
            $result = $this->process_post_save_and_accept($post);

            if (is_wp_error($result)) {
                $errors[] = [
                    'post_id' => $post_data['post_id'] ?? 0,
                    'error' => $result->get_error_message(),
                ];
            } else {
                $results[] = $result;
            }
        }

        if (!empty($errors)) {
            wp_send_json_error(['saved' => $results, 'errors' => $errors]);
        }

        wp_send_json_success(['saved' => $results]);
    }

    private function get_date_based_on_status($status, $post_date, $ob_date, $is_utc = null) {
        $now = new DateTime('now', new DateTimeZone('UTC'));
        $max_date = (clone $now)->modify('+10 years');
        $date = new DateTime($post_date, new DateTimeZone('UTC'));
        $is_about_to_publish =
            ($status === 'future' || $status === 'publish')
            && $date <= $max_date;

        $postingDate = $is_about_to_publish
            ? $post_date
            : ($ob_date ? $ob_date : $post_date);

        return $postingDate;
    }

    public function ob_load_generated_posts_html()
    {
        check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);

        $post = wp_unslash($_POST);

        $ids = !empty($post['post_ids']) ? $post['post_ids'] : [];
        $ids = array_map('intval', $ids);
        $postGenerationOption = PostsGenerationLoader::getPostsOption();
        $result = [];

        foreach ($ids as $idea_id) {
            $post = get_post($idea_id);

            if (!$post) {
                error_log("Post with ID $idea_id not found.");
                continue;
            }

            $title = $post->post_title;
            $clusterName = get_post_meta($idea_id, 'seoaic_cluster', true) ?: '';
            $contentType = get_post_meta($idea_id, '_idea_type', true) ?: '';
            $postingDate = get_post_meta($idea_id, 'seoaic_ob_posting_date', true) ?: '';
            $status = $post->post_status;
            $postingDate = $this->get_date_based_on_status($status, $post->post_date, $postingDate);

            $language = get_post_meta($idea_id, 'seoaic_ob_language', true) ?: '';
            $keywords = get_post_meta($idea_id, 'seoaic_keywords', true);

            $html = $this->ideasListHtml(
                $idea_id,
                $title,
                $clusterName,
                $contentType,
                $postingDate,
                $status,
                $language,
                $keywords,
                true,
                $postGenerationOption
            );

            $result[$idea_id] = $html;
        }

        wp_send_json_success($result);
    }

    /**
     * @throws Exception
     */
    public function view_remote_ideas()
    {
        check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);

        if (!current_user_can('edit_posts')) {
            SEOAICAjaxResponse::alert("Permission denied")->wpSend();
        }

        $post = wp_unslash($_POST);

        global $wpdb;

        $return_number = isset($post['return_number']) && filter_var($post['return_number'], FILTER_VALIDATE_BOOLEAN);

        $post_ids = $wpdb->get_col($wpdb->prepare(
            "
            SELECT p.ID
            FROM {$wpdb->posts} p
            INNER JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id
            WHERE pm.meta_key = %s
              AND pm.meta_value = %s
              AND p.post_status NOT IN ('auto-draft', 'trash', 'inherit')
            ",
            'seoaic_ob_needs_review',
            '1'
        ));

        if ($return_number) {
            wp_send_json(count($post_ids));
        }

        $selected_ids = [];
        if (!empty($post['post_ids']) && is_array($post['post_ids'])) {
            $selected_ids = array_map('absint', $post['post_ids']);
        }

        $local_clusters = [];

        $ids = !empty($selected_ids) ? $selected_ids : $post_ids;

        if (!empty($ids)) {
            foreach ($ids as $post_id) {
                $get_post = get_post($post_id);
                if (!$get_post) {
                    continue;
                }

                $posting_date = get_post_meta($post_id, 'seoaic_ob_posting_date', true);
                $type = get_post_meta($post_id, '_idea_type', true);

                $local_clusters[] = [
                    'id' => $get_post->ID,
                    'title' => $get_post->post_title,
                    'status' => $get_post->post_status,
                    'cluster_name' => get_post_meta($get_post->ID, 'seoaic_cluster', true) ?: '',
                    'type' => $type,
                    'posting_date' => $posting_date,
                ];
            }

            usort($local_clusters, function ($a, $b) {
                $dateA = strtotime($a['posting_date'] ?? 'now');
                $dateB = strtotime($b['posting_date'] ?? 'now');
                return $dateA <=> $dateB;
            });
        }

        $postGenerationOption = PostsGenerationLoader::getPostsOption();
        $html = $this->createIdeasHTML($local_clusters, false, $postGenerationOption);

        wp_send_json(['html' => $html, 'count' => count($post_ids)]);
    }

    public function generate_cluster_ob_ideas_form_mini($cluster_id, $cluster_name)
    {
        global $SEOAIC, $SEOAIC_OPTIONS;
        $keywords = $SEOAIC->keywords->getKeywords();
        $clusters_options = [];
        if (!empty($SEOAIC_OPTIONS[self::CLUSTERS_GENERATED_STATUS])) {
            $clusters_options = $this->request_clusters(1, 100);
        }
        ob_start();
        ?>
        <div id="seoaic-generate_ob_ideas_form_<?php echo esc_attr($cluster_id) ?>" class="seoaic-pt-25">
            <div id="seoaic_get_onboarding_schedule_ideas"
                 class="seoaic-onboarding-selects seoaic-onboarding-selects-mini seoaic-ajax-form">
                <div class="inner d-none">
                    <label class="mb-5"><?php _e('How many month', 'seoaic'); ?></label>
                    <select id="seoaic-onboarding-select-how_many_month" name="how_many_month" class="seoaic-ajax-field"
                            data-placeholder="<?php _e('Not Selected', 'seoaic'); ?>">
                        <option value="1"><?php esc_html_e('1 month', 'seoaic'); ?></option>
                        <option value="3"><?php esc_html_e('3 month', 'seoaic'); ?></option>
                        <option value="6" selected><?php esc_html_e('6 month', 'seoaic'); ?></option>
                        <option value="12"><?php esc_html_e('12 month', 'seoaic'); ?></option>
                    </select>
                </div>
                <div class="inner inner-posts-per-month-per-cluster">
                    <label class="mb-5"
                           data-seoaic-tooltip-info="<?php esc_attr_e('Posts number', 'seoaic'); ?>"><?php _e('Posts', 'seoaic'); ?></label>
                    <input type="number" id="seoaic-onboarding-input-posts_per_month_per_cluster"
                           min="1"
                           max="3700"
                           name="posts_per_month_per_cluster"
                           class="seoaic-form-item form-input light seoaic-ajax-field"
                           value="5" placeholder="<?php _e('Set number of posts', 'seoaic'); ?>">
                </div>
                <div class="inner">
                    <label class="mb-5"><?php _e('Content type', 'seoaic'); ?></label>
                    <select id="seoaic-onboarding-select-selected_content_types_<?php echo esc_attr($cluster_id) ?>" name="selected_content_types"
                            class="clusters seoaic-ajax-field"
                            data-placeholder="<?php _e('Not Selected', 'seoaic'); ?>">
                        <?php
                        foreach (seoaic_get_prompt_template_types() as $key => $template_type) {
                            ?>
                            <option value="<?php echo esc_attr($key);?>"><?php echo esc_html($template_type);?></option>
                            <?php
                        }
                        ?>
                    </select>
                </div>
                <div class="inner d-none">
                    <label class="mb-5"><?php esc_html_e('Starting date', 'seoaic'); ?></label>
                    <input type="hidden" id="seoaic-onboarding-input-starting_schedule_date_utc_<?php echo esc_attr($cluster_id) ?>"
                           name="starting_schedule_date_utc" class="seoaic-ajax-field" value="">
                    <input type="text" id="seoaic-onboarding-input-starting_schedule_date_<?php echo esc_attr($cluster_id) ?>"
                           name="starting_schedule_date" class="seoaic-form-item form-input light seoaic-ajax-field"
                           value="" placeholder="<?php esc_attr_e('Starting date', 'seoaic'); ?>">
                </div>
                <div class="inner seoiac-advanced-options mt-10">
                    <label class="accent accent-underline"
                           for="seoiac-open-advanced-options-generate-ob-ideas_<?php echo esc_attr($cluster_id) ?>"><?php esc_html_e(' Advanced Options (Optional)', 'seoaic'); ?></label>
                    <input type="checkbox" id="seoiac-open-advanced-options-generate-ob-ideas_<?php echo esc_attr($cluster_id) ?>">
                    <div class="seoiac-advanced-options-generate-ob-ideas">
                        <div class="d-flex seoaic-flex-column">
                            <div class="d-flex seoaic-flex-column seoaic-ob-left-col-options">
                                <label class="mb-10 mt-20"
                                       for="custom-prompt"><?php esc_html_e('Custom Prompt / Instructions', 'seoaic'); ?></label>
                                <textarea class="seoaic-form-item form-input light light seoaic-ajax-field seoaic-fs-14 seoaic-ob-custom-prompt"
                                          name="CustomPrompt"
                                          placeholder="<?php esc_attr_e('Enter any specific instructions or themes for the AI...', 'seoaic') ?>"
                                          rows="3"></textarea>
                            </div>
                            <div class="d-flex">
                                <div class="d-flex seoaic-flex-column mb-19 padding-x seoaic-ob-center-col-options">
                                    <div class="d-flex seoaic-flex-column seoaic-ob-select-options">
                                        <label for="seoaic-ob-select-keywords"
                                               class="mt-15"><?php esc_html_e('Keywords', 'seoaic'); ?></label>
                                        <select multiple name="seoaic-select-ob-keywords"
                                                class="seoaic-ajax-field">
                                            <?php
                                            foreach ($keywords as $keyword) {
                                                echo '<option value="' . esc_attr($keyword['slug']) . '">' . esc_html($keyword['name']) . '</option>';
                                            }
                                            ?>
                                        </select>
                                    </div>
                                    <div class="d-flex seoaic-flex-column seoaic-ob-select-options">
                                        <?php
                                        echo SEOAIC_SETTINGS::createRepeaterHTML('seoaic_services', true, false, false, 'seoaic-ajax-field', 'seoaic-ob-select-services', false);
                                        ?>
                                    </div>
                                    <div class="d-flex seoaic-flex-column seoaic-ob-select-options">
                                        <?php
                                        echo SEOAIC_SETTINGS::createRepeaterHTML('seoaic_target_audience', true, false, false, 'seoaic-ajax-field', 'seoaic-ob-select-targets', false);
                                        ?>
                                    </div>
                                </div>
                                <div class="d-flex seoaic-flex-column mb-19 seoaic-ob-right-col-options">
                                    <div class="mb-10 mt-15"><?php echo $SEOAIC->multilang->get_multilang_checkboxes(); ?></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <button title="Apply" type="button" class="seoaic-magic-button seoaic-ajax-submit generate-cluster-ideas mt-15">
                    <input type="hidden" class="seoaic-ajax-field" name="action" value="seoaic_onboarding_cluster_ideas_generate">
                    <input type="hidden" class="seoaic-ajax-field" name="id" value="<?php echo esc_attr($cluster_id) ?>">
                    <input type="hidden" class="seoaic-ajax-field" name="cluster_name" value="<?php echo esc_attr($cluster_name) ?>">
                    <input type="hidden" class="seoaic-ajax-field" name="quantity" value="10">
                    <?php esc_html_e('Generate more ideas', 'seoaic'); ?>
                </button>
            </div>
        </div>
        <?php
        return ob_get_clean();
    }

    public function cluster_pages_and_ideas() {
        $post = wp_unslash($_POST);

        global $wpdb;

        $meta_key   = 'seoaic_cluster';
        $meta_value = $post['cluster_name'];
        $cluster_id = $post['cluster_id'];

        $excluded_statuses = [ 'trash', 'auto-draft', 'inherit' ];
        $placeholders      = implode(',', array_fill(0, count($excluded_statuses), '%s'));

        $query = $wpdb->prepare(
            "
        SELECT pm.post_id, p.post_type, p.post_title, p.post_status
        FROM {$wpdb->postmeta} pm
        INNER JOIN {$wpdb->posts} p ON p.ID = pm.post_id
        WHERE pm.meta_key = %s
        AND pm.meta_value = %s
        AND p.post_status NOT IN ($placeholders)
        ",
            array_merge([ $meta_key, $meta_value ], $excluded_statuses)
        );

        $results = $wpdb->get_results($query);

        $pages_html = '';
        $ideas_html = '';

        $pages_count = 0;
        $ideas_count = 0;

        foreach ($results as $row) {
            if ($row->post_type === 'seoaic-post') {
                $ideas_html .= $this->render_post_html(intval($row->post_id));
                $ideas_count++;
            } else {
                $pages_html .= $this->render_post_html(intval($row->post_id));
                $pages_count++;
            }
        }

        $pages_html = '
        <div class="inner-card inner-card-pages active loaded">
            <div id="seoaic_cluster_graph_id_' . $post['cluster_id'] . '" class="graph-chart">
                <div class="chart-container"></div>
                <div class="hiden-border-offset"></div>
            </div>
            <div class="article-row summary-articles">
                <div class="count"><p>' . esc_html($pages_count) . '</p><span>' . esc_html__('Posts', 'seoaic') . '</span></div>
            </div>
            <div class="seoaic-scroll-vertical">
                <ul class="seoaic-mind-map-clusters-card-inner-posts-timeline">
                   ' . $pages_html . '
                </ul>
            </div>
            <button title="Apply" type="button" data-cluster-id="{$cluster_id}" data-cluster-name="'.esc_attr($post['cluster_name']).'" class="d-none add-page-to-cluster-modal seoaic-button-small modal-button position-relative" data-modal="#seoaic-alert-modal" data-title="Select page" data-content="">
                ' . esc_html__('Add page', 'seoaic') . '
            </button>
        </div>
    ';

        $ideas_html = '
        <div class="inner-card inner-card-ideas seoaic-pt-0 loaded">
            <div class="article-row summary-articles">
                <div class="count">
                    <p>' . esc_html($ideas_count) . '</p><span>' . esc_html__('Ideas', 'seoaic') . '</span>
                </div>
            </div>
            <div class="seoaic-scroll-vertical">
                <ul class="seoaic-mind-map-clusters-card-inner-posts-timeline">
                   ' . $ideas_html . '
                </ul>
            </div>
            <div class="generate-cluster-ideas-form">
            ' . $this->generate_cluster_ob_ideas_form_mini($cluster_id, $meta_value) . '
            </div>
        </div>
    ';

        wp_send_json_success([
            'pages_html' => $pages_html,
            'ideas_html' => $ideas_html,
        ]);
    }

    private function syncTaxClustersWithBackend($clusters_data = null) {
        $this->clearKeywordsClustersTransient();
        $clusters_data = $this->getOrSetClustersTransient();

        $existing_terms = get_terms([
            'taxonomy'   => self::KEYWORDS_CATEGORIES_KEY,
            'hide_empty' => false,
        ]);

        $local_without_remote = [];
        $map_remote = [];

        foreach ($existing_terms as $term) {
            $remote_id = get_term_meta($term->term_id, 'remote_cluster_id', true);
            if ($remote_id) {
                $map_remote[$remote_id] = $term;
            } else {
                $local_without_remote[] = $term;
            }
        }

        if (!empty($local_without_remote)) {
            $names = wp_list_pluck($local_without_remote, 'name');
            $new_clusters = $this->insertClusters($names, true);

            if (!empty($new_clusters)) {
                foreach ($new_clusters as $cluster) {
                    foreach ($local_without_remote as $term) {
                        if ($term->name === $cluster['name']) {
                            update_term_meta($term->term_id, 'remote_cluster_id', $cluster['id']);
                        }
                    }
                }
                $clusters_data = array_merge($clusters_data, $new_clusters);
            }
        }

        $clusters_map_by_id = [];
        foreach ($clusters_data as $cluster) {
            $clusters_map_by_id[$cluster['id']] = $cluster['name'];
        }

        foreach ($map_remote as $remote_id => $term) {
            if (!isset($clusters_map_by_id[$remote_id])) {
                wp_delete_term($term->term_id, self::KEYWORDS_CATEGORIES_KEY);
            } else {
                $expected_name = $clusters_map_by_id[$remote_id];
                if ($term->name !== $expected_name) {
                    wp_update_term($term->term_id, self::KEYWORDS_CATEGORIES_KEY, [
                        'name' => $expected_name,
                    ]);
                }
            }
        }

        $existing_names = wp_list_pluck($existing_terms, 'name');
        foreach ($clusters_data as $cluster) {
            if (!in_array($cluster['name'], $existing_names)) {
                $term = wp_insert_term($cluster['name'], self::KEYWORDS_CATEGORIES_KEY);
                if (!is_wp_error($term)) {
                    update_term_meta($term['term_id'], 'remote_cluster_id', $cluster['id']);
                }
            }
        }
    }

    private function addKeywordsCluster($remote_cluster_id, $cluster_name) {
        $term = wp_insert_term($cluster_name, self::KEYWORDS_CATEGORIES_KEY);
        if (!is_wp_error($term)) {
            update_term_meta($term['term_id'], 'remote_cluster_id', $remote_cluster_id);
        }
    }

    private function updateOrRemoveKeywordsCluster($remote_cluster_id, $cluster_name = null) {
        $terms = get_terms([
            'taxonomy'   => self::KEYWORDS_CATEGORIES_KEY,
            'hide_empty' => false,
            'meta_query' => [
                [
                    'key'     => 'remote_cluster_id',
                    'value'   => $remote_cluster_id,
                    'compare' => '='
                ]
            ]
        ]);

        if (empty($terms) || is_wp_error($terms)) {
            return;
        }

        $term = $terms[0];

        if ($cluster_name === null) {
            wp_delete_term($term->term_id, self::KEYWORDS_CATEGORIES_KEY);
        } elseif ($term->name !== $cluster_name) {
            wp_update_term($term->term_id, self::KEYWORDS_CATEGORIES_KEY, [
                'name' => $cluster_name
            ]);
        }
    }

    private function getOrSetClustersTransient()
    {
        $clusters_options = get_transient(self::CLUSTERS_CACHE);

        if (false === $clusters_options) {
            $clusters_options = $this->request_clusters(1, 100);
            set_transient(self::CLUSTERS_CACHE, $clusters_options, DAY_IN_SECONDS);
        }

        return !empty($clusters_options['data']['data']) && is_array($clusters_options['data']['data']) ? $clusters_options['data']['data'] : [];
    }

    private function clearKeywordsClustersTransient() {
        delete_transient(self::CLUSTERS_CACHE);
    }

    public function migrateClusters() {
        $clusters = $this->getOrSetClustersTransient();

        $terms = get_terms([
            'taxonomy'   => self::KEYWORDS_CATEGORIES_KEY,
            'hide_empty' => false,
        ]);

        $has_without_remote = false;
        $is_compared = count($terms) !== count($clusters);

        foreach ($terms as $term) {
            $remote_id = get_term_meta($term->term_id, 'remote_cluster_id', true);
            if (empty($remote_id)) {
                $has_without_remote = true;
                break;
            }
        }

        if ($has_without_remote || $is_compared) {
            error_log('== CLUSTERS SYNC WITH BACKEND ==');
           $this->syncTaxClustersWithBackend();
        }
    }
}