<?php

namespace SEOAIC;

use SEOAIC\last_used_prompts\IdeasGenerateLastUsedPrompts;
use SEOAIC\last_used_prompts\KeywordsGenerateLastUsedPrompts;
use SEOAIC\last_used_prompts\PostsMassEditLastUsedPrompts;
use SEOAIC\last_used_prompts\PostsMassGenerateLastUsedPrompts;
use SEOAIC\last_used_prompts\PostsMassReviewLastUsedPrompts;
use SeoaicAjaxValidation;

class SEOAIC_PROMPTS
{
    public function __construct()
    {
        add_action('wp_ajax_seoaic_settings_prompts', [$this, 'seoaic_settings_prompts']);

        add_action('wp_ajax_seoaic_keywords_generate_save_prompt_template', [$this, 'keywordsGenerateSavePromptTemplate']);
        add_action('wp_ajax_seoaic_keywords_generate_delete_prompt_template', [$this, 'keywordsGenerateDeletePromptTemplate']);
        add_action('wp_ajax_seoaic_keywords_generate_delete_last_prompt', [$this, 'keywordsGenerateDeleteLastPrompt']);

        add_action('wp_ajax_seoaic_ideas_generate_save_prompt_template', [$this, 'ideasGenerateSavePromptTemplate']);
        add_action('wp_ajax_seoaic_ideas_generate_delete_prompt_template', [$this, 'ideasGenerateDeletePromptTemplate']);
        add_action('wp_ajax_seoaic_ideas_generate_delete_last_prompt', [$this, 'ideasGenerateDeleteLastPrompt']);

        add_action('wp_ajax_seoaic_posts_mass_generate_save_prompt_template', [$this, 'postsMassGenerateSavePromptTemplate']);
        add_action('wp_ajax_seoaic_posts_mass_generate_delete_prompt_template', [$this, 'postsMassGenerateDeletePromptTemplate']);
        add_action('wp_ajax_seoaic_posts_mass_generate_delete_last_prompt', [$this, 'postsMassGenerateDeleteLastPrompt']);

        add_action('wp_ajax_seoaic_posts_mass_edit_save_prompt_template', [$this, 'postsMassEditSavePromptTemplate']);
        add_action('wp_ajax_seoaic_posts_mass_edit_delete_prompt_template', [$this, 'postsMassEditDeletePromptTemplate']);
        add_action('wp_ajax_seoaic_posts_mass_edit_delete_last_prompt', [$this, 'postsMassEditDeleteLastPrompt']);

        add_action('wp_ajax_seoaic_posts_mass_review_save_prompt_template', [$this, 'postsMassReviewSavePromptTemplate']);
        add_action('wp_ajax_seoaic_posts_mass_review_delete_prompt_template', [$this, 'postsMassReviewDeletePromptTemplate']);
        add_action('wp_ajax_seoaic_posts_mass_review_delete_last_prompt', [$this, 'postsMassReviewDeleteLastPrompt']);
    }

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

        global $SEOAIC_OPTIONS;

        $keywordsLastPromptsInstance = new KeywordsGenerateLastUsedPrompts();
        $ideasLastPromptsInstance = new IdeasGenerateLastUsedPrompts();
        $postsGenerationLastPromptsInstance = new PostsMassGenerateLastUsedPrompts();
        $postsEditLastPromptsInstance = new PostsMassEditLastUsedPrompts();
        $postsReviewLastPromptsInstance = new PostsMassReviewLastUsedPrompts();
        $keywordsSettingsCountField = $keywordsLastPromptsInstance->getSettingsCountField();
        $ideasSettingsCountField = $ideasLastPromptsInstance->getSettingsCountField();
        $postsGenerateSettingsCountField = $postsGenerationLastPromptsInstance->getSettingsCountField();
        $postsEditSettingsCountField = $postsEditLastPromptsInstance->getSettingsCountField();
        $postsReviewSettingsCountField = $postsReviewLastPromptsInstance->getSettingsCountField();

