<?php

namespace SEOAIC;

use DateTime;
use DateTimeZone;
use Exception;
use SEOAIC\resources\ContentAlertSettings;
use SeoaicAjaxValidation;

class SEOAIC_SETTINGS
{
    public const SEOAI_POST = 'seoai_post';

    private $seoaic;

    public function __construct($seoaic)
    {
        $this->seoaic = $seoaic;
        add_action('wp_ajax_seoaic_settings_generate_description', [$this, 'generateDescription']);
        add_action('wp_ajax_seoaic_settings_content_alerts_save', [$this, 'contentAlertsSaveAjax']);
        add_action('wp_ajax_seoaic_drafts_queue', [$this, 'drafts_queue']);
        add_action('wp_ajax_seoaic_sort_auto_scheduled_drafts', [$this, 'sort_auto_scheduled_drafts']);
        add_action('wp_ajax_seoaic_settings_save_description', [$this, 'settings_save_description']);
        add_action('wp_ajax_seoaic_update_industry', [$this, 'seoaic_update_industry']);
        add_action('wp_ajax_seoaic_settings_custom_template_save', [$this, 'saveCustomTemplateSettingsAjax']);

        add_action('init', [$this, 'init_auto_schedule_action']);
        add_action('init', [$this, 'initCustomPostType']);
    }

    public static function getLanguage()
    {
        global $SEOAIC_OPTIONS;

        return !empty($SEOAIC_OPTIONS['seoaic_language']) ? $SEOAIC_OPTIONS['seoaic_language'] : 'English';
    }

    public static function getTranslatingGuidelines()
    {
        global $SEOAIC_OPTIONS;

        return !empty($SEOAIC_OPTIONS['seoaic_translating_guidelines']) ? $SEOAIC_OPTIONS['seoaic_translating_guidelines'] : '';
    }

    public static function getCustomFaqPrompt()
    {
        global $SEOAIC_OPTIONS;

        return !empty($SEOAIC_OPTIONS['seoaic_custom_faq_prompt']) ? $SEOAIC_OPTIONS['seoaic_custom_faq_prompt'] : '';
    }

    public static function getLeadsFormGoalPromptDefault()
    {
        global $SEOAIC_OPTIONS;

        return !empty($SEOAIC_OPTIONS['seoaic_default_leads_form_prompt']) ? $SEOAIC_OPTIONS['seoaic_default_leads_form_prompt'] : '';
    }

    public static function getIndustry()
    {
        global $SEOAIC_OPTIONS;

        return !empty($SEOAIC_OPTIONS['seoaic_industry']) ? $SEOAIC_OPTIONS['seoaic_industry'] : '';
    }

    public static function getBusinessName()
    {
        global $SEOAIC_OPTIONS;

        return !empty($SEOAIC_OPTIONS['seoaic_business_name']) ? $SEOAIC_OPTIONS['seoaic_business_name'] : get_option('blogname', true);
    }

    public static function getBusinessDescription()
    {
        global $SEOAIC_OPTIONS;

        return !empty($SEOAIC_OPTIONS['seoaic_business_description']) ? $SEOAIC_OPTIONS['seoaic_business_description'] : get_option('blogdescription', true);
    }

    private function setBusinessDescription($value)
    {
        $value = stripslashes(sanitize_textarea_field($value));
        $this->seoaic->set_option('seoaic_business_description', $value);
    }

    public static function getLocation()
    {
        global $SEOAIC_OPTIONS;

        return !empty($SEOAIC_OPTIONS['seoaic_location']) ? $SEOAIC_OPTIONS['seoaic_location'] : 'United States';
    }

    public static function getCompanyWebsite($part = '')
    {
        global $SEOAIC_OPTIONS;

        $companyWebsite = !empty($SEOAIC_OPTIONS['seoaic_company_website']) ? $SEOAIC_OPTIONS['seoaic_company_website'] : get_bloginfo('url');

        if ('host' == $part) {
            return wp_parse_url($companyWebsite)['host'];
        }

        return $companyWebsite;
    }

    public static function getSEOAICPostType()
    {
        global $SEOAIC_OPTIONS;

        return !empty($SEOAIC_OPTIONS['seoaic_post_type']) ? $SEOAIC_OPTIONS['seoaic_post_type'] : 'post';
    }

    public static function getPostsDefaultCategories()
    {
        global $SEOAIC_OPTIONS;

        return !empty($SEOAIC_OPTIONS['seoaic_default_category']) ? $SEOAIC_OPTIONS['seoaic_default_category'] : [];
    }

    public static function getPostsGeneratePromptTemplates()
    {
        global $SEOAIC_OPTIONS;

        return !empty($SEOAIC_OPTIONS['seoaic_posts_mass_generate_prompt_templates']) ? $SEOAIC_OPTIONS['seoaic_posts_mass_generate_prompt_templates'] : [];
    }

    public static function setPostsGeneratePromptTemplates($value)
    {
        self::save('seoaic_posts_mass_generate_prompt_templates', $value);
    }

    public static function getPostsEditPromptTemplates()
    {
        global $SEOAIC_OPTIONS;

        return !empty($SEOAIC_OPTIONS['seoaic_posts_mass_edit_prompt_templates']) ? $SEOAIC_OPTIONS['seoaic_posts_mass_edit_prompt_templates'] : [];
    }

