<?php

namespace SEOAIC;

use DateTime;
use SeoaicAjaxValidation;

class SeoaicAlsoAskIdeas
{
    private $seoaic;

    public function __construct($seoaic)
    {
        $this->seoaic = $seoaic;
        add_action('wp_ajax_seoaic_create_also_ask_html', [$this, 'create_also_ask_html']);
    }

    public function create_also_ask_html()
    {
        global $SEOAIC_OPTIONS;
        check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);
        $post = wp_unslash($_POST);
        $keyword    = !empty($post['keyword']) ? $post['keyword'] : null;
        $location   = !empty($post['location']) ? $post['location'] : null;
        $language   = !empty($post['language']) ? $post['language'] : null;
        $post_id    = !empty($post['post_id']) ? $post['post_id'] : null;

        if ($post_id) {
            if ($this->seoaic->multilang->is_multilang()) {
                $language = $this->seoaic->multilang->get_post_language($post_id);
                $lang = $this->seoaic->multilang->get_language_by($language);
                $location_code = !empty($SEOAIC_OPTIONS['language_locations'][$lang['code']]) ? $SEOAIC_OPTIONS['language_locations'][$lang['code']] : null;
                $location = $this->getCountryNameByCode($this->seoaic->multilang->getLocationsWithLanguages(), $location_code);
                if (!$location) {
                    $location = SEOAIC_SETTINGS::getLocation();
                }
                if (!$language) {
                    $language = SEOAIC_SETTINGS::getLanguage();
                }
            } else {
                $location = SEOAIC_SETTINGS::getLocation();
                $language = SEOAIC_SETTINGS::getLanguage();
            }
        }

        if (!$keyword) {
            wp_send_json_success(['html' => '<div class="mt-40">' . esc_html__('Keyword is not set', 'seoaic') . '</div>']);
        }

        $data = $this->request_questions_data($keyword, $location, $language);
        if (empty($data['data'])) {
            wp_send_json_success(['html' => '<div class="seoaic-also-ask-level-1">' . esc_html__('No data for this keyword') . '</div>']);
        }
        $html = wp_kses($this->renderQuestions($data['data']), $this->kses_allowed_html());
        if (!$keyword) {
            SEOAICAjaxResponse::alert('Keyword is not set')->wpSend();
        }

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

    public function getCountryNameByCode($countries, $code)
    {
        foreach ($countries as $country) {
            if ($country['code'] === intval($code)) {
                return $country['name'];
            }
        }
        return null;
    }

    private function countLeafQuestions($items)
    {
        $count = 0;
        foreach ($items as $item) {
            if (isset($item['results']) && is_array($item['results']) && count($item['results']) > 0) {
                $count += $this->countLeafQuestions($item['results']);
            } elseif (isset($item['question'])) {
                $count++;
            }
        }

        return $count;
    }

    private function get_current_datetime_attribute()
    {
        $datetime = new DateTime('now', wp_timezone());
        return $datetime->format('Y-m-d\TH:i');
    }

    private function request_questions_data($keyword, $location, $language)
    {
        $request_data = [
            'keywords' => [
                [
                  "keyword" => $keyword,
                  "location" => $location,
                  "language" => $language
                ],
            ],
        ];

        return $this->seoaic->curl->init('api/ai/also-asked-ideas', $request_data, true, true, true);
    }

    private function kses_allowed_html()
    {
        return [
            'input' => [
                'id' => true,
                'type' => true,
                'name' => true,
                'value' => true,
                'class' => true,
                'data-date' => true,
                'data-title' => true,
                'data-cluster' => true,
                'data-language' => true,
                'data-idea-type' => true,
                'data-language-code' => true,
                'data-keywords' => true,
            ],
            'label' => [
                'for' => true,
                'class' => true,
            ],
            'span' => [
                'class' => true,
            ],
            'li' => [
                'class' => true,
            ],
            'ul' => [
                'class' => true,
            ],
            'div' => [
                'class' => true,
                'style' => true,
                'data-hide' => true,
                'data-keywords' => true,
            ],
            'h4' => [
                'class' => true,
            ],
            'p' => [
                'class' => true,
            ],
        ];
    }

    private function createCheckbox($lastTreeCheckbox, $unique_id, $question, $term, $lang_name, $lang_code)
    {
        $html = '';
        if ($lastTreeCheckbox) {
            //data-cluster="' . esc_attr(preg_replace('/[^\p{L}\p{N}\s]/u', '', $term)) . '"
            $html .= '<input 
                    id="' . esc_attr($unique_id) . '"
                    type="checkbox" 
                    name="questions[]"
                    data-date="' . $this->get_current_datetime_attribute() . '" 
                    data-title="' . esc_attr($question) . '" 
                   
                    data-language="' . esc_attr($lang_name) . '"
                    data-idea-type="also_asked"
                    data-language-code="' . esc_attr($lang_code) . '"
                    value="' . esc_attr($question) . '" 
                    class="seoaic-checkbox ' . esc_attr($lastTreeCheckbox) . '">';
            $html .= '<label for="' . esc_attr($unique_id) . '" class="seoaic-also-ask-question">' . esc_attr($question) . '</label>';
        } else {
            $html .= '<input type="checkbox" name="questions[]" value="' . esc_attr($question) . '" class="seoaic-checkbox ' . esc_attr($lastTreeCheckbox) . '">';
            $html .= '<span class="">' . esc_html__('Cluster name: ', 'seoaic') . '</span><span class="seoaic-also-ask-question">' . esc_html(preg_replace('/[^\p{L}\p{N}\s]/u', '', $question)) . '</span>';
        }

        return $html;
    }