        foreach ($_POST as $key => $value) {
            switch ($key) {
                case $keywordsSettingsCountField:
                case $ideasSettingsCountField:
                case $postsGenerateSettingsCountField:
                case $postsEditSettingsCountField:
                case $postsReviewSettingsCountField:
                case 'seoaic_keywords_generate_prompt_templates':
                case 'seoaic_ideas_generate_prompt_templates':
                case 'seoaic_posts_mass_generate_prompt_templates':
                case 'seoaic_posts_mass_edit_prompt_templates':
                case 'seoaic_posts_mass_review_prompt_templates':
                    if (is_array($value)) {
                        $SEOAIC_OPTIONS[$key] = [];

                        foreach ($value as $item) {
                            $item = map_deep($item, function ($str) {
                                $str = wp_unslash($str);

                                return wp_kses($str, [
                                    'br'    => [],
                                    'a'     => [
                                        'href'      => [],
                                        '_target'   => [],
                                        'class'     => [],
                                    ],
                                ]);
                            });

                            if (
                                'seoaic_posts_mass_generate_prompt_templates' == $key
                                || 'seoaic_keywords_generate_prompt_templates' == $key
                                || 'seoaic_ideas_generate_prompt_templates' == $key
                                || 'seoaic_posts_mass_edit_prompt_templates' == $key
                                || 'seoaic_posts_mass_review_prompt_templates' == $key
                            ) {
                                $prompt_key = 'pt-' . rand(1000, 6000);
                                $SEOAIC_OPTIONS[$key][$prompt_key] = stripslashes($item);

                            } else {
                                $SEOAIC_OPTIONS[$key][] = stripslashes($item);
                            }
                        }

                    } else {
                        $SEOAIC_OPTIONS[$key] = stripslashes(sanitize_textarea_field($value));
                    }

                    break;
            }

            $settingFieldsArray = [
                $keywordsSettingsCountField,
                $ideasSettingsCountField,
                $postsGenerateSettingsCountField,
                $postsEditSettingsCountField,
                $postsReviewSettingsCountField,
            ];

            foreach ($settingFieldsArray as $settingField) {
                if (
                    empty($_POST[$settingField])
                    || !is_numeric($_POST[$settingField])
                    || $_POST[$settingField] < 0
                ) {
                    $SEOAIC_OPTIONS[$settingField] = 0;
                }
            }


            if (!isset($_POST['seoaic_keywords_generate_prompt_templates'])) {
                $SEOAIC_OPTIONS['seoaic_keywords_generate_prompt_templates'] = [];
            }

            if (!isset($_POST['seoaic_ideas_generate_prompt_templates'])) {
                $SEOAIC_OPTIONS['seoaic_ideas_generate_prompt_templates'] = [];
            }

            if (!isset($_POST['seoaic_posts_mass_generate_prompt_templates'])) {
                $SEOAIC_OPTIONS['seoaic_posts_mass_generate_prompt_templates'] = [];
            }

            if (!isset($_POST['seoaic_posts_mass_edit_prompt_templates'])) {
                $SEOAIC_OPTIONS['seoaic_posts_mass_edit_prompt_templates'] = [];
            }

            if (!isset($_POST['seoaic_posts_mass_review_prompt_templates'])) {
                $SEOAIC_OPTIONS['seoaic_posts_mass_review_prompt_templates'] = [];
            }
        }

        update_option('seoaic_options', $SEOAIC_OPTIONS);