    public static function setPostsEditPromptTemplates($value)
    {
        self::save('seoaic_posts_mass_edit_prompt_templates', $value);
    }

    public static function getPostsReviewPromptTemplates()
    {
        global $SEOAIC_OPTIONS;

        return !empty($SEOAIC_OPTIONS['seoaic_posts_mass_review_prompt_templates']) ? $SEOAIC_OPTIONS['seoaic_posts_mass_review_prompt_templates'] : [];
    }

    public static function setPostsReviewPromptTemplates($value)
    {
        self::save('seoaic_posts_mass_review_prompt_templates', $value);
    }

    public static function getKeywordsGeneratePromptTemplates()
    {
        global $SEOAIC_OPTIONS;

        return !empty($SEOAIC_OPTIONS['seoaic_keywords_generate_prompt_templates']) ? $SEOAIC_OPTIONS['seoaic_keywords_generate_prompt_templates'] : [];
    }

    public static function setKeywordsGeneratePromptTemplates($value)
    {
        self::save('seoaic_keywords_generate_prompt_templates', $value);
    }

    public static function getIdeasGeneratePromptTemplates()
    {
        global $SEOAIC_OPTIONS;

        return !empty($SEOAIC_OPTIONS['seoaic_ideas_generate_prompt_templates']) ? $SEOAIC_OPTIONS['seoaic_ideas_generate_prompt_templates'] : [];
    }

    public static function setIdeasGeneratePromptTemplates($value)
    {
        self::save('seoaic_ideas_generate_prompt_templates', $value);
    }

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

    public static function getSubtitlesRangeMin()
    {
        global $SEOAIC_OPTIONS;
        return !empty(intval($SEOAIC_OPTIONS['seoaic_subtitles_range_min'])) ? intval($SEOAIC_OPTIONS['seoaic_subtitles_range_min']) : 2;
    }

    public static function getSubtitlesRangeMax()
    {
        global $SEOAIC_OPTIONS;
        return !empty(intval($SEOAIC_OPTIONS['seoaic_subtitles_range_max'])) ? intval($SEOAIC_OPTIONS['seoaic_subtitles_range_max']) : 6;
    }

    public static function getWordsRangeMin()
    {
        global $SEOAIC_OPTIONS;
        return !empty(intval($SEOAIC_OPTIONS['seoaic_words_range_min'])) ? intval($SEOAIC_OPTIONS['seoaic_words_range_min']) : 500;
    }

    public static function getWordsRangeMax()
    {
        global $SEOAIC_OPTIONS;
        return !empty(intval($SEOAIC_OPTIONS['seoaic_words_range_max'])) ? intval($SEOAIC_OPTIONS['seoaic_words_range_max']) : 1000;
    }

    public static function getWritingStyle()
    {
        global $SEOAIC_OPTIONS;
        return !empty($SEOAIC_OPTIONS['seoaic_writing_style']) ? $SEOAIC_OPTIONS['seoaic_writing_style'] : '';
    }

    public static function isGutenbergTinyMCEDisabled()
    {
        global $SEOAIC_OPTIONS;
        return !empty($SEOAIC_OPTIONS['seoaic_gutenberg_tinymce_on']) && 'off' == $SEOAIC_OPTIONS['seoaic_gutenberg_tinymce_on'];
    }

    public static function isGeneratedContentInCustomFieldTurnedOn(): bool
    {
        global $SEOAIC_OPTIONS;

        $value = !empty($SEOAIC_OPTIONS['seoaic_show_generated_content_in_custom_field'])
            ? $SEOAIC_OPTIONS['seoaic_show_generated_content_in_custom_field']
            : false;

        return (bool)$value;
    }

    public static function isContentImprovementDisabled()
    {
        global $SEOAIC_OPTIONS;
        return !empty($SEOAIC_OPTIONS['seoaic_activate_content_improvement']) && 'off' == $SEOAIC_OPTIONS['seoaic_activate_content_improvement'];
    }

    public static function isHidePostsEnabled()
    {
        global $SEOAIC_OPTIONS;
        return !empty($SEOAIC_OPTIONS['seoaic_hide_posts']);
    }

    public static function isShowRelatedArticlesEnabled()
    {
        global $SEOAIC_OPTIONS;
        return !empty($SEOAIC_OPTIONS['seoaic_show_related_articles']);
    }

    public static function isGenerateInternalLinksEnabled()
    {
        global $SEOAIC_OPTIONS;
        return !empty($SEOAIC_OPTIONS['seoaic_generate_internal_links']);
    }

    public static function isAddPillarLinksEnabled()
    {
        global $SEOAIC_OPTIONS;
        return !empty($SEOAIC_OPTIONS['seoaic_pillar_link_action']);
        /**
         * @return [] Array of styles in "key" => "value" format
         */
    }

    public static function getImageGenerateStylesAvailable()
    {
        return [
            "Illustrations" => "Illustrations",
            "Photorealism" => "Photorealism",
            "Digital art" => "Digital art",
            "Minimalism" => "Minimalism",
            "Collages" => "Collages",
        ];
    }

    public static function getImageGenerateStyle()
    {
        global $SEOAIC_OPTIONS;
        return $SEOAIC_OPTIONS['seoaic_image_generate_style'] ?? 'Photorealism';
    }

