<?php

namespace SEOAIC;

use SEOAIC\DB\KeywordsPostsTable;
use SEOAIC\last_used_prompts\IdeasGenerateLastUsedPrompts;
use SEOAIC\relations\KeywordsPostsRelation;
use SEOAIC_FRAMES;
use SeoaicAjaxValidation;

class SEOAIC_IDEAS
{
    public const IDEA_TYPE = 'seoaic-post';
    public const IDEA_STATUS = 'seoaic-idea';
    private $seoaic;
    private $generatedIdeasIDs;

    function __construct ( $_seoaic )
    {
        $this->seoaic = $_seoaic;
        $this->generatedIdeasIDs = [];

        add_action('wp_ajax_seoaic_add_idea', [$this, 'add_idea']);
        add_action('wp_ajax_seoaic_edit_idea', [$this, 'edit_idea']);
        add_action('wp_ajax_seoaic_remove_idea', [$this, 'remove_idea']);
        add_action('wp_ajax_seoaic_get_idea_content', [$this, 'getIdeaContentAjax']);
        add_action('wp_ajax_seoaic_save_content_idea', [$this, 'save_content_idea']);
        add_action('wp_ajax_seoaic_remove_idea_posting_date', [$this, 'remove_idea_posting_date']);
        add_action('wp_ajax_seoaic_generate_ideas', [$this, 'generateAjax'], 2);
        add_action('wp_ajax_seoaic_generate_ideas_new_keywords', [$this, 'generateIdeasNewKeywords'], 2);
        // add_action('wp_ajax_seoaic_get_blog_settings', [$this, 'blog_idea_settings'], 2);
        // add_action('wp_ajax_nopriv_seoaic_get_blog_settings', [$this, 'blog_idea_settings'], 2);
        add_action('wp_ajax_seoaic_Update_credits_real_time', [$this, 'Update_credits_real_time'], 2);
        add_action('wp_ajax_seoaic_improve_ideas', [$this, 'improveIdeasAjax'], 2);
    }

    /**
     * Checks if provided entity is Idea
     * @param object|array @entity Post
     * @return bool
     */
    public static function isIdea($entity): bool
    {
        if (is_array($entity)) {
            return !empty($entity['post_type'])
                && self::IDEA_TYPE == $entity['post_type']
                && !empty($entity['post_status'])
                && self::IDEA_STATUS == $entity['post_status'];
        }

        return !empty($entity->post_type)
            && self::IDEA_TYPE == $entity->post_type
            && !empty($entity->post_status)
            && self::IDEA_STATUS == $entity->post_status;
    }

    /**
     * Get Ideas by ids.
     * @param array $ids Array of IDs
     * @return WP_Post[] array of ideas in WP_Post format
     */
    public function getIdeas(array $ids)
    {
        $ideas = get_posts([
            'post__in'      => $ids,
            'post_type'     => self::IDEA_TYPE,
            'post_status'   => self::IDEA_STATUS,
            'lang'          => '',
            'numberposts'   => -1,
        ]);

        return $ideas;
    }

    /**
     * Update Idea fields (WP_Post)
     * @param int $id Idea ID
     * @param array Array of fields to update (WP_Post fields) in "key => value" format
     * @return bool
     */
    public function updateIdea(int $id, array $data = []): bool
    {
        $updData = array_merge([
            'ID' => $id,
        ], $data);

        $result = wp_update_post($updData);

        return (bool)$result;
    }

    /**
     * Ajax action - add idea
     */
    public function add_idea($args = [])
    {
        check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);

        $__REQUEST = wp_unslash($_REQUEST);
        $defaults = [
            'name'      => $__REQUEST['item_name'] ?? '',
            'idea_type' => !empty($__REQUEST['idea_template_type']) ? stripslashes(sanitize_text_field($__REQUEST['idea_template_type'])) : 'default',
            'language'  => $this->seoaic->multilang->filter_request_multilang(),
            'post_type' => 'seoaic-post',
            'parent_id' => $__REQUEST['seoaic-multilanguage-parent-id'] ?? 0,
            'return'    => false,
            'multi'     => true,
        ];

        $parsed_args = wp_parse_args($args, $defaults);

        if (empty($parsed_args['name'])) {
            if ($parsed_args['return']) {
                wp_die();
            }

            SEOAICAjaxResponse::alert(esc_html__("Empty Name field.", "seoaic"))->wpSend();
        }

        $title = stripslashes(sanitize_textarea_field($parsed_args['name']));

        $title = explode("\n", $title);
        $message = '';

        foreach ($title as $_title) {
            $id = wp_insert_post([
                'post_title'    => $_title,
                'post_type'     => self::IDEA_TYPE,
                'post_status'   => self::IDEA_STATUS,
            ]);

            if (!empty($parsed_args['parent_id'])) {
                $data['_idea_type'] = get_post_meta($parsed_args['parent_id'], '_idea_type', true);
            } else {
                $data['_idea_type'] = $defaults['idea_type'];
            }

            if ($this->seoaic->multilang->is_multilang()) {
                $languageArgs = $this->seoaic->multilang->get_language_by($parsed_args['language']);
                $locationCode = $this->getLanguageLocations($parsed_args['language']);
                $data['_idea_language_location_code'] = $locationCode[$languageArgs['code']];
            }

            $selectedKeywordsIDs = !empty($__REQUEST['select-keywords']) ? $__REQUEST['select-keywords'] : [];

            if (!empty($selectedKeywordsIDs)) {
                $keywords = $this->seoaic->keywords->getKeywordsByIDs($selectedKeywordsIDs);
                $selectedKeywordsNames = array_column($keywords, 'name');

                if (!empty($selectedKeywordsNames)) {
                    $ideaContent = [
                        'idea_keywords' => $selectedKeywordsNames,
                    ];
                    $data['seoaic_idea_content'] = json_encode($ideaContent, JSON_UNESCAPED_UNICODE);
                    $data['_idea_keywords_data'] = $selectedKeywordsNames;
                }

                $this->setRelation(intval($id), $selectedKeywordsIDs, $selectedKeywordsNames);
            }

            if (!empty($__REQUEST['internal_links'])) {
                $data['seoaic_internal_links'] = $__REQUEST['internal_links'];
            }

            if (!empty($__REQUEST['pillar_links'])) {
                $data['seoaic_pillar_links'] = $__REQUEST['pillar_links'];
            }

            $this->updateIdeaData($id, $data);

            $this->seoaic->multilang->add_new_idea_manually($id, $parsed_args);

            if ($parsed_args['return']) {
                return $id;
            }

            $message .= '<p>' . esc_html__('Idea has been added', 'seoaic') . ': <b>#' . esc_html($id) . '</b> <span class="gray">«' . esc_html($_title) . '»</span></p>';
        }