        SEOAICAjaxResponse::success()->wpSend();
    }

    /**
     * @param object $dataCollectionInstance instance of AbstractPromptDataCollection class
     */
    public function makePromptsSection($dataCollectionInstance, $echo = false)
    {
        $html = '';

        if (is_a($dataCollectionInstance, 'SEOAIC\collections\prompt_data\AbstractPromptDataCollection')) {
            $html = $this->makePromptsSectionHTML($dataCollectionInstance);
        }

        if (!$echo) {
            return $html;
        }

        echo $html;
        return;
    }

    private function makePromptsSectionHTML($instance = null)
    {
        if (!$instance) {
            return '';
        }

        ob_start();
        ?>
        <div class="prompts-templates-and-lastused-section position-absolute">
            <?php
            if (
                !empty($instance->promptsTemplates)
                && is_array($instance->promptsTemplates)
            ) {
                ?>
                <div class="prompt-templates-section mb-30">
                    <div class="label d-inline-block position-relative fs-16 mb-10">
                        <b><?php esc_html_e('Prompt templates', 'seoaic');?></b>
                    </div>
                    <div class="templates d-flex">
                        <?php
                        foreach ($instance->promptsTemplates as $i => $promptTemplate) {
                            ?>
                            <div class="template-wrapper">
                                <div class="template fs-small position-relative">
                                    <div class="template-text"><?php echo esc_html($promptTemplate);?></div>
                                    <div class="prompt-editor-wrapper">
                                        <textarea class="prompt-template-editor"><?php echo esc_html($promptTemplate);?></textarea>
                                        <div class="prompt-editor-buttons d-flex">
                                            <div
                                                class="seoaic-editor-save seoaic-editor-btn"
                                                title="<?php esc_html_e('Save template', 'seoaic');?>"
                                                data-id="<?php echo esc_attr($i);?>"
                                                data-action="<?php echo esc_attr($instance->saveTemplateAction);?>"
                                            ></div>
                                            <div class="seoaic-editor-cancel seoaic-editor-btn" title="<?php esc_html_e('Cancel', 'seoaic');?>"></div>
                                        </div>
                                    </div>
                                    <div class="buttons position-absolute">
                                        <button title="<?php esc_html_e('Edit template', 'seoaic');?>" type="button" class="button seoaic-edit-prompt-btn"></button>
                                        <button title="<?php esc_html_e('Delete template', 'seoaic');?>" type="button" class="button seoaic-delete-prompt-btn ml-5px"></button>
                                    </div>
                                    <div class="delete-confirm-section position-absolute">
                                        <div class="prompt-deletion position-absolute">
                                            <div class="prompt-deletion-title"><?php esc_html_e('Delete', 'seoaic');?>?</div>
                                            <div class="prompt-deletion-body d-flex">
                                                <div
                                                    class="seoaic-prompt-confirm-delete-yes"
                                                    title="<?php esc_html_e('Yes', 'seoaic');?>"
                                                    data-id="<?php echo esc_attr($i);?>"
                                                    data-action="<?php echo esc_attr($instance->deleteTemplateAction);?>"
                                                ></div>
                                                <div class="seoaic-prompt-confirm-delete-no" title="<?php esc_html_e('No', 'seoaic');?>"></div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <?php
                        }
                        ?>
                    </div>
                </div>
                <?php
            }

            if (
                !empty($instance->promptsLastUsed)
                && is_array($instance->promptsLastUsed)
            ) {
                ?>
                <div class="last-prompts-section">
                    <div class="label d-inline-block position-relative fs-16 mb-10 seoaic-cursor-help" title="<?php esc_html_e("The last prompt is on the top of the list.", 'seoaic');?>">
                        <span><b><?php esc_html_e('Last Used Prompts', 'seoaic');?></b></span>
                    </div>
                    <div class="templates d-flex">
                        <?php
                        foreach ($instance->promptsLastUsed as $i => $usedPrompt) {
                            ?>
                            <div class="template-wrapper">
                                <div class="template fs-small position-relative">
                                    <div class="template-text"><?php echo esc_html($usedPrompt);?></div>
                                    <div class="buttons position-absolute">
                                        <button title="<?php esc_html_e('Delete prompt', 'seoaic');?>" type="button" class="button seoaic-delete-prompt-btn ml-5px"></button>
                                    </div>
                                    <div class="delete-confirm-section position-absolute">
                                        <div class="prompt-deletion position-absolute">
                                            <div class="prompt-deletion-title"><?php esc_html_e('Delete', 'seoaic');?>?</div>
                                            <div class="prompt-deletion-body d-flex">
                                                <div
                                                    class="seoaic-prompt-confirm-delete-yes"
                                                    title="<?php esc_html_e('Yes', 'seoaic');?>"
                                                    data-id="<?php echo esc_attr($i);?>"
                                                    data-action="<?php echo esc_attr($instance->deleteLastUsedAction);?>"
                                                ></div>
                                                <div class="seoaic-prompt-confirm-delete-no" title="<?php esc_html_e('No', 'seoaic');?>"></div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <?php
                        }
                        ?>
                    </div>
                </div>
                <?php
            }
            ?>
        </div>
        <?php

        return ob_get_clean();
    }

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

        if (empty($_POST['id'])) {
            SEOAICAjaxResponse::error('Wrong template ID');
        }

        if (empty($_POST['text'])) {
            SEOAICAjaxResponse::error('Text is empty');
        }

        $templates = SEOAIC_SETTINGS::getPostsGeneratePromptTemplates();
        if (
            !empty($templates)
            && is_array($templates)
        ) {
            foreach ($templates as $i => &$template) {
                if ($i == $_POST['id']) {
                    $template = esc_html($_POST['text']);
                }
            }

            SEOAIC_SETTINGS::setPostsGeneratePromptTemplates($templates);
        }

        SEOAICAjaxResponse::success()->wpSend();
    }

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

        if (empty($_POST['id'])) {
            SEOAICAjaxResponse::error('Wrong template ID');
        }

        $templates = SEOAIC_SETTINGS::getPostsGeneratePromptTemplates();
        if (
            !empty($templates)
            && is_array($templates)
            && isset($templates[$_POST['id']])
        ) {
            unset($templates[$_POST['id']]);

            SEOAIC_SETTINGS::setPostsGeneratePromptTemplates($templates);
        }

        SEOAICAjaxResponse::success()->wpSend();
    }

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

        if (empty($_POST['id'])) {
            SEOAICAjaxResponse::error('Wrong template ID');
        }

        (new PostsMassGenerateLastUsedPrompts())->delete($_POST['id']);

        SEOAICAjaxResponse::success()->wpSend();
    }


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

        if (empty($_POST['id'])) {
            SEOAICAjaxResponse::error('Wrong template ID');
        }

        if (empty($_POST['text'])) {
            SEOAICAjaxResponse::error('Text is empty');
        }

        $templates = SEOAIC_SETTINGS::getKeywordsGeneratePromptTemplates();
        if (
            !empty($templates)
            && is_array($templates)
        ) {
            foreach ($templates as $i => &$template) {
                if ($i == $_POST['id']) {
                    $template = esc_html($_POST['text']);
                }
            }

            SEOAIC_SETTINGS::setKeywordsGeneratePromptTemplates($templates);
        }

        SEOAICAjaxResponse::success()->wpSend();
    }

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

        if (empty($_POST['id'])) {
            SEOAICAjaxResponse::error('Wrong template ID');
        }

        $templates = SEOAIC_SETTINGS::getKeywordsGeneratePromptTemplates();
        if (
            !empty($templates)
            && is_array($templates)
            && isset($templates[$_POST['id']])
        ) {
            unset($templates[$_POST['id']]);

            SEOAIC_SETTINGS::setKeywordsGeneratePromptTemplates($templates);
        }

        SEOAICAjaxResponse::success()->wpSend();
    }

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

        if (empty($_POST['id'])) {
            SEOAICAjaxResponse::error('Wrong template ID');
        }

        (new KeywordsGenerateLastUsedPrompts())->delete($_POST['id']);

        SEOAICAjaxResponse::success()->wpSend();
    }

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

        if (empty($_POST['id'])) {
            SEOAICAjaxResponse::error('Wrong template ID');
        }

        if (empty($_POST['text'])) {
            SEOAICAjaxResponse::error('Text is empty');
        }

        $templates = SEOAIC_SETTINGS::getIdeasGeneratePromptTemplates();
        if (
            !empty($templates)
            && is_array($templates)
        ) {
            foreach ($templates as $i => &$template) {
                if ($i == $_POST['id']) {
                    $template = esc_html($_POST['text']);
                }
            }

            SEOAIC_SETTINGS::setIdeasGeneratePromptTemplates($templates);
        }

        SEOAICAjaxResponse::success()->wpSend();
    }

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

        if (empty($_POST['id'])) {
            SEOAICAjaxResponse::error('Wrong template ID');
        }

        $templates = SEOAIC_SETTINGS::getIdeasGeneratePromptTemplates();
        if (
            !empty($templates)
            && is_array($templates)
            && isset($templates[$_POST['id']])
        ) {
            unset($templates[$_POST['id']]);

            SEOAIC_SETTINGS::setIdeasGeneratePromptTemplates($templates);
        }

        SEOAICAjaxResponse::success()->wpSend();
    }

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

        if (empty($_POST['id'])) {
            SEOAICAjaxResponse::error('Wrong template ID');
        }

        (new IdeasGenerateLastUsedPrompts())->delete($_POST['id']);

        SEOAICAjaxResponse::success()->wpSend();
    }

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

        if (empty($_POST['id'])) {
            SEOAICAjaxResponse::error('Wrong template ID');
        }

        if (empty($_POST['text'])) {
            SEOAICAjaxResponse::error('Text is empty');
        }

        $templates = SEOAIC_SETTINGS::getPostsEditPromptTemplates();
        if (
            !empty($templates)
            && is_array($templates)
        ) {
            foreach ($templates as $i => &$template) {
                if ($i == $_POST['id']) {
                    $template = esc_html($_POST['text']);
                }
            }

            SEOAIC_SETTINGS::setPostsEditPromptTemplates($templates);
        }

        SEOAICAjaxResponse::success()->wpSend();
    }

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

        if (empty($_POST['id'])) {
            SEOAICAjaxResponse::error('Wrong template ID');
        }

        $templates = SEOAIC_SETTINGS::getPostsEditPromptTemplates();
        if (
            !empty($templates)
            && is_array($templates)
            && isset($templates[$_POST['id']])
        ) {
            unset($templates[$_POST['id']]);

            SEOAIC_SETTINGS::setPostsEditPromptTemplates($templates);
        }

        SEOAICAjaxResponse::success()->wpSend();
    }

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

        if (empty($_POST['id'])) {
            SEOAICAjaxResponse::error('Wrong template ID');
        }

        (new PostsMassEditLastUsedPrompts())->delete($_POST['id']);

        SEOAICAjaxResponse::success()->wpSend();
    }


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

        if (empty($_POST['id'])) {
            SEOAICAjaxResponse::error('Wrong template ID');
        }

        if (empty($_POST['text'])) {
            SEOAICAjaxResponse::error('Text is empty');
        }

        $templates = SEOAIC_SETTINGS::getPostsReviewPromptTemplates();
        if (
            !empty($templates)
            && is_array($templates)
        ) {
            foreach ($templates as $i => &$template) {
                if ($i == $_POST['id']) {
                    $template = esc_html($_POST['text']);
                }
            }

            SEOAIC_SETTINGS::setPostsReviewPromptTemplates($templates);
        }

        SEOAICAjaxResponse::success()->wpSend();
    }

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

        if (empty($_POST['id'])) {
            SEOAICAjaxResponse::error('Wrong template ID');
        }

        $templates = SEOAIC_SETTINGS::getPostsReviewPromptTemplates();
        if (
            !empty($templates)
            && is_array($templates)
            && isset($templates[$_POST['id']])
        ) {
            unset($templates[$_POST['id']]);

            SEOAIC_SETTINGS::setPostsReviewPromptTemplates($templates);
        }

        SEOAICAjaxResponse::success()->wpSend();
    }

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

        if (empty($_POST['id'])) {
            SEOAICAjaxResponse::error('Wrong template ID');
        }

        (new PostsMassReviewLastUsedPrompts())->delete($_POST['id']);

        SEOAICAjaxResponse::success()->wpSend();
    }
}