    public static function getImageGeneratePromptDefault()
    {
        global $SEOAIC_OPTIONS;
        return $SEOAIC_OPTIONS['seoaic_image_generate_prompt_default'] ?? '';
    }

    public static function getImageGenerateWidthDefault()
    {
        global $SEOAIC_OPTIONS;
        return $SEOAIC_OPTIONS['seoaic_image_generate_width_default'] ?? 1024;
    }

    public static function getImageGenerateHeightDefault()
    {
        global $SEOAIC_OPTIONS;
        return $SEOAIC_OPTIONS['seoaic_image_generate_height_default'] ?? 768;
    }

    public static function isGSCIntegrated()
    {
        global $SEOAIC_OPTIONS;

        return isset($SEOAIC_OPTIONS['seoaic_integrate_google_search_console_checkbox'])
            && $SEOAIC_OPTIONS['seoaic_integrate_google_search_console_checkbox'];
    }

    public static function getScheduledPostingTime()
    {
        global $SEOAIC_OPTIONS;
        return !empty($SEOAIC_OPTIONS['seoaic_default_scheduled_posting_time']) ? $SEOAIC_OPTIONS['seoaic_default_scheduled_posting_time'] : '8:00';
    }

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

        $_post = wp_unslash($_POST);

        $prompt = !empty($_post['prompt']) ? strip_tags($_post['prompt']) : '';
        $target_name = !empty($_post['target_name']) ? $_post['target_name'] : self::getBusinessName();

        if (empty($target_name)) {
            SEOAICAjaxResponse::error('Empty Target Audience name.')->wpSend();
        }

        $data = [
            'prompt' => $prompt,
            'target_name' => $target_name,
            'type' => $_post['type'],
            'words_min' => $_post['generate_words-min'],
            'words_max' => $_post['generate_words-max'],
            'website' => self::getCompanyWebsite(),
            'domain' => self::getCompanyWebsite(),
            'company_name' => self::getBusinessName(),
            'company_description' => self::getBusinessDescription(),
            'industry' => self::getIndustry(),
            'language' => $this->seoaic->getDefaultLanguageName(),
        ];

        $result = $this->seoaic->curl->init('/api/ai/expand-description', $data, true, true, true);

        if (
            !empty($result)
            && 'success' == $result['status']
            && !empty($result['description'])
        ) {
            $description = $result['description'];
        }

        if (!empty($description)) {
            if ($_post['type'] === 'company') {
                $this->setBusinessDescription($description);
            }
            SEOAICAjaxResponse::success()->addFields([
                'content' => [
                    'description' => $description
                ],
            ])->wpSend();
        }

