<?php

use SEOAIC\posts_mass_actions\FramesMassGenerate;
use SEOAIC\SEOAICAjaxResponse;
use SEOAIC\traits\MassActionsWorkflow;

class SEOAIC_FRAMES
{
    use MassActionsWorkflow;

    private $seoaic;

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

        add_action('wp_ajax_seoaic_generate_skeleton', [$this, 'generateAjax']);
        add_action('wp_ajax_seoaic_frames_mass_generate', [$this, 'massGenerateAjax']);
        add_action('wp_ajax_seoaic_frames_mass_generate_check_status', [$this, 'massGenerateCheckStatusAjax']);
    }

    public static function formatWithOutlines($skeleton = [])
    {
        return array_map(function($item) {
            if (is_string($item)) {
                return [
                    'title'     => $item,
                    'outline'   => "",
                ];
            }

            return $item;
        }, $skeleton);
    }

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

        global $SEOAIC_OPTIONS;

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

        $subtitlesRangeMin  = $_REQUEST['seoaic_subtitles_range_min'] ?: $SEOAIC_OPTIONS['seoaic_subtitles_range_min'];
        $subtitlesRangeMax  = $_REQUEST['seoaic_subtitles_range_max'] ?: $SEOAIC_OPTIONS['seoaic_subtitles_range_max'];
        $requestPrompt      = $_REQUEST['prompt'] ?: '';

        $lang = $this->seoaic->multilang->get_post_language($id);

        $name = !empty($SEOAIC_OPTIONS['seoaic_business_name']) ? $SEOAIC_OPTIONS['seoaic_business_name'] : get_option('blogname', true);
        $industry = !empty($SEOAIC_OPTIONS['seoaic_industry']) ? " on the industry of " . $SEOAIC_OPTIONS['seoaic_industry'] : '';
        $desc = !empty($SEOAIC_OPTIONS['seoaic_business_description']) ? $SEOAIC_OPTIONS['seoaic_business_description'] : get_option('blogdescription', true);

        //$editorFrame = $_REQUEST['data_editor'];
        $title = isset($_REQUEST['get_title']) ? $_REQUEST['get_title'] : get_the_title($id);
        $keys = get_post_meta( $id, '_idea_keywords_data', true );
        $prompt = get_post_meta( $id, '_idea_prompt_data', true );
        $idea_type = get_post_meta($id, '_idea_type', true);
        $title = $title ? $title : get_the_title($id);

        $data = [
            'idea' => $title,
            'language' => $lang,
            'idea_prompt' => $prompt ?: $requestPrompt,
            'idea_type' => $idea_type ?: 'default',
            'idea_keys' => is_array($keys) ? implode(',', $keys) : $keys,
            'name' => $name,
            'desc' => $desc,
            'industry' => $industry,
            'subtitles_min' => !empty($subtitlesRangeMin) ? intval($subtitlesRangeMin) : 0,
            'subtitles_max' => !empty($subtitlesRangeMax) ? intval($subtitlesRangeMax) : 6,
            'writing_style' => !empty($SEOAIC_OPTIONS['seoaic_writing_style']) ? $SEOAIC_OPTIONS['seoaic_writing_style'] : '',
            'with_outlines' => true,
        ];

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

        $content = !empty($result['content']) ? $result['content'] : '';

        $thumbnail_generator = !empty($SEOAIC_OPTIONS['seoaic_image_generator']) ? $SEOAIC_OPTIONS['seoaic_image_generator'] : 'no_image';
        $old_idea_content = get_post_meta($id, 'seoaic_idea_content', true);
        if ( !empty($old_idea_content) ) {
            $old_idea_content = json_decode($old_idea_content, true);
            if ( !empty($old_idea_content['idea_thumbnail_generator']) ) {
                $thumbnail_generator = $old_idea_content['idea_thumbnail_generator'];
            }
        }

        $subtitles = isset($content['subtitles']) ? self::formatWithOutlines($content['subtitles']) : [];

        if (!empty($content)) {
            $idea_content = [
                'idea_thumbnail' => isset($content['image-description']) ? str_replace('"', '\"', $content['image-description']) : '',
                'idea_thumbnail_generator' => str_replace('"', '\"', $thumbnail_generator),
                'idea_skeleton' => $subtitles,
                'idea_keywords' => isset($content['keywords']) ? str_replace('"', '\"', $content['keywords']) : '',
                'idea_description' => isset($content['description']) ? str_replace('"', '\"', $content['description']) : '',
            ];
        } else {
            $idea_content = [];
        }

        update_post_meta($id, 'seoaic_idea_content', json_encode($idea_content, JSON_UNESCAPED_UNICODE));

        $idea_content['idea_keywords'] = array_map(
            function ($keyword) {
                return [
                    'id' => '',
                    'name' => $this->seoaic->ideas->fix_umlauts_characters($keyword),
                ];
            },
            $idea_content['idea_keywords']
        );

        SEOAICAjaxResponse::success()->addFields([
            'content' => [
                'idea_content'   => $idea_content,
                'idea_postdate'  => '',
                //'seoaic_credits' => $this->seoaic->get_api_credits(),
                'idea_id'        => $id,
                'idea_icons'     => $this->seoaic->ideas->get_idea_icons($id),
            ],
        ])->setFlags(JSON_UNESCAPED_UNICODE)->wpSend();
    }

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

        $instance = new FramesMassGenerate($this->seoaic);
        $this->postsMassActionRun($instance);
    }

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

        $instance = new FramesMassGenerate($this->seoaic);
        $this->postsMassActionCheckStatus($instance);
    }
}