        SEOAICAjaxResponse::alert($message)->wpSend();
    }

    public function setRelation(int $ideaId, array $keywordsIds, array $keywordsNames): void
    {
        if (
            empty($keywordsIds)
            || empty($keywordsNames)
        ) {
            return;
        }

        $keywords = $keywordsIds ? $this->seoaic->keywords->getKeywordsByIDs($keywordsIds) : [];
        $filteredKeywords = array_filter($keywords, function($keyword) use ($keywordsNames) {
            return in_array($keyword['name'], $keywordsNames);
        });

        if (!empty($filteredKeywords)) {
            $ideaKeywordsIDs = array_column($filteredKeywords, 'id');

            KeywordsPostsRelation::setRelations($ideaKeywordsIDs, $ideaId);
        }
    }

    /**
     * Ajax action - edit (update) idea
     */
    public function edit_idea($args = [])
    {
        check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);

        $defaults = [
            'id'        => $_REQUEST['item_id'] ?? 0,
            'name'      => $_REQUEST['item_name'] ?? '',
            'language'  => $_REQUEST['seoaic_ml_language'] ?? '',
            'post_type' => 'seoaic-post',
            'parent_id' => $_REQUEST['seoaic-multilanguage-parent-id'] ?? 0,
            'return'    => false,
            'multi'     => true,
        ];

        $parsed_args = wp_parse_args( $args, $defaults );


        if (empty($parsed_args['name']) || empty($parsed_args['id'])) {
            wp_die();
        }

        $title = stripslashes(sanitize_text_field($parsed_args['name']));
        $id = intval($parsed_args['id']);

        wp_update_post([
            'post_title' => $title,
            'post_name'  => '',
            'ID' => $id,
        ]);

        $this->seoaic->multilang->add_new_idea_manually($id, $parsed_args);

        SEOAICAjaxResponse::success('Idea #' . esc_html($id) . ' updated!')->addFields([
            'id' => $id,
            'content' => [
                'id' => $id,
                'title' => $title,
            ],
        ])->wpSend();
    }

    /**
     * Ajax action - remove idea
     */
    public function remove_idea()
    {
        check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);

        if (
            empty($_REQUEST['item_id'])
            && empty($_REQUEST['item_ids'])
            && empty($_REQUEST['idea-mass-create'])
        ) {
            SEOAICAjaxResponse::error(esc_html__('No ideas selected', 'seoaic'))->wpSend();
        }

        if ($_REQUEST['item_id'] === 'all') {
            $this->removeAllIdeas();
        }

        if (!empty($_REQUEST['item_id'])) {
            $ids = [$_REQUEST['item_id']];

        } elseif (!empty($_REQUEST['item_ids'])) {
            $ids = explode(',', $_REQUEST['item_ids']);

        } else {
            $ids = is_array($_REQUEST['idea-mass-create']) ? $_REQUEST['idea-mass-create'] : [$_REQUEST['idea-mass-create']];
        }
        $message = '';
        $removed_ids = [];

        foreach ($ids as $id) {
            $id = intval($id);
            $isIdea = get_post_type($id) === 'seoaic-post';

            if (!$isIdea) {
                $message .= '<p>Idea <b>#' . esc_html($id) . '</b> not exists!</p>';
            } else {
                $title = get_the_title($id);
                $deleteResult = wp_delete_post($id, true);

                if ($deleteResult) {
                    KeywordsPostsRelation::deleteByPostID($id);
                }
                $removed_ids[] = $id;
                $message .= '<p>Idea <b>#' . esc_html($id) . '</b> <span class="gray">«' . esc_html($title) . '»</span> removed!</p>';
            }
        }

        SEOAICAjaxResponse::success($message)->addFields([
            'id' => $id,
            'content' => [
                'item_type' => 'idea',
                'removed_ids' => $removed_ids,
            ],
        ])->wpSend();
    }

    /**
     * Ajax action - remove all ideas
     */
    public function removeAllIdeas()
    {
        check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);

        $args = [
            'numberposts' => -1,
            'post_type' => 'seoaic-post',
            'post_status' => 'seoaic-idea',
        ];
        $schedule_too = false;

        if (!empty($_REQUEST['schedule_too']) && $_REQUEST['schedule_too'] === '1') {
            $schedule_too = true;
        }

        $ideas = get_posts($args);

        foreach ($ideas as $idea) {
            if (!$schedule_too) {
                $post_date = get_post_meta($idea->ID, 'seoaic_idea_postdate', true);
                if (!empty($post_date)) {
                    continue;
                }
            }

            $deleteResult = wp_delete_post($idea->ID, true);

            if ($deleteResult) {
                KeywordsPostsRelation::deleteByPostID($idea->ID);
            }
        }

        SEOAICAjaxResponse::alert('All ideas have been removed!')->wpSend();
    }

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

        if (empty($_REQUEST['item_id'])) {
            wp_die();
        }

        $id = intval($_REQUEST['item_id']);

        $idea_content = get_post_meta($id, 'seoaic_idea_content', true);
        if (!empty($idea_content)) {
            $idea_content = json_decode($idea_content, true);
        } else {
            $idea_content = [];
        }

        $idea_categories = !empty($idea_content['idea_post_type']) ? seoaic_get_categories($idea_content['idea_post_type'], $id) : seoaic_get_categories(SEOAIC_SETTINGS::getSEOAICPostType());

        if (
            $this->seoaic->multilang->is_multilang()
            && empty($idea_content['idea_language'])
        ) {
            $idea_content['idea_language'] = $this->seoaic->multilang->get_post_language($id, 'locale');
        }

        if (!empty($idea_content['idea_keywords'])) {
            foreach ($idea_content['idea_keywords'] as &$keyword) {
                $keyword = [
                    'id' => '',
                    'name' => $this->fix_umlauts_characters($keyword),
                ];
            }
        }

        if (!empty($idea_content['idea_skeleton'])) {
            $idea_content['idea_skeleton'] = SEOAIC_FRAMES::formatWithOutlines($idea_content['idea_skeleton']);
        }

        SEOAICAjaxResponse::success()->addFields([
            'content' => [
                'id'            => $id,
                'idea_name'     => get_the_title($id),
                'idea_content'  => $idea_content,
                'idea_postdate' => str_replace([' ', ':00'], ['T', ''], get_post_meta($id, 'seoaic_idea_postdate', true)),
                'idea_categories' => $idea_categories
            ]
        ])->setFlags(JSON_UNESCAPED_UNICODE)->wpSend();
    }

    //TODO temporary solution
    public function fix_umlauts_characters($string) {
        $replacements = [
            'u00e4' => 'ä',
            'u00c4' => 'Ä',
            'u00f6' => 'ö',
            'u00c6' => 'Æ',
            'u00e9' => 'é',
            'u00c9' => 'É',
            'u00fc' => 'ü',
            'u00c0' => 'À',
            'u00e0' => 'à',
            'u00f1' => 'ñ',
            'u00d1' => 'Ñ',
        ];

        foreach ($replacements as $code => $char) {
            $string = str_replace("{$code}", $char, $string);
        }

        return $string;
    }

    /**
     * Ajax action - save idea content
     */
    public function save_content_idea()
    {
        check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);

        $__REQUEST = wp_unslash($_REQUEST);

        if (empty($__REQUEST['id'])) {
            SEOAICAjaxResponse::error(esc_html__('Empty data!', 'seoaic'))->wpSend();
        }

        $id = intval($__REQUEST['id']);

        if (!empty($__REQUEST['idea_post_date'])) {
            $ideaPostdate = str_replace('T', ' ', sanitize_text_field($__REQUEST['idea_post_date'])) . ':00';

            if ($ideaPostdate < date('Y-m-d H:i:s')) {
                SEOAICAjaxResponse::error(esc_html__('It can`t be the past date!', 'seoaic'))->wpSend();
            }

        } else {
            $ideaPostdate = NULL;
        }

        if (isset($__REQUEST['idea_content'])) {
            $ideaContent = sanitize_text_field($__REQUEST['idea_content']);
            $ideaKeywordsIds = !empty($__REQUEST['idea_keywords_ids']) ? array_unique($__REQUEST['idea_keywords_ids']) : [];
            $ideaContentArray = json_decode(stripslashes($ideaContent), true);

            if ($this->seoaic->multilang->is_multilang()) {
                if (empty($ideaContentArray['idea_language'])) {
                    SEOAICAjaxResponse::alert(esc_html__('Please select language', 'seoaic'))->wpSend();

                } else {
                    //TODO: check add_new_ideas_generation
                    // $this->seoaic->multilang->set_post_language($id, $ideaContentArray['idea_language']);
                    $language = $this->seoaic->multilang->get_language_by($ideaContentArray['idea_language'], 'locale');
                    $this->seoaic->multilang->setPostLanguage($id, [
                        'language'  => $language['name'],
                        'post_type' => 'seoaic-post',
                    ], true);
                }
            }

            if (
                !isset($ideaContentArray['idea_keywords'])
                || empty($ideaContentArray['idea_keywords'])
            ) {
                KeywordsPostsRelation::deleteByPostID($id);

            } else {
                if (!empty($ideaKeywordsIds)) {
                    KeywordsPostsRelation::setRelations($ideaKeywordsIds, $id);
                }
            }

            update_post_meta($id, 'seoaic_idea_content', $ideaContent);
        }

        $this->update_ideas_post_date($id, $ideaPostdate);
        ob_start();
        $this->seoaic->multilang->get_language_translations_control($id, []);
        $html = ob_get_clean();

        SEOAICAjaxResponse::alert(esc_html__('Idea content saved!', 'seoaic'))->addFields([
            'content' => [
                'idea_id'    => $id,
                'idea_icons' => $this->get_idea_icons($id),
                'langauages_html' => $html,
            ]
        ])->wpSend();
    }

    /**
     * Ajax action - remove idea posting date
     */
    public function remove_idea_posting_date()
    {
        check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);

        if (empty($_REQUEST['id'])) {
            wp_send_json([
                'status' => 'error',
                'message' => 'Empty data!',
            ]);
        }

        $id = intval($_REQUEST['id']);

        $this->update_ideas_post_date($id, NULL);

        echo 'success';
        wp_die();
    }

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

        $this->generate();
    }

    /**
     * Get ideas (can be used in ajax call)
     *
     * @param bool $return
     * @param int $n
     */
    public function generate($return = false, $n = 10, $prompt = '', $competitor_keywords = '')
    {
//        error_reporting(E_ALL);
//        ini_set('display_errors', '1');

        global $SEOAIC_OPTIONS;

        if (!empty($_REQUEST['ideas_count'])) {
            $n = intval($_REQUEST['ideas_count']);
        }

        $idea_prompt = !empty($_REQUEST['idea_prompt']) ? stripslashes(sanitize_text_field($_REQUEST['idea_prompt'])) : '';

        if($prompt) {
            $idea_prompt = $prompt;
        }

        $serviceName = '';
        $serviceText = '';

        if ( !empty($SEOAIC_OPTIONS['seoaic_services']) && isset($_REQUEST['select_service']) && $_REQUEST['select_service'] !== '' ) {
            $serviceName = $SEOAIC_OPTIONS['seoaic_services'][(int)$_REQUEST['select_service']]['name'];
            $serviceText = $SEOAIC_OPTIONS['seoaic_services'][(int)$_REQUEST['select_service']]['text'];
        }

        $language = $this->seoaic->multilang->filter_request_multilang();

        if (isset($_REQUEST['search_terms_page'])) {
            $keywords = '';
            $search_terms = !empty($_REQUEST['selected_keywords']) ? implode(', ', $_REQUEST['selected_keywords']) : '';
        } else {
            $search_terms = '';
            $keywords = !empty($_REQUEST['selected_keywords']) ? implode(', ', $_REQUEST['selected_keywords']) : '';
        }

        if($competitor_keywords) {
            $keywords = $competitor_keywords;
        }

        $data = [
            'title' => !empty($SEOAIC_OPTIONS['seoaic_business_name']) ? $SEOAIC_OPTIONS['seoaic_business_name'] : get_option('blogname', true),
            'description' => get_option('blogdescription', true),
            'language' => $language,
            'idea_type' => !empty($_REQUEST['idea_template_type']) ? stripslashes(sanitize_text_field($_REQUEST['idea_template_type'])) : 'default',
            'content' => '',
            'prompt' => $idea_prompt,
            'company' => !empty($SEOAIC_OPTIONS['seoaic_business_name']) ? $SEOAIC_OPTIONS['seoaic_business_name'] : get_option('blogname', true),
            'industry' => !empty($SEOAIC_OPTIONS['seoaic_industry']) ? $SEOAIC_OPTIONS['seoaic_industry'] : '',
            'company_desc' => !empty($SEOAIC_OPTIONS['seoaic_business_description']) ? $SEOAIC_OPTIONS['seoaic_business_description'] : get_option('blogdescription', true),
            'keywords' => $keywords,
            'search_term' => $search_terms,
            //'service' => !empty($_REQUEST['selected_services']) ? implode(', ', $_REQUEST['selected_services']) : '',
            'service' => !empty($serviceName) ? ($serviceText ? $serviceName . ' (' . $serviceText . ')' : $serviceName ) : '',
            'n' => $n,
        ];

        $first_location = [];

        if ( !empty($_REQUEST['selected_locations']) && is_array($_REQUEST['selected_locations']) ) {
            $first_location = array_shift($_REQUEST['selected_locations']);
            $data['locations'] = $first_location;
        }

        $result = $this->seoaic->curl->init('/api/ai/ideas-formatted', $data, true, false, true);

        $SEOAIC_OPTIONS['seoaic_idea_prompt'] = $idea_prompt;
        update_option('seoaic_options', $SEOAIC_OPTIONS);

        $idea_id = 0;
        //$idea_schedule = intval($_REQUEST['idea_schedule']);
        $idea_schedule = false;
        $date = false;
        //$date = sanitize_text_field($_REQUEST['posting_date']);

        $raw_content = !empty($result['content']) ? $result['content'] : [];
        $content = $this->getIdeasContent($raw_content);
        //$content = [];
        $key = 0;
        $languagesArray = explode(',', $language);

//        foreach ($raw_content as $ideas) {
//            foreach ($ideas as $idea_key => $_title) {
//                $content[] = [
//                    'key' => $idea_key,
//                    'title' => $_title,
//                    'language' => $this->seoaic->multilang->get_language_by($languagesArray[$key]),
//                    'is_default' => ($languagesArray[$key] === $this->seoaic->multilang->get_default_language()),
//                ];
//            }
//
//            $key ++;
//        }

        if (
            !$this->seoaic->multilang->is_multilang()
            && !empty($_REQUEST['selected_locations'])
            && is_array($_REQUEST['selected_locations'])
        ) {
            $base_content = $content;
            foreach ($base_content as $idea) {
                foreach ($_REQUEST['selected_locations'] as $location) {
                    $content[] = [
                        "title" => str_replace($first_location, $location, $idea['title'])
                    ];
                }
            }
        }

        $insert_posts = [];

        // Filter out ideas duplicates from response
        $names = array_column($content, 'title');
        $unique_names = array_unique($names);
        $unique_array = array();
        foreach ($content as $item) {
            if (in_array($item['title'], $unique_names)) {
                $unique_array[] = $item;
                unset($unique_names[array_search($item['title'], $unique_names)]);
            }
        }

        $content = $unique_array;

        foreach ($content as $key => &$idea) {
            if (empty($idea['title'])) {
                break;
            }

            $title = trim($idea['title'], '"');

            $idea_id = wp_insert_post([
              'post_title' => wp_check_invalid_utf8($title),
              'post_type' => 'seoaic-post',
              'post_status' => 'seoaic-idea',
            ]);

            if (empty($idea_id)) {
                continue;
            }

            $idea_ids[] = $idea_id;

            $idea['idea_id'] = $idea_id;
            $this->generatedIdeasIDs[] = $idea_id;
            $languageLocations = $this->getLanguageLocations($language);
            update_post_meta($idea_id, '_idea_prompt_data', $data['prompt']);
            update_post_meta($idea_id, '_idea_type', $data['idea_type']);
            update_post_meta($idea_id, '_idea_keywords_data', explode(',', $data['keywords']));
            update_post_meta($idea_id, '_idea_language_location_code', $languageLocations[$idea['language']['code']]);

            $insert_posts[$idea_id] = $title;

            if (!empty($idea_schedule)) {
                $days = $SEOAIC_OPTIONS['seoaic_schedule_days'];

                if (empty($days)) {
                    continue;
                }

                $days_loop = true;
                $datetime = time();

                while ($days_loop) {
                    $_day = strtolower(date('l', $datetime));
                    $_posts = $days[$_day]['posts'];

                    if (isset($days[$_day])) {
                        $_have_posted_idea = get_posts([
                            'numberposts' => 99,
                            'fields' => 'ids',
                            'post_type' => 'seoaic-post',
                            'post_status' => 'seoaic-idea',
                            'meta_query' => [
                                'relation' => 'OR',
                                [
                                    'key' => 'seoaic_idea_postdate',
                                    'value' => $date,
                                    'compare' => 'LIKE'
                                ]
                            ]
                        ]);

                        if (count($_have_posted_idea) < $_posts) {
                            $this->update_ideas_post_date($idea_id, $date . ' ' . date('H:i:s', strtotime($days[$_day]['time'])));
                            $days_loop = false;
                        } else {
                            $datetime = strtotime($date . ' +1 day');
                            $date = date('Y-m-d', $datetime);
                        }
                    } else {
                        $datetime = strtotime($date . ' +1 day');
                        $date = date('Y-m-d', $datetime);
                    }
                }
            }
        }

        $this->seoaic->multilang->add_new_ideas_generation($content);

        if ($return && !empty($idea_ids)) {
            return $idea_ids;
        }

        $message = '<div class="mb-19">New ideas have been generated:</div>';
        $message .= self::makeIdeasRows($insert_posts);

        wp_send_json([
            'status'  => 'alert',
            'message' => $message,
        ]);
    }

    public function generateIdeasNewKeywords($return = false, $n = 10, $generated_ideas = null, $external_request = null)
    {
        check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);

        global $SEOAIC_OPTIONS;

        if($external_request) {
            $_REQUEST = $external_request;
        }

        $__REQUEST = wp_unslash($_REQUEST);

        if (is_multisite()) {
            KeywordsPostsTable::dropOldIfExists();
        }
        KeywordsPostsTable::createIfNotExists();

        if (!empty($__REQUEST['ideas_count'])) {
            $n = intval($__REQUEST['ideas_count']);
        }

        $idea_prompt = !empty($__REQUEST['idea_prompt']) ? stripslashes(sanitize_text_field($__REQUEST['idea_prompt'])) : '';

        $language = $this->seoaic->multilang->filter_request_multilang();
        $selectedKeywordsIDs = !empty($__REQUEST['select-keywords']) ? $__REQUEST['select-keywords'] : [];
        $keywords = $selectedKeywordsIDs ? $this->seoaic->keywords->getKeywordsByIDs($selectedKeywordsIDs) : [];
        if ($this->seoaic->multilang->is_multilang()) {
            $languageLocations = $this->getLanguageLocations($language);
        }

        $keywordsNamesArray = array_map(function ($item) {
            return $item['name'];
        }, $keywords);

        if (
            (!empty($__REQUEST['keywords_from_competitors']) || !empty($__REQUEST['keywords_from_explorer']))
            && !empty($__REQUEST['selected_keywords'])
        ) {
            $keywordsNamesArray = $__REQUEST['selected_keywords'];
        }

        $data = [
            'title' => SEOAIC_SETTINGS::getBusinessName(),
            'description' => get_option('blogdescription', true),
            'language' => $language,
            'idea_type' => !empty($__REQUEST['idea_template_type']) ? stripslashes(sanitize_text_field($__REQUEST['idea_template_type'])) : 'default',
            'content' => '',
            'prompt' => $idea_prompt,
            'company' => SEOAIC_SETTINGS::getBusinessName(),
            'industry' => SEOAIC_SETTINGS::getIndustry(),
            'company_desc' => SEOAIC_SETTINGS::getBusinessDescription(),
            'keywords' => implode(', ', $keywordsNamesArray),
            'search_term' => '',
            'n' => $n,
        ];

        if(!empty($_POST['seoaic_services'])) {
            $data['service'] = SEOAIC_SETTINGS::getSelectedRepeaterValues('seoaic_services', $_POST['seoaic_services'], true);
        }

        if(!empty($_POST['seoaic_target_audience'])) {
            $data['target_audience'] = SEOAIC_SETTINGS::getSelectedRepeaterValues('seoaic_target_audience', $_POST['seoaic_target_audience'], true);
        }

        $first_location = [];

        if (
            !empty($__REQUEST['selected_locations'])
            && is_array($__REQUEST['selected_locations'])
        ) {
            //$first_location = array_shift($_REQUEST['selected_locations']);
            $data['locations'] = implode(', ', $__REQUEST['selected_locations']);
        }

        $data['generate_keywords_separately'] = !empty($__REQUEST['generate_keywords_separately']);

        if($generated_ideas) {
            $result = $generated_ideas;
        } else {
            $result = $this->seoaic->curl->init('/api/ai/ideas-formatted', $data, true, false, true);
        }

        // $SEOAIC_OPTIONS['seoaic_idea_prompt'] = $idea_prompt;
        // update_option('seoaic_options', $SEOAIC_OPTIONS);
        (new IdeasGenerateLastUsedPrompts())->store($idea_prompt);

        $idea_id = 0;
        //$idea_schedule = intval($__REQUEST['idea_schedule']);
        $idea_schedule = false;
        $date = false;
        //$date = sanitize_text_field($__REQUEST['posting_date']);

        $raw_content = !empty($result['content']) ? $result['content'] : [];
        $content = $this->getIdeasContent($raw_content);

        if (
            !$this->seoaic->multilang->is_multilang()
            && !empty($__REQUEST['selected_locations'])
            && is_array($__REQUEST['selected_locations'])
        ) {
            $base_content = $content;
            foreach ($base_content as $idea) {
                foreach ($__REQUEST['selected_locations'] as $location) {
                    $content[] = [
                        "title" => str_replace($first_location, $location, $idea['title'])
                    ];
                }
            }
        }

        $insert_posts = [];

        // Filter out ideas duplicates from response
        $names = array_column($content, 'title');
        $unique_names = array_unique($names);
        $unique_array = array();
        foreach ($content as $item) {
            if (in_array($item['title'], $unique_names)) {
                $unique_array[] = $item;
                unset($unique_names[array_search($item['title'], $unique_names)]);
            }
        }

        $content = $unique_array;

        $idea_ids = [];
        foreach ($content as $key => &$idea) {
            if (empty($idea['title'])) {
                break;
            }

            $title = trim($idea['title'], '"');

            $idea_id = wp_insert_post([
                'post_title'    => wp_check_invalid_utf8($title),
                'post_type'     => 'seoaic-post',
                'post_status'   => 'seoaic-idea',
            ]);

            if (empty($idea_id)) {
                continue;
            }

            $this->setRelation(intval($idea_id), $selectedKeywordsIDs, $keywordsNamesArray);

            $idea['idea_id'] = $idea_id;
            $insert_posts[$idea_id] = $title;
            $this->generatedIdeasIDs[] = $idea_id;
            $idesKeywordsNames = $idea['keywords'];

            $updateData = [
                '_idea_prompt_data' => $data['prompt'],
                '_idea_type'        => !empty($idea['idea_type']) ? stripslashes(sanitize_text_field(strtolower($idea['idea_type']))) : $data['idea_type'],
                '_idea_keywords_data' => $idea['keywords'],
                'seoaic_idea_content' => wp_json_encode([
                    'idea_keywords' => $idesKeywordsNames,
                ], JSON_UNESCAPED_UNICODE),
            ];
            if (!empty($idea['seoaic_needs_review']) && !empty($idea['posting_date']) && !empty($idea['cluster_name'])) {
                $updateData['seoaic_ob_needs_review'] = 1;
                $updateData['seoaic_ob_posting_date'] = $idea['posting_date'];
                $updateData['seoaic_cluster'] = $idea['cluster_name'];
            }

            if ($this->seoaic->multilang->is_multilang()) {
                if ($generated_ideas) {
                    if (!empty($idea['location_code']) && !empty($idea['language_name'])) {
                        $updateData['_idea_language_name'] = $idea['language_name'];
                        $updateData['_idea_language_location_code'] = $idea['location_code'];
                    }
                } else {
                    $updateData['_idea_language_location_code'] = $languageLocations[$idea['language']['code']];
                    $updateData['_idea_language_name'] = $idea['language']['name'];
                }
            }

            if (!empty($__REQUEST['internal_links'])) {
                $updateData['seoaic_internal_links'] = $__REQUEST['internal_links'];
            }

            if (!empty($__REQUEST['pillar_links'])) {
                $updateData['seoaic_pillar_links'] = $__REQUEST['pillar_links'];
            }

            $this->updateIdeaData($idea_id, $updateData);

            if (!empty($idea_schedule)) {
                $days = $SEOAIC_OPTIONS['seoaic_schedule_days'];

                if (empty($days)) {
                    continue;
                }

                $days_loop = true;
                $datetime = time();

                while ($days_loop) {
                    $_day = strtolower(date('l', $datetime));
                    $_posts = $days[$_day]['posts'];

                    if (isset($days[$_day])) {
                        $_have_posted_idea = get_posts([
                            'numberposts' => 99,
                            'fields' => 'ids',
                            'post_type' => 'seoaic-post',
                            'post_status' => 'seoaic-idea',
                            'meta_query' => [
                                'relation' => 'OR',
                                [
                                    'key' => 'seoaic_idea_postdate',
                                    'value' => $date,
                                    'compare' => 'LIKE'
                                ]
                            ]
                        ]);

                        if (count($_have_posted_idea) < $_posts) {
                            $this->update_ideas_post_date($idea_id, $date . ' ' . date('H:i:s', strtotime($days[$_day]['time'])));
                            $days_loop = false;
                        } else {
                            $datetime = strtotime($date . ' +1 day');
                            $date = date('Y-m-d', $datetime);
                        }
                    } else {
                        $datetime = strtotime($date . ' +1 day');
                        $date = date('Y-m-d', $datetime);
                    }
                }
            }
        }

        $this->seoaic->multilang->add_new_ideas_generation($content);

        if ($generated_ideas) {
            return $this->generatedIdeasIDs;
        }
        if ($return && !empty($idea_id)) {
            return $idea_id;
        }

        $message = '<h3 class="mb-19 mt-0">' . esc_html__("New ideas have been generated:", "seoaic") . '</h3>';
        $message .= self::makeIdeasRows($insert_posts);
        $message .= '<div class="seoaic-generated-ideas-improve-section">
            <button type="button"
                title="' . esc_attr__("Improve non-approved ideas using mass edit function.", "seoaic") . '"
                class="button-primary seoaic-button-primary seoaic-button-primary-hover seoaic-improve-open-fields seoaic-btn-border"
            >' . esc_html__("Improve", "seoaic") . '</button>
            <div class="seoaic-generated-ideas-improve-inputs mt-15 seoaic-popup__field">
                <div class="tc"><span class="seoaic-ideas-improvement-desc">' . esc_html__("Edit these idea titles based on these instructions:", "seoaic"). '</span></div>
                <textarea
                    id="generated_ideas_improvement_prompt"
                    class="seoaic-w-100"
                    required
                ></textarea>
                <div class="text-end">
                    <button type="button"
                        title="' . esc_html__("Improve", "seoaic") . '"
                        class="seoaic-popup-gradient__btn seoaic-popup-gradient-hover__btn seoaic-improve-ideas-button mt-10"
                        data-posts-ids="' . esc_attr(implode(',', array_keys($insert_posts))) . '"
                        data-action="seoaic_improve_ideas"
                        data-form-callback="keywords_popup_remove_ideas"
                    >' . esc_html__("Improve", "seoaic") . '</button>
                </div>
            </div>
        </div>';

        $button = '<div class="additional-button"><div class="position-absolute seoaic-delete-all-ideas-button-wrapper">
            <button title="' . esc_html__("Delete all", "seoaic") . '" type="button"
                class="button button-danger-hover seoaic-delete-all-ideas-button modal-button confirm-modal-button"
                data-posts-ids="' . esc_attr(implode(',', array_keys($insert_posts))) . '"
                data-modal="#seoaic-confirm-modal"
                data-action="seoaic_remove_idea"
                data-content="' . esc_html__("Do you want to remove all these ideas?", "seoaic") . '"
                data-form-callback="keywords_popup_remove_ideas"
            >' . esc_html__("Delete all", "seoaic") . '</button>
        </div>
        <div class="mr-15">
            <button
                title="' . esc_html__("Generate", "seoaic") . '"
                type="button"
                class="button-primary seoaic-button-primary mass-effect-button seoaic-generate-posts-button modal-button confirm-modal-button"
                data-modal="#seoaic-post-mass-creation-modal"
                data-callback-before="before_open_mass_create_in_modal"
                data-create-posts-count="' . esc_attr(count($insert_posts)) . '"
                data-action="seoaic_posts_mass_create"
                data-title="' . esc_html__("Posts creation", "seoaic") . '"
                data-content="' . esc_html__("You will generate posts from following ideas:", "seoaic") . '"
            >
                ' . esc_html__("Generate", "seoaic") . '
                <div class="dn additional-form-items">';

        $button .= self::makeIdeasGenerateButton($insert_posts);
        $button .= '</div>
            </button>
        </div></div>';

        SEOAICAjaxResponse::alert($message)->addFields(['button' => $button])->wpSend();
    }

    private function getLanguageLocations($languages) {
        $languages = explode(',', $languages);
        $codes = [];
        foreach ($languages as $language) {
            $lang = $this->seoaic->multilang->get_language_by($language);
            if (!empty($_REQUEST['seoaic_language_locations-' . $lang['code']])) {
                $codes[$lang['code']] = $_REQUEST['seoaic_language_locations-' . $lang['code']];
            }
        }
        return $codes;
    }

    private function getIdeasContent($ideas) {
        $content = [];

        foreach ($ideas as $idea_key => $idea) {
            $item = [
                'key' => $idea['key'],
                'title' => $idea['title'],
                'language' => $this->seoaic->multilang->get_language_by($idea['language']),
                'is_default' => ($idea['language'] === $this->seoaic->multilang->get_default_language()),
                'keywords' => $idea['keywords'],
            ];

            if (!empty($idea['seoaic_needs_review']) && !empty($idea['posting_date']) && !empty($idea['cluster_name'])) {
                $item['seoaic_needs_review'] = 1;
                $item['posting_date'] = $idea['posting_date'];
                $item['cluster_name'] = $idea['cluster_name'];
            }

            if (!empty($idea['location_code'])) {
                $item['location_code'] = $idea['location_code'];
            }
            if (!empty($idea['language_name'])) {
                $item['language_name'] = $idea['language_name'];
            }

            if (!empty($idea['idea_type'])) {
                $item['idea_type'] = $idea['idea_type'];
            }

            $content[] = $item;
        }

        return $content;
    }

    /**
     * Updates Idea's data (meta fields)
     * @param array|int $idea Idea or ID
     * @param array $data meta fields to update. Assoc array in a "key => value" format
     * @return bool
     */
    public function updateIdeaData($idea, $data = [])
    {
        if (empty($data)) {
            return false;
        }

        if (
            is_numeric($idea)
            && (int) $idea == $idea
        ) {
            $id = $idea;
        } else {
            $id = $idea['id'];
        }

        $updateRes = wp_update_post([
            'ID'            => $id,
            'meta_input'    => $data,
        ]);

        if (is_wp_error($updateRes)) {
            return false;
        }

        return true;
    }

    public function getGeneratedIdeasIDs()
    {
        return $this->generatedIdeasIDs;
    }

    private static function makeIdeasRows($ideas = [])
    {
        ob_start();
        foreach ($ideas as $key => $value) {
            ?>
            <div
                class="mb-5 alert-added-ideas item-row-id-<?php echo esc_attr($key);?>"
            >
                <b class="num-col">#<?php echo esc_html($key);?></b>
                <div class="title-col">
                    <input type="text" name="idea_updated_title" value="<?php echo esc_attr($value);?>" class="seoaic-form-item idea-updated-title">
                    <span class="idea-orig-title"><?php echo esc_html($value);?></span>
                </div>
                <div class="btn1-col">
                    <span class="save idea-btn dashicons dashicons-yes" title="Save" data-action="seoaic_edit_idea" data-post-id="<?php echo esc_attr($key);?>"></span>
                    <span class="edit idea-btn" title="Edit manually"></span>
                </div>
                <div class="btn2-col">
                    <span
                        class="delete idea-btn dashicons dashicons-dismiss  w-100 h-100"
                        title="Delete"
                        data-action="seoaic_remove_idea"
                        data-post-id="<?php echo esc_attr($key);?>"
                    ></span>
                </div>
                <div class="btn3-col">
                    <span
                        class="accept idea-btn dashicons dashicons-unlock position-relative w-100 h-100"
                        title="<?php esc_attr_e("Accept idea. Protected against mass edit.", "seoaic");?>"
                        data-post-id="<?php echo esc_attr($key);?>"
                    ></span>
                    <span
                        class="accepted idea-btn dashicons dashicons-lock position-relative w-100 h-100"
                        title="<?php esc_attr_e("Accepted. Protected against mass edit.", "seoaic");?>"
                        data-post-id="<?php echo esc_attr($key);?>"
                    ></span>
                </div>
            </div>
            <?php
        }
        return ob_get_clean();
    }

    private static function makeIdeasGenerateButton($ideas=[]) {
        ob_start();
        foreach ($ideas as $key => $value) {
            ?>
            <label data-id="label-idea-mass-create-<?php echo esc_attr($key);?>">
                <input type="checkbox" checked="" class="seoaic-form-item" name="idea-mass-create" value="<?php echo esc_attr($key);?>"> <b>#<?php echo esc_html($key);?></b> - <span><?php echo esc_html($value);?></span>
            </label>
            <?php
        }
        return ob_get_clean();
    }

    /**
     * Get idea`s icons
     *
     * @param int $id
     */
    public function get_idea_icons($id = 0)
    {
        if (empty($id)) {
            return '';
        }

        $idea_content = get_post_meta($id, 'seoaic_idea_content', true);
        if (!empty($idea_content)) {
            $idea_content = json_decode($idea_content, true);
        }

        $icons = !empty($idea_content['idea_skeleton']) ? '<span title="Idea`s structure" class="seoaic-idea-icon seoaic-idea-icon-structure"></span>' : '';
        $icons .= !empty($idea_content['idea_keywords']) ? '<span title="Idea`s keywords" class="seoaic-idea-icon seoaic-idea-icon-keywords"></span>' : '';
        $icons .= !empty($idea_content['idea_description']) ? '<span title="Idea`s description" class="seoaic-idea-icon seoaic-idea-icon-description"></span>' : '';
        $icons .= !empty($idea_content['idea_thumbnail']) ? '<span title="Idea`s thumbnail" class="seoaic-idea-icon seoaic-idea-icon-thumbnail"></span>' : '';

        return $icons;
    }

    /**
     * Get idea`s posting date
     *
     * @param int $id idea ID
     *
     * @return string Formatted date string
     */
    public function get_idea_date( $id ) {
        $id = intval( $id );

        if ( $id <= 0 ) {
            return '';
        }

        $raw_date = get_post_meta( $id, 'seoaic_idea_postdate', true );

        if ( empty( $raw_date ) ) {
            return '';
        }

        $timestamp = strtotime( $raw_date );

        if ( ! $timestamp ) {
            return '';
        }

        return date( 'M j, Y, H:i A', $timestamp );
    }


    /**
     * Update ideas post date
     *
     * @param int $idea_id
     * @param string $date
     */
    public function update_ideas_post_date ( $idea_id = 0, $date = '' )
    {
        if (empty($idea_id) || (!empty($date) && strtotime($date) < time())) {
            return false;
        }

        if (NULL === $date) {
            delete_post_meta($idea_id, 'seoaic_idea_postdate');
        } else {
            update_post_meta($idea_id, 'seoaic_idea_postdate', $date);
        }
    }

    /**
     * Give idea setting to SEO AI server
     *
     */
    // public function blog_idea_settings()
    // {
    //     if ( !$this->seoaic->auth->check_api_token($_REQUEST['email'], $_REQUEST['token']) ) {
    //         wp_send_json( [
    //             'status'  => 'Auth error!',
    //         ] );
    //     }

    //     if ( empty($_REQUEST['item_id']) ) {
    //         wp_send_json( [
    //             'status'  => 'Idea error!',
    //         ] );
    //     }

    //     $data = $this->seoaic->posts->generate_post(false, true);
    //     $data['status'] = 'success';

    //     wp_send_json( $data );
    // }

    /**
     * Update credits real time
     *
     */
    public function Update_credits_real_time()
    {
        check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);

        global $SEOAIC_OPTIONS;

        $data = [
            'email' => $SEOAIC_OPTIONS['seoaic_api_email'],
            'domain' => $_SERVER['HTTP_HOST'],
        ];

        $result = $this->seoaic->curl->init('api/companies/credits', $data, true, true, true);

        $this->seoaic->set_api_credits($result);

        SEOAICAjaxResponse::success()->addFields($result)->wpSend();
    }

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

        $__POST = wp_unslash($_POST);
        $ids = !empty($__POST['ids']) ? $__POST['ids'] : [];
        $errMsgs = [];

        if (empty($ids)) {
            SEOAICAjaxResponse::alert(esc_html__('No ideas were sent', 'seoaic'))->wpSend();
        }

        if (empty($__POST['prompt'])) {
            SEOAICAjaxResponse::error(esc_html__('Empty prompt', 'seoaic'))->wpSend();
        }

        $ideas = $this->getIdeas($ids);

        if (empty($ideas)) {
            SEOAICAjaxResponse::error(esc_html__('No ideas found', 'seoaic'))->wpSend();
        }

        $ideasIDs = array_map(function($item) {
            return $item->ID;
        }, $ideas);
        $defaultLanguageName = $this->seoaic->multilang->get_selected_language();
        $data = [
            'prompt'    => $__POST['prompt'],
            'ideas'     => array_map(function ($idea) use ($defaultLanguageName) {
                $ideaLanguageName = get_post_meta($idea->ID, '_idea_language_name', true);

                return [
                    'id'        => $idea->ID,
                    'title'     => $idea->post_title,
                    'language'  => !empty($ideaLanguageName) ? $ideaLanguageName : $defaultLanguageName,
                ];
            }, $ideas),
        ];

        $response = $this->seoaic->curl->initWithReturn('/api/ai/ideas/improve', $data, true);
        $this->seoaic->curl->validateResponse($response);

        if (empty($response['content'])) {
            SEOAICAjaxResponse::error(esc_html__("Processing failed", "seoaic"))->wpSend();
        }

        foreach ($response['content'] as $updIdea) {
            if (in_array($updIdea['id'], $ideasIDs)) {
                $updResult = $this->updateIdea($updIdea['id'], [
                    'post_title' => $updIdea['title'],
                ]);

                if (!$updResult) {
                    $errMsgs[$updIdea['id']] = 'Idea #' . $updIdea['id'] . ' not updated.';
                }
            }
        }

        SEOAICAjaxResponse::success('OK')->addFields([
            'ideas'     => $response['content'],
            'errors'    => $errMsgs,
        ])->wpSend();
    }

    public function updateCategory(int $id, $category): bool
    {
        $ideaContent = get_post_meta($id, 'seoaic_idea_content', true);
        $ideaContent = !empty($ideaContent) ? json_decode($ideaContent, true) : [];

        if (
            !empty($category)
            && (
                empty($ideaContent['idea_category'])
                || $category != $ideaContent['idea_category']
            )
        ) {
            $ideaContent['idea_category'] = $category;
            $data['seoaic_idea_content'] = json_encode($ideaContent, JSON_UNESCAPED_UNICODE);

            $this->updateIdeaData($id, $data);

            return true;
        }

        return false;
    }
}