        SEOAICAjaxResponse::alert('Could not generate description.')->wpSend();
    }

    public static function createRepeaterHTML($optionKey, $select = false, $generate_button = false, $single = false, $select_class = false, $custom_select_name = false, $is_multiple = true, $options = [], $label = true)
    {
        global $SEOAIC_OPTIONS;
        $base_prompt = '';
        $on_empty = '';

        switch ($optionKey) {
            case 'seoaic_target_audience':
                $title = esc_html__('Target Audience', 'seoaic');
                $description_type = 'target_audience'; // company_description, service_description, target_audience_description
                break;
            case 'seoaic_services':
                $title = esc_html__('Company service', 'seoaic');
                $description_type = 'service';
                break;
            case 'seoaic_business_description':
                $title = esc_html__('Description of the company', 'seoaic');
                $description_type = 'company';
                $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.');
                $on_empty = '';
                break;
            default:
                $title = esc_html__('Selection', 'seoaic');
                $description_type = 'company';
                break;
        }

        $html = '';

        if (!$single) {

            $repeater_option = !empty($SEOAIC_OPTIONS[$optionKey]) ? $SEOAIC_OPTIONS[$optionKey] : [];

            if(!empty($options)) {
                $repeater_option = $options;
            }

            if ($select) {
                $class_name = $select_class ? $select_class : 'settings_repeater_select';
                $custom_select_name = $custom_select_name ? $custom_select_name : $optionKey;
                $multiple_select = $is_multiple ? 'multiple' : '';
                if ($repeater_option) {
                    $html .= '<label class="mb-10 mt-20">' . esc_html__('Choose ' . $title, 'seoaic') . '</label>';
                    $html .= '<select name="' . esc_attr($custom_select_name) . '" class="seoaic-form-item form-select ' . esc_attr($class_name) . '" data-placeholder="' . esc_html__('Select ' . $title, 'seoaic') . '" ' . esc_attr($multiple_select) . '>';
                    $html .= '     <option value="">' . esc_html__('Select ' . $title, 'seoaic') . '</option>';

                    foreach ($repeater_option as $i => $value) {
                        if (isset($value['name'])) {
                            $html .= '<option value="' . esc_attr($i) . '">' . esc_html($value['name']) . '</option>';
                        }
                    }

                    $html .= '</select>';
                }

                return $html;
            }

            if ($label) {
                $html .= '<label>' . $title . '</label>';
            }
            $html .= '<div class="seoaic_input_repeater seoaic_services mb-19" data-option="' . $optionKey . '">
                            <div id="' . $optionKey . '_' . uniqid() . '" class="list">';

            $base_prompt = esc_attr('Create a more detailed definition of the website\'s ' . $title . ' called input_name');

            if ($generate_button) {
                $generate_button = '<a href="#" data-type="' . $description_type . '" data-option-key="' . $optionKey . '" data-base-prompt="' . $base_prompt . '" class="modal-button seoaic-magic-button fw-600 seoaic-mt-5" data-modal="#settings-description-generate-modal" data-action="seoaic_settings_generate_description">' . esc_html__('Generate Description', 'seoaic') . '</a>';
            }

            foreach ($repeater_option as $item) {

                $name = esc_attr($item['name']);
                $text = !empty($item['text'] ?? $item['description']) ? esc_html($item['text'] ?? $item['description']) : '';
                $html .= '
                    <div class="service-section active">
                        <input type="checkbox" class="seoaic-checkbox" checked="">
                        <div class="item">
                            <input
                                data-id="input_' . $optionKey . '_' . uniqid() . '"
                                type="text"
                                class="form-input light ' . $optionKey . '-input"
                                name="' . $optionKey . '-input"
                                placeholder="' . esc_html__($title . ' name', 'seoaic') . '"
                                value="' . $name . '"
                                required
                            />
                            <textarea
                                data-id="textarea_' . $optionKey . '_' . uniqid() . '"
                                class="form-input light seoaic-textarea-autoresize"
                                name="service-text"
                                placeholder="' . esc_html__($title . ' description (optional)', 'seoaic') . '"
                                autocomplete="off"
                                rows="3"
                            >' . $text . '</textarea>
                            ' . $generate_button . '
                            <a
                                href="#"
                                class="delete delete-service seoaic_edit_meta_cancel"
                                title="' . esc_html__('Remove', 'seoaic') . '"
                            ></a>
                        </div>
                    </div>
                    ';
            }

            $html .= '</div>
            <a href="#"
               class="add seoaic_repeater_add_new_section"
               data-title="' . $title . '"
               data-option="' . $optionKey . '"
               data-loading="' . esc_html__('Adding', 'seoaic') . '"
               data-name-field="' . esc_html__($title . ' name', 'seoaic') . '"
               data-text-field="' . esc_html__($title . ' description', 'seoaic') . '"
               data-generate-button="' . esc_html($generate_button) . '"
               data-action="seoaic_repeater_add_new_section"
               title="' . $title . '">
               ' . esc_html__('+ Add Item', 'seoaic') . '
            </a>
            </div>';

            return $html;
        }

        $single_option = !empty($SEOAIC_OPTIONS[$optionKey]) ? esc_html($SEOAIC_OPTIONS[$optionKey]) : esc_html($on_empty);

        if(!empty($options)) {
            $single_option = $options;
        }
        if ($label) {
            $html .= '<label>' . $title . '</label>';
        }
        $html .= '
                    <div class="seoaic_input_repeater mb-19" data-option="' . $optionKey . '">
                        <div id="' . $optionKey . '_' . uniqid() . '" class="list">
                            <div class="service-section">
                                <div class="item">
                                    <textarea
                                    class="seoaic-form-item form-input light seoaic-textarea-autoresize"
                                    id="' . $optionKey . '"
                                    data-id="textarea_' . $optionKey . '_' . uniqid() . '"
                                    placeholder="' . $title . '"
                                    autocomplete="off"
                                    name="' . $optionKey . '"
                                    rows="6"
                                     >' . $single_option . '</textarea>
                                    <a href="#" data-target-name="' . self::getBusinessName() . '" data-type="' . $description_type . '" data-option-key="' . $optionKey . '" data-base-prompt="' . $base_prompt . '" class="modal-button seoaic-magic-button fw-600 seoaic-mt-5" data-modal="#settings-description-generate-modal" data-action="seoaic_settings_generate_description" data-form-callback="settings_target_audience_update_description">' . esc_html__('Generate Description', 'seoaic') . '</a>
                                </div>
                            </div>
                        </div>
                    </div>';

        return $html;
    }

    public static function getSelectedRepeaterValues($optionKey, $selected_indexes, $comma_separated = false)
    {

        global $SEOAIC_OPTIONS;

        $repeater_options = !empty($SEOAIC_OPTIONS[$optionKey]) ? $SEOAIC_OPTIONS[$optionKey] : [];

        $selected_values = [];

        foreach ((array)$selected_indexes as $index) {
            $index = $index - 1;
            $name = $repeater_options[intval($index)]['name'];
            $description = $repeater_options[intval($index)]['text'];

            if ($comma_separated) {
                $selected_values[] = $name . ' (' . $description . ')';
                continue;
            }

            $selected_values[] = [$name, $description];
        }

        if ($comma_separated) {
            return implode(',', $selected_values);
        }

        return $selected_values;
    }

    public function contentAlertsLoad()
    {
        try {
            $response = $this->seoaic->curl->setMethodGet()->initWithReturn('api/content-alerts/config', '', false, true);

            if (!$response) {
                throw new Exception("Can't get the saved settings.");
            }

            return ContentAlertSettings::fromBackendResponse($response)->toArray();
        } catch (Exception $e) {
            return [
                'error' => $e->getMessage(),
            ];
        }

        return [];
    }

    public function contentAlertsSave(ContentAlertSettings $settings)
    {
        $data = [
            'data' => $settings->toArray(),
        ];
        $response = $this->seoaic->curl->initWithReturn('api/content-alerts/config', $data, true, true);

        if (!$response) {
            throw new Exception(esc_html__("Can't save the settings.", "seoaic"));
        }

        if (
            empty($response['status'])
            || 'success' != $response['status']
        ) {
            if (!empty($response['message'])) {
                throw new Exception(esc_html__('Error: ', 'seoaic') . esc_html($response['message']));
            }

            throw new Exception(esc_html__("Settings not saved.", "seoaic"));
        }

        return 'success' == $response['status'];
    }

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

        try {
            $__REQUEST = wp_unslash($_REQUEST);
            $settings = ContentAlertSettings::fromAjaxRequest($__REQUEST);

            if (!$settings->isValid()) {
                SEOAICAjaxResponse::error(esc_html__('Wrong data:', 'seoaic') . $settings->getErrors())->wpSend();
            }

            if ($this->contentAlertsSave($settings)) {
                SEOAICAjaxResponse::alert(esc_html__("Settings saved.", "seoaic"))->wpSend();
            }

            SEOAICAjaxResponse::error(esc_html__('Not saved.', 'seoaic'))->wpSend();

        } catch (Exception $e) {
            SEOAICAjaxResponse::error($e->getMessage())->wpSend();
        }
    }

    // AUTO SCHEDULER
    public function init_auto_schedule_action()
    {
        global $SEOAIC_OPTIONS;

        if (empty($SEOAIC_OPTIONS['seoaic_schedule_days']) || !is_array($SEOAIC_OPTIONS['seoaic_schedule_days'])) {
            return;
        }

        $result = array_map(static function ($item) {
            if (empty($item['time']) || empty($item['posts'])) {
                return null;
            }

            try {
                $date = new DateTime($item['time']);
            } catch (Exception $e) {
                error_log('Invalid date format in seoaic_schedule_days: ' . $e->getMessage());
                return null;
            }

            return [
                'posts' => $item['posts'],
                'time' => sanitize_text_field($item['time']),
                'day' => strtolower($date->format('l')),
                'parsed_time' => $date->format('h:i A'),
            ];
        }, $SEOAIC_OPTIONS['seoaic_schedule_days']);

        $result = array_filter($result);

        foreach ($result as $data) {
            $time_hook = self::convertTimeToHook($data['parsed_time']);
            $cron_hook = "seoaic_auto_publish_drafts_{$data['day']}_{$time_hook}";

            add_action($cron_hook, static function ($count) {
                self::publish_drafts($count);
            }, 10, 1);
        }
    }

    private static function valid_time($day, $time)
    {
        $data_time = strtoupper($time);
        $date = DateTime::createFromFormat('g:i A', $data_time);
        $formattedTime = $date->format('H:i');

        $day = ucfirst($day);

        $timestamp_today = strtotime("{$day} {$formattedTime} UTC");
        $timestamp_next = strtotime("next {$day} {$formattedTime} UTC");

        $current_time = time();
        return ($timestamp_today > $current_time) ? $timestamp_today : $timestamp_next;
    }

    private static function convertTimeToHook($time)
    {
        return strtolower(str_replace([':', ' '], '_', $time));
    }

    private static function unschedule_all()
    {
        $crons = _get_cron_array();
        foreach ($crons as $timestamp => $cron) {
            foreach ($cron as $hook => $event) {
                if (strpos($hook, 'seoaic_auto_publish_drafts_') === 0) {
                    foreach ($event as $details) {
                        wp_unschedule_event($timestamp, $hook, $details['args']);
                        wp_unschedule_hook($hook);
                        wp_clear_scheduled_hook($hook);
                    }
                }
            }
        }
    }

    public static function get_auto_schedule_posts_dates()
    {

        global $SEOAIC_OPTIONS;

        $data = !empty($SEOAIC_OPTIONS['seoaic_schedule_days']) ? $SEOAIC_OPTIONS['seoaic_schedule_days'] : [];

        return array_map(function ($item) {
            $date = new DateTime($item['time']);
            return array(
                'posts' => $item['posts'],
                'time' => $item['time'],
                'day' => strtolower($date->format('l')),
                'parsed_time' => $date->format('h:i A'),
            );
        }, $data);
    }

    public static function setup_auto_publish_cron()
    {
        global $SEOAIC;

        self::unschedule_all();

        foreach (self::get_auto_schedule_posts_dates() as $data) {

            $time_hook = self::convertTimeToHook($data['parsed_time']);
            $cron_hook = "seoaic_auto_publish_drafts_{$data['day']}_{$time_hook}";
            $timestamp = wp_next_scheduled($cron_hook, [$data['posts']]);

            if ($timestamp) {
                wp_unschedule_event($timestamp, $cron_hook, [$data['posts']]);
            }

            $set_time = self::valid_time($data['day'], $data['parsed_time']);

            $scheduled = wp_schedule_event($set_time, 'weekly', $cron_hook, [$data['posts']]);
            if (!$scheduled) {
                $SEOAIC->posts->debugLog("Failed to schedule event! {$cron_hook}");
                error_log("Failed to schedule event! {$cron_hook}");
            }
        }
    }

    public static function get_drafts_args($posts_count)
    {
        global $wpdb;

        $posts_count = max(0, $posts_count);
        $limit_sql = $posts_count > 0 ? "LIMIT %d" : "";

        $query = "
        SELECT p.ID, p.post_title, p.post_status, p.post_date
        FROM {$wpdb->posts} AS p
        INNER JOIN {$wpdb->postmeta} AS pm ON p.ID = pm.post_id
        WHERE pm.meta_key = 'seoaic_auto_scheduled'
        AND pm.meta_value = '1'
        AND p.post_status != 'trash'
        ORDER BY p.post_date DESC
        $limit_sql
    ";

        $sql = $posts_count > 0 ? $wpdb->prepare($query, $posts_count) : $query;

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

        return is_array($results) ? $results : [];
    }

    private static function publish_drafts($count)
    {
        $drafts = self::get_drafts_args($count);
        foreach ($drafts as $post) {

            if (empty($post->ID)) {
                continue;
            }

            $current_time = current_time('mysql');

            $updated = wp_update_post([
                'ID' => $post->ID,
                'post_status' => 'publish',
                'post_date' => $current_time,
                'post_date_gmt' => get_gmt_from_date($current_time),
                'edit_date' => true,
            ], true);

            delete_post_meta($post->ID, 'seoaic_auto_scheduled');

            if (is_wp_error($updated)) {
                error_log("post publication error ID {$post->ID}: " . $updated->get_error_message());
            }
        }
    }

    public function drafts_queue($return = false)
    {
        check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);

        $drafts = self::get_drafts_args(-1);

        $html = '<ul id="seoaic_sortable_drafts" class="seoaic-space-between-vertical-12px">';

        foreach ($drafts as $post) {

            if (empty($post->ID)) {
                continue;
            }

            $html .= "<li data-id='{$post->ID}' class='d-flex ai-start'><span class='seoaic_pre_title_id'>ID:{$post->ID}</span><span class='seoaic-mr-20 seoai-grab-cursor ml-10'>{$post->post_title}</span><a href='" . get_edit_post_link($post->ID) . "' target='_blank' class='seoai-border-0 seoai-color-white seoai-bg-black ml-auto seoaic-button-small position-relative'>" . esc_html__('open in editor', 'seoaic') . "</a></li>";

        }

        $html .= '</ul>';

        $content = '<div class="seoaic-scroll-vertical">' . $html . '</div>';

        if ($return) {
            return $content;
        }

        wp_send_json($content);
    }

    private function get_post_date(int $post_id): ?string
    {
        global $wpdb;

        if (!$wpdb) {
            return null;
        }

        $query = $wpdb->prepare(
            "SELECT post_date FROM {$wpdb->posts} WHERE ID = %d",
            esc_sql($post_id)
        );

        return $wpdb->get_var($query) ?: null;
    }

    private function update_post_date(int $post_id, ?int $prev_id, ?int $next_id): void
    {
        global $wpdb;

        if (!$post_id) {
            return;
        }

        $prev_date = $prev_id ? strtotime($this->get_post_date($prev_id)) : null;
        $next_date = $next_id ? strtotime($this->get_post_date($next_id)) : null;

        if ($prev_date !== null && $next_date !== null) {
            $new_timestamp = ($prev_date + $next_date) / 2;
        } elseif ($prev_date !== null) {
            $new_timestamp = $prev_date - 5;
        } elseif ($next_date !== null) {
            $new_timestamp = $next_date + 5;
        } else {
            $new_timestamp = time();
        }

        $new_date = date('Y-m-d H:i:s', $new_timestamp);
        $gmt_date = get_gmt_from_date($new_date);

        $updated = $wpdb->update(
            $wpdb->posts,
            ['post_date' => $new_date, 'post_date_gmt' => $gmt_date],
            ['ID' => $post_id],
            ['%s', '%s'],
            ['%d']
        );

        if ($updated === false) {
            error_log("Failed to update post {$post_id}");
        }
    }

    public function sort_auto_scheduled_drafts(): void
    {
        check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);

        $input = filter_input_array(INPUT_POST, [
            'dragged_id' => FILTER_VALIDATE_INT,
            'prev_id' => FILTER_VALIDATE_INT,
            'next_id' => FILTER_VALIDATE_INT,
        ]);

        if (!isset($input['dragged_id']) || (!$input['prev_id'] && !$input['next_id'])) {
            return;
        }

        $this->update_post_date($input['dragged_id'], $input['prev_id'], $input['next_id']);

        wp_send_json_success([
            'prev_id' => $input['prev_id'] ? $this->get_post_date($input['prev_id']) : null,
            'dragged_id' => $this->get_post_date($input['dragged_id']),
            'next_id' => $input['next_id'] ? $this->get_post_date($input['next_id']) : null,
        ]);
    }

    private static function time_stamp_to_utc($timestamp)
    {
        $datetime = new DateTime();
        $datetime->setTimestamp($timestamp);
        $datetime->setTimezone(new DateTimeZone('UTC'));
        return $datetime->format('Y-m-d\TH:i:s\Z');
    }

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

        if (empty($post['option_key']) || !isset($post['text'])) {
            return;
        }

        $option_key = sanitize_key($post['option_key']);
        $value      = $post['text'];

        global $SEOAIC_OPTIONS;

        switch ($option_key) {
            case 'seoaic_business_description':
                $content = wp_kses_post($value);
                break;

            case 'seoaic_target_audience':
            case 'seoaic_services':
                if (is_array($value)) {
                    $content = array_map(function($item) {
                        return [
                            'name' => isset($item['name']) ? sanitize_text_field($item['name']) : '',
                            'text' => isset($item['text']) ? wp_kses_post($item['text']) : '',
                        ];
                    }, $value);
                } else {
                    $content = [];
                }
                break;

            default:
                return;
        }

        $SEOAIC_OPTIONS[$option_key] = $content;
        update_option('seoaic_options', $SEOAIC_OPTIONS);

        wp_send_json_success([
            'text' => $content
        ]);
    }

    public function seoaic_update_industry() {
        $post = wp_unslash($_POST);
        if (!isset($post['industry'])) {
            return;
        }
        $industry = wp_kses_post($post['industry']);
        global $SEOAIC_OPTIONS;
        $SEOAIC_OPTIONS['seoaic_industry'] = $industry;
        update_option('seoaic_options', $SEOAIC_OPTIONS);
        wp_send_json_success([
            'new_industry' => $industry
        ]);
    }

    private static function get_cron_slots($cron_jobs)
    {
        $cron_slots = [];
        foreach ($cron_jobs as $timestamp => $hooks) {
            foreach ($hooks as $hook => $details) {
                if (strpos($hook, 'seoaic_auto_publish_drafts_') === 0) {
                    foreach ($details as $detail) {
                        if (!empty($detail['args'][0]) && is_numeric($detail['args'][0])) {
                            $cron_slots[] = [
                                'timestamp' => $timestamp,
                                'count' => (int) $detail['args'][0]
                            ];
                        }
                    }
                }
            }
        }
        return $cron_slots;
    }

    private static function assign_posts_to_cron_slots($posts_array, &$cron_slots)
    {
        $scheduled_posts = [];
        $post_index = 0;
        $total_posts = count($posts_array);
        $slot_index = 0;

        while ($post_index < $total_posts) {
            $slot = &$cron_slots[$slot_index];
            $timestamp = $slot['timestamp'];

            for ($i = 0; $i < $slot['count'] && $post_index < $total_posts; $i++, $post_index++) {
                $scheduled_posts[] = self::format_auto_scheduled_post($posts_array[$post_index], $timestamp);
            }

            $slot['timestamp'] += WEEK_IN_SECONDS;
            $slot_index = ($slot_index + 1) % count($cron_slots);
        }

        return $scheduled_posts;
    }

    private static function format_auto_scheduled_post($post, $timestamp)
    {
        $date = self::time_stamp_to_utc($timestamp);
        $end_date = date('Y-m-d\TH:i:s\Z', strtotime($date) + 60);

        return is_object($post) ? [
            'title' => $post->post_title ?? 'Untitled',
            'start' => $date,
            'end' => $end_date,
            'category' => 'AI in SEO',
            'id' => intval($post->ID) ?? 0,
            'allDay' => false,
            'draggable' => false,
            'auto_scheduled'=> true,
            'status'=> 'future'
        ] : [];
    }

    public static function get_auto_scheduled_posts()
    {
        $scheduled_posts = [];
        $cron_jobs = _get_cron_array();
        $posts_array = self::get_drafts_args(-1);

        if (!$cron_jobs || empty($posts_array)) {
            return $scheduled_posts;
        }

        $cron_slots = self::get_cron_slots($cron_jobs);

        if (empty($cron_slots)) {
            return $scheduled_posts;
        }

        return self::assign_posts_to_cron_slots($posts_array, $cron_slots);
    }
    // AUTO SCHEDULER END

    public static function getCompanyServices(): array
    {
        global $SEOAIC_OPTIONS;

        $services = !empty($SEOAIC_OPTIONS['seoaic_services']) ? $SEOAIC_OPTIONS['seoaic_services'] : [];

        return $services;
    }

    public static function getTargetAudience(): array
    {
        global $SEOAIC_OPTIONS;

        $targetAudiences = !empty($SEOAIC_OPTIONS['seoaic_target_audience']) ? $SEOAIC_OPTIONS['seoaic_target_audience'] : [];

        return $targetAudiences;
    }

    public function initCustomPostType()
    {
        if (self::isCPTEnabled()) {
            $labels = array(
                'name'                  => _x('SEO AI Posts', 'Post type general name', 'seoaic'),
                'singular_name'         => _x('SEO AI Post', 'Post type singular name', 'seoaic'),
                'menu_name'             => _x('SEO AI Posts', 'Admin Menu text', 'seoaic'),
                'name_admin_bar'        => _x('SEO AI Post', 'Add New on Toolbar', 'seoaic'),
                'add_new'               => __('Add New', 'seoaic'),
                'add_new_item'          => __('Add New', 'seoaic'),
                'new_item'              => __('New SEO AI Post', 'seoaic'),
                'edit_item'             => __('Edit SEO AI Post', 'seoaic'),
                'view_item'             => __('View SEO AI Post', 'seoaic'),
                'all_items'             => __('All SEO AI Posts', 'seoaic'),
                'search_items'          => __('Search', 'seoaic'),
                'parent_item_colon'     => __('Parent:', 'seoaic'),
                'not_found'             => __('No SEO AI Posts found.', 'seoaic'),
                'not_found_in_trash'    => __('No SEO AI Posts found in Trash.', 'seoaic'),
            );
            $args = array(
                'labels'             => $labels,
                'description'        => 'SEO AI custom post type.',
                'public'             => true,
                'publicly_queryable' => true,
                'show_ui'            => true,
                'show_in_menu'       => true,
                'query_var'          => true,
                'rewrite'            => [
                    'slug'          => self::getCPTSlug(),
                    'with_front'    => false,
                ],
                'capability_type'    => 'post',
                'has_archive'        => true,
                'hierarchical'       => false,
                'menu_position'      => 20,
                'menu_icon'         => 'dashicons-media-text',
                'supports'           => [
                    'title',
                    'editor',
                    'author',
                    'thumbnail',
                    'excerpt',
                    'revisions',
                ],
                'taxonomies'         => [
                    'category',
                    'post_tag',
                ],
                'show_in_rest'       => true,
            );

            register_post_type(self::SEOAI_POST, $args);
            // Flush rewrite rules to ensure the new structure takes effect
            add_action('init', 'flush_rewrite_rules', 999);
        }
    }

    private static function getCPTSettings()
    {
        global $SEOAIC_OPTIONS;

        return !empty($SEOAIC_OPTIONS['cpt']) ? $SEOAIC_OPTIONS['cpt'] : [];
    }

    public static function getCustomPostTypeSettings()
    {
        $return = [
            'enabled'   => self::isCPTEnabled(),
            'slug'      => self::getCPTSlug(),
            'custom_template' => self::isCustomTemplateEnabled(),
        ];

        return $return;
    }

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

        $__POST = wp_unslash($_POST);

        $__POST = array_filter($__POST, function($key) {
            $allowedFields = [
                'seoaic_custom_template_header_id',
                'seoaic_custom_template_footer_id',
                'seoaic_custom_template_content',
                'seoaic_custom_template_css',
            ];

            return in_array($key, $allowedFields);
        }, ARRAY_FILTER_USE_KEY);

        $this->saveCustomTemplateSettings($__POST);
    }

    public static function saveCustomTemplateSettings($arr)
    {
        $templateSettings = [
            'headerId'  => !empty($arr['seoaic_custom_template_header_id']) ? strip_tags($arr['seoaic_custom_template_header_id']) : '',
            'footerId'  => !empty($arr['seoaic_custom_template_footer_id']) ? strip_tags($arr['seoaic_custom_template_footer_id']) : '',
            'content'   => !empty($arr['seoaic_custom_template_content']) ? trim($arr['seoaic_custom_template_content']) : '',
            'css'       => !empty($arr['seoaic_custom_template_css']) ? trim(strip_tags($arr['seoaic_custom_template_css'])) : '',
        ];

        self::save('template', $templateSettings);
    }

    private static function getCustomTemplateSettings()
    {
        global $SEOAIC_OPTIONS;
        global $SEOAIC;

        $savedSettings = !empty($SEOAIC_OPTIONS['template']) ? $SEOAIC_OPTIONS['template'] : [];

        return [
            'headerId'  => !empty($savedSettings['headerId']) ? $savedSettings['headerId'] : '',
            'footerId'  => !empty($savedSettings['footerId']) ? $savedSettings['footerId'] : '',
            'content'   => isset($savedSettings['content']) ? $savedSettings['content'] : $SEOAIC->custom_template->getDefaultContent(),
            'css'       => isset($savedSettings['css']) ? $savedSettings['css'] : $SEOAIC->custom_template->getDefaultCSS(),
        ];
    }

    public static function getCustomTemplateHeaderId()
    {
        return self::getCustomTemplateSettings()['headerId'];
    }

    public static function getCustomTemplateFooterId()
    {
        return self::getCustomTemplateSettings()['footerId'];
    }

    public static function getCustomTemplateContent()
    {
        return self::getCustomTemplateSettings()['content'];
    }

    public static function getCustomTemplateCSS()
    {
        return strip_tags(self::getCustomTemplateSettings()['css']);
    }

    public static function saveCustomPostTypeSettings($arr)
    {
        $cptSettings = [
            'enabled'   => !empty($arr['seoaic_cpt_enabled']) ? $arr['seoaic_cpt_enabled'] : 'off',
            'slug'      => !empty($arr['seoaic_cpt_slug']) ? $arr['seoaic_cpt_slug'] : 'seoai-posts',
            'custom_template' => !empty($arr['seoaic_custom_template']) ? $arr['seoaic_custom_template'] : 'off',
        ];

        flush_rewrite_rules();

        self::save('cpt', $cptSettings);
    }

    public static function isCPTEnabled(): bool
    {
        $cptSettings = self::getCPTSettings();

        return !empty($cptSettings) && !empty($cptSettings['enabled']) ? 'on' == $cptSettings['enabled'] : false;
    }

    public static function getCPTSlug(): string
    {
        $cptSettings = self::getCPTSettings();

        return !empty($cptSettings) && !empty($cptSettings['slug']) ? $cptSettings['slug'] : 'seoai-posts';
    }

    public static function isCustomTemplateEnabled(): bool
    {
        $cptSettings = self::getCPTSettings();

        return !empty($cptSettings) && !empty($cptSettings['custom_template']) ? 'on' == $cptSettings['custom_template'] : false;
    }
}