    private function createLi($lastTreeCheckbox, $lastTreeQuestion, $level, $unique_id, $question, $term, $lang_name, $lang_code, $hasChildren, $item, $levelClass)
    {
        $html = '<li class="seoaic-also-ask-item fs-small li-also-ask-level-' . $level . '">';
        $html .= '<div class="seoaic-also-ask-toggle ' . esc_attr($lastTreeQuestion) . '">';
        $html .= $this->createCheckbox($lastTreeCheckbox, $unique_id, $question, $term, $lang_name, $lang_code);


        if ($hasChildren) {
            $leafCount = $this->countLeafQuestions($item['results']);
            $html .= ' (' . $leafCount . ')';
        }

        $html .= '</div>';

        if ($hasChildren) {
            $html .= '<div class="seoaic-also-ask-children display-none ' . $levelClass . '">';
            $html .= wp_kses($this->renderQuestions($item['results'], $level + 1, $lang_code, $lang_name, $question), $this->kses_allowed_html());
            $html .= '</div>';
        }

        $html .= '</li>';

        return $html;
    }

    private function renderQuestions($data, $level = 1, $lang_code = '', $lang_name = '', $term = '')
    {
        global $SEOAIC;
        $html = '';

        if ($level === 1 && isset($data[0]['term'])) {
            foreach ($data as $entry) {
                if (!isset($entry['term'])) {
                    continue;
                }

                $term = htmlspecialchars($entry['term']);
                $html .= '<div class="seoaic-top-level-header">';
                $html .= '<h4 class="mb-5 mt-15">' . esc_html__('Content Map: ', 'seoaic') . $term . '</h4>';
                $html .= '<p class="mb-19 mt-15">' . esc_html__('A hierarchical view of related questions based on your main keyword. Select specific questions to generate content.', 'seoaic') . '</p>';
                $html .= '</div>';

                if (isset($entry['results']) && is_array($entry['results'])) {
                    $leafCount = $this->countLeafQuestions($entry['results']);

                    $html .= '<div class="seoaic-also-ask-item main-wrap mr-5" data-keywords="' . esc_attr(json_encode([$term])) . '">';
                    $html .= '<div class="seoaic-also-ask-toggle seoaic-also-ask-main-toggle">';
                    $html .= '<input id="seoaic-check-mai" type="checkbox" class="seoaic-also-ask-master-checkbox seoaic-checkbox">';
                    $html .= '<label for="seoaic-check-mai" class="seoaic-also-ask-question accent accent-underline">Select all (' . $leafCount . ')</label>';
                    $html .= '</div>';
                    $html .= '<div class="seoaic-also-ask-children seoaic-also-ask-main-children">';
                    $lang_code = $entry['language'];
                    $language = $SEOAIC->multilang->get_language_by($lang_code, 'code');
                    $language = !empty($language['name']) ? $language['name'] : '';
                    $html .= wp_kses($this->renderQuestions($entry['results'], $level, $lang_code, $language, $term), $this->kses_allowed_html());
                    $html .= '</div>';
                    $html .= '</div>';
                }
            }

            return $html;
        }

        $html .= '<ul class="seoaic-also-ask-level-' . $level . '">';
        $levelClass = 'level-' . $level;
        $noParentQuestions = '';
        $noParentQuestionsCount = 0;
        foreach ($data as $item) {
            $question = !empty($item['question']) ? htmlspecialchars($item['question']) : '';
            $hasChildren = isset($item['results']) && is_array($item['results']) && count($item['results']) > 0;
            $lastTreeCheckbox = $hasChildren ? '' : 'seoaic-also-ask-idea-checkbox';
            $lastTreeQuestion = $hasChildren ? '' : 'seoaic-also-ask-idea-question';
            $unique_id = 'seoaic_idea_' . sanitize_title($question) . '_' . rand(100, 9999);

            if ($lastTreeCheckbox && $level === 1) {
                $noParentQuestionsCount = $noParentQuestionsCount + 1;
                $noParentQuestions .= $this->createLi($lastTreeCheckbox, $lastTreeQuestion, $level, $unique_id, $question, $term, $lang_name, $lang_code, $hasChildren, $item, $levelClass);
            } else {
                $html .= $this->createLi($lastTreeCheckbox, $lastTreeQuestion, $level, $unique_id, $question, $term, $lang_name, $lang_code, $hasChildren, $item, $levelClass);
            }
        }

        if ($noParentQuestions) {
            $html .= '
            <li class="seoaic-also-ask-item fs-small li-also-ask-level-1">
                <div class="seoaic-also-ask-toggle">
                    <input type="checkbox" name="questions[]" class="seoaic-checkbox ">
                    <span class="">' . esc_html__('Cluster name: ', 'seoaic') . '</span>
                    <span class="seoaic-also-ask-question">' . esc_html($term) . '</span> (' . $noParentQuestionsCount . ')
                </div>
                <div class="seoaic-also-ask-children display-none level-1">
                    <ul class="seoaic-also-ask-level-2">
                        ' . $noParentQuestions . '
                    </ul>
                </div>
            </li>';
        }

        $html .= '</ul>';

        return $html;
    }
}
