<?php

namespace SEOAIC;

use SeoaicAjaxValidation;

class SEOAIC_EXPLORER
{
    private $seoaic;

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

        add_action('wp_ajax_seoaic_get_keywords_results', [$this, 'get_keywords_results']);
        add_action('wp_ajax_seoaic_get_questions_words', [$this, 'get_questions_words']);
    }

    private function get_language_code($language)
    {

        global $SEOAIC;

        $result = $SEOAIC->curl->setMethodGet()->initWithReturn('/api/ai/locations-and-languages', [], false, true);

        foreach ((array)$result['data'] as $country) {
            if (isset($country['languages'][$language])) {
                return $country['languages'][$language]['code'];
            }
        }
        return null;
    }

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

        $_post = wp_unslash($_POST);

        if(empty($_post['language'])) {
            return;
        }

        //$result = $SEOAIC->curl->setMethodGet()->initWithReturn('/api/static/question-words', [], false, true);

        $code = $this->get_language_code($_post['language']);
        $result = $this->get_questions_by_code($code);

        if(empty($result)) {
            wp_send_json('empty');
        }
        $questions = array_unique($result);
        $questions = array_values(array_diff($questions, ['from']));
        $checkboxes = '';
        foreach ($questions as $label) {
            $checkboxes .= '
        <div class="check">
            <input id="' . sanitize_title($label) . '-question" type="checkbox" class="seoaic-checkbox terms-filter-input" value="' . $label . '">
            <label for="' . sanitize_title($label) . '-question" class="label-checkbox">' . $label . '</label>
        </div>';
        }

        wp_send_json($checkboxes);
    }

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

        $_post = wp_unslash($_POST);

        $page_num = $_post['page'];
        $keywords_type = $_post['keywords_type'];
        $location = !empty($_post['location']) ? $_post['location'] : SEOAIC_SETTINGS::getLocation();
        $language = !empty($_post['language']) ? $_post['language'] : SEOAIC_SETTINGS::getLanguage();
        $language_code = $this->get_language_code($language);

        if(empty($_post['keyword'])) {
            SEOAICAjaxResponse::alert(esc_html__('Please specify the ', 'seoaic') . '<a href="#" class="set_focus_keyword">' . esc_html__('keyword', 'seoaic') . '</a>')->wpSend();
        }

        $keyword = $_post['keyword'];

        $data = [
            'email' => wp_get_current_user()->user_email,
            'language' => $language,
            'location' => $location,
            'keywords' => [$keyword],
            'keyword' => $keyword,
            'limit' => 100,
            'page' => $page_num,
            'lang_code' => $language_code
        ];

        if(!empty($_post['filters'])) {
            $data['filters'] = $_post['filters'];
        }

        $suggestions = $this->seoaic->curl->init('/api/ai/' . $keywords_type, $data, true, true, true);

        if (empty($suggestions['data'])) {
            SEOAICAjaxResponse::alert(esc_html__('No keywords found with this search criteria', 'seoaic'))->wpSend();
        }

        $html = '';

        foreach ($suggestions['data'] as $item) {
            $html .= '<div class="keyword">
                        <div class="check">
                            <input id="Which-question" type="checkbox" class="seoaic-checkbox" value="' . $item['keyword'] . '">
                        </div>
                        <div class="name">' . $item['keyword'] . '</div>
                        <!---div class="traffic_potential"></div-->
                        <div class="search_volume">' . $item['search_volume'] . '</div>
                        <div class="difficulty">' . $item['difficulty'] . '</div>
                        <div class="serp">
                            <a href="#" data-mini-modal=".view-mini-modal-competitors" class="open-mini-modal keywords-explorer-show-competitors" data-keyword="' . $item['keyword'] . '">show competitors</a>
                        </div>
                    </div>';
        }

        $html .= $this->inline_pagination(intval($page_num), $suggestions['total_pages']);

        wp_send_json($html);
    }

    private function pagination_fields($page, $action = '')
    {
        return $action ? '
            <input type="hidden" class="seoaic-ajax-field" name="action" value="' . $action . '">
            <input type="hidden" class="seoaic-ajax-field" name="page" value="' . $page . '">
        ' : '';
    }

    public function inline_pagination($current_page, $total_pages, $action = false) {

        $current_page = max(1, min($current_page, $total_pages));

        $action_class = '';

        if($action) {
            $action_class = 'seoaic-ajax-form seoaic-ajax-submit';
        }

        $html = '<div class="seoaic-pagination">';

        if ($current_page > 1) {
            $html .= '<a class="page-numbers ' . $action_class . '" data-paginate="' . ($current_page - 1) . '" href="#" class="prev">' . esc_html__('Prev') . $this->pagination_fields($current_page - 1, $action) .'</a>';
        } else {
            $html .= '';
        }

        $start_page = max(1, $current_page - 2);
        $end_page = min($total_pages, $current_page + 2);

        if ($end_page - $start_page < 4) {
            if ($start_page === 1) {
                $end_page = min($total_pages, $start_page + 4);
            } elseif ($end_page === $total_pages) {
                $start_page = max(1, $end_page - 4);
            }
        }

        for ($i = $start_page; $i <= $end_page; $i++) {
            if ($i === $current_page) {
                $html .= '<span class="page-numbers pe-none seaoic_bg-dark seaoic_color-white">' . $i . '</span>';
            } else {
                $html .= '<a class="page-numbers ' . $action_class . '" data-paginate="' . $i . '" href="#">' . $i . $this->pagination_fields($i, $action) . '</a>';
            }
        }

        if ($current_page < $total_pages) {
            $html .= '<a class="page-numbers ' . $action_class . '" data-paginate="' . ($current_page + 1) . '" href="#" class="next">' . esc_html__('Next') . $this->pagination_fields(($current_page + 1), $action) . '</a>';
        } else {
            $html .= '';
        }

        $html .= '</div>';

        return $html;
    }

    public function top_section_html()
    {
        return '
            <div class="top-section">
                <div class="menu-section-seoai padding-x medium-size">
                    <ul>
                        <li>
                            <a class="tab checked" data-keywords-type="keyword-suggestions" href="#">' . esc_html__('Keyword suggestions', 'seoaic') . '</a>
                        </li>
                        <li>
                            <a class="tab" data-keywords-type="keyword-ideas" href="#">' . esc_html__('Related keywords', 'seoaic') . '</a>
                        </li>
                    </ul>
                </div>
                <div id="seoaic-keywords-lists"
                     class="dynamics-tabs"
                     data-on-empty-tab="' . esc_html__('No keywords added in this list', 'seoaic') . '">
                    <div class="carousel-container">
                        <button class="carousel-arrow prev" disabled>‹</button>
                        <div class="carousel-track-container">
                            <div class="carousel-track"></div>
                        </div>
                        <button class="carousel-arrow next" disabled>›</button>
                        <button class="create-list open-mini-modal" data-mini-modal=".add-list">
                            +
                            <span>' . esc_html__('Create List', 'seoaic') . '</span>
                        </button>
                    </div>
                </div>
            </div>';
    }

    public function pre_content_html()
    {
        return '
    <div class="pre-content">
        <div class="keyword edit_keyword_explorer_value">
            <p class="m-0">' . esc_html__('Main Keyword:', 'seoaic') . '</p>
            <input type="text" class="main-keyword-value" placeholder="set keyword"><i class="dashicons dashicons-edit"></i>
            <ul class="suggestions-list"></ul>
            <div class="text-measurer" style="display: none"></div>
            <div class="location-settings">
                <div class="selections">
                    <div class="location-block">
                        <select name="location" class="kw_explorer_location"></select>
                    </div>

                    <div class="language-block ml-10">
                        <select class="kw_explorer_language" name="language"></select>
                    </div>
                    <i class="dashicons dashicons-saved location_loader_selection"></i>
                </div>
            </div>
        </div>
        <div class="question waiting-for-ajax">
            <label for="seoai-selector-questions_20549">' . esc_html__('Questions', 'seoaic') . '</label>
            <input id="seoai-selector-questions_20549" value="20549" type="checkbox" name="seoai-selector-questions_20549">
            <label for="seoai-selector-questions_20549" class="toggler"><span></span></label>
        </div>
        <button type="button"
                class="seoaic-generate-also-ask-map modal-button seoaic-branded-button small-button seoaic-ml-20"
                data-modal="#seoaic-also-ask-generate-ideas"
                data-modal-class="ignore_close_event" disabled>
            ' . esc_html__('Create Content Map', 'seoaic') . '
        </button>
    </div>';
    }

    public function filter_keywords_html()
    {

        //$this->render_filter_parameter(esc_html__('Traffic potential', 'seoaic'), 'traffic_potential', 100000)
        return '
        <div class="filter-keywords">
            <div class="inner">
                ' . $this->render_filter_parameter(esc_html__('Difficulty', 'seoaic'), 'difficulty', 100) . '
                ' . $this->render_filter_parameter(esc_html__('Search volume', 'seoaic'), 'search_volume', 100000) . '
                ' . $this->render_question_filter() . '
                ' . $this->render_text_filter(esc_html__('Include', 'seoaic'), 'include', esc_html__('Separate multiple words by commas.', 'seoaic')) . '
                ' . $this->render_text_filter(esc_html__('Exclude', 'seoaic'), 'exclude', esc_html__('Separate multiple words by commas.', 'seoaic')) . '

                <button class="search-keywords" type="button" disabled>' . esc_html__('Search keywords', 'seoaic') . '</button>
            </div>
        </div>';
    }

    public function keywords_content_html()
    {
        return '
            <div class="keywords-content">
                <div class="keywords-row header">
                    <div class="keyword">
                        <div class="check">
                            <input id="select_all_keywords_explorer" type="checkbox" class="seoaic-checkbox">
                        </div>
                        <div class="name">' . esc_html__('Keyword', 'seoaic') . '</div>
                        <!---div class="traffic_potential">Traffic Potential</div--->
                        <div class="search_volume">' . esc_html__('Search volume', 'seoaic') . '</div>
                        <div class="difficulty">' . esc_html__('Difficulty', 'seoaic') . '</div>
                        <div class="serp">' . esc_html__('SERP', 'seoaic') . '</div>
                    </div>
                </div>
                <div class="keywords-row explorer"></div>
            </div>';
    }

    public function after_keywords_content_html()
    {
        return '
            <div class="after-keywords-content">
                <button id="seoaic_removeFromListButton"
                        data-active-row=""
                        type="button"
                        class="seoaic-popup__btn outline"
                        disabled>
                    ' . esc_html__('– Remove selected', 'seoaic') . '
                </button>
                <button id="seoaic_addToListButton"
                        type="button"
                        class="seoaic-popup__btn outline open-mini-modal"
                        data-mini-modal=".add-to-list"
                        disabled>
                    ' . esc_html__('+ Add to list', 'seoaic') . '
                </button>
                <button type="button"
                        data-modal="#generate-ideas-new-keywords"
                        data-modal-class="ignore_close_event"
                        class="seoaic-popup__btn modal-button"
                        disabled>
                    ' . esc_html__('Generate ideas', 'seoaic') . '
                </button>
                <button type="button"
                        class="modal-button seoaic-popup__btn outline"
                        data-modal="#add-keyword-modal"
                        data-modal-class="ignore_close_event"
                        disabled>
                    ' . esc_html__('+ Add to keywords page', 'seoaic') . '
                </button>
            </div>';
    }

    public function mini_modals_html()
    {
        return '
        <div class="mini-modal-inside view-mini-modal-competitors" style="display: none">
            <button type="button" class="close-mini-modal"></button>
            <div class="content-mini-modal">
                <div class="menu-section-seoai padding-x small-size mb-13">
                    <ul>
                        <li>
                            <label for="seoaic_show_competitors_organic" class="tab checked">' . esc_html__('Organic competitors', 'seoaic') . '</label>
                        </li>
                        <li>
                            <label for="seoaic_show_competitors_people_also_ask" class="tab">' . esc_html__('People also ask competitors', 'seoaic') . '</label>
                        </li>
                    </ul>
                    <button id="seoaic_add_to_ideas_questions"
                        data-mode="add"
                        data-single="no"
                        type="button"
                        data-modal="#add-idea-manually"
                        data-modal-class="ignore_close_event"
                        data-title="' . esc_html__('Add new Idea', 'seoaic') . '"
                        data-label="' . esc_html__('Name (separate ideas by new line)', 'seoaic') . '"
                        class="modal-button seoaic-popup__btn"
                        disabled>Add selected to ideas
                    </button>
                    <div class="keyword">
                        <span>Selected keyword:</span>
                        <span id="seoaic_selected-keyword-value" class="selected-keyword-value"></span>
                    </div>
                </div>

                <input id="seoaic_show_competitors_organic" type="radio" name="competitors_overview" checked>
                ' . $this->competitors_overview('organic') . '

                <input id="seoaic_show_competitors_people_also_ask" type="radio" name="competitors_overview">
                ' . $this->competitors_overview('people-also-ask') . '
            </div>
        </div>
        ' . $this->add_list_modal() . $this->add_to_list_modal() . '
    ';
    }

    private function competitors_overview($type)
    {
        if ($type === 'organic') {
            return '
            <div class="competitors-overview active">
                <div id="seoaic_competitors_serp_content" class="serp-content filled">
                    ' . $this->competitors_table() . '
                </div>
                <div class="view-box">
                    <div class="inner columns">
                        <div class="heading page-urls">
                            <button type="button" class="close-view-box"></button>
                            <div class="url">
                                <a target="_blank"
                                   href="№">
                                    <span></span>
                                </a>
                            </div>
                        </div>
                        <div class="analysis left"></div>
                    </div>
                </div>
            </div>
        ';
        }

        return '
        <div class="competitors-overview people-also-ask-competitors-overview">
            <div id="seoaic_people_also_ask_content" class="serp-content filled"></div>
            <div class="view-box">
                <div class="inner columns">
                    <div class="heading page-urls">
                        <button type="button" class="close-view-box"></button>
                        <div class="title"></div>
                    </div>
                    <div class="analysis left"></div>
                </div>
            </div>
        </div>
    ';
    }

    private function competitors_table()
    {
        return '
        <div class="competitors-table">
            <div class="table-row heading">
                <div class="competitor">' . esc_html__('Competitor', 'seoaic') . '</div>
                <div class="rank">' . esc_html__('Rank', 'seoaic') . '</div>
                <div class="analyze">' . esc_html__('Analyze', 'seoaic') . '</div>
            </div>
            <!-- Dynamically render rows here -->
        </div>
    ';
    }

    private function add_list_modal()
    {
        return '
        <div class="mini-modal-inside add-list" style="display: none">
            <button type="button" class="close-mini-modal"></button>
            <div class="content-mini-modal">
                <label for="seoaic-add-new-list">' . esc_html__('Add new list', 'seoaic') . '</label>
                <input id="seoaic-add-new-list" class="seoaic-form-item form-input" type="text"
                    value="' . esc_html__('New list', 'seoaic') . '"
                    placeholder="' . esc_html__('List name', 'seoaic') . '">
            </div>
            <button type="button" class="apply-btn add-new-list close-mini-modal">' . esc_html__('Apply', 'seoaic') . '</button>
        </div>
    ';
    }

    private function add_to_list_modal()
    {
        return '
        <div class="mini-modal-inside add-to-list" style="display: none">
            <button type="button" class="close-mini-modal"></button>
            <div class="content-mini-modal">
                <input type="checkbox" id="seoaic_add_to_new_list">
                <div class="selector-add-lists-options">
                    <span>' . esc_html__('You can ', 'seoaic') . '</span>
                    <label id="seoaic_new_list_label" class="accent accent-underline" for="seoaic_add_to_new_list">' . esc_html__('create new list', 'seoaic') . '</label>
                    <label id="seoaic_add_to_exiting_list_label" class="accent accent-underline" for="seoaic_add_to_new_list">' . esc_html__('add to existing list', 'seoaic') . '</label>
                </div>
                <div class="seoaic-add-to-list-select-wrap">
                    <label for="seoaic-add-to-list-select">' . esc_html__('Add to list', 'seoaic') . '</label>
                    <select id="seoaic-add-to-list-select"></select>
                </div>
                <div class="seoaic-add-to-list-input-wrap">
                    <label for="seoaic-add-new-list">' . esc_html__('Add new list', 'seoaic') . '</label>
                    <input id="seoaic-add-new-list-if-empty" class="seoaic-form-item form-input" type="text"
                        value="' . esc_html__('New list', 'seoaic') . '"
                        placeholder="' . esc_html__('List name', 'seoaic') . '">
                </div>
            </div>
            <button type="button" class="apply-btn add-to-list close-mini-modal">' . esc_html__('Apply', 'seoaic') . '</button>
        </div>
    ';
    }

    private function render_filter_parameter($label, $filter, $default_max)
    {
        return '
    <div class="parameter" data-filter="' . esc_html($filter) . '">
        <div class="filter-name">
            <div class="selected-values"><span title=""></span>
                <button type="button" class="dashicons dashicons-no-alt"></button>
            </div>
            <div class="label-parameter">' . $label . ' <span class="dashicons dashicons-arrow-down-alt2"></span></div>
        </div>
        <div class="dropdown range">
            <label class="drop-title">' . $label . '</label>
            <div class="sort-values">
                <input name="vol_min" data-default="0" type="number" class="terms-filter-input" value="0">
                <span class="sep"></span>
                <input name="vol_max" data-default="' . esc_attr($default_max) . '" type="number" class="terms-filter-input" value="' . esc_attr($default_max) . '">
            </div>
            <button type="button" class="apply-btn close-dropdown">' . esc_html__('Apply', 'seoaic') . '</button>
        </div>
    </div>';
    }

    private function render_question_filter()
    {
        $questions = [];

        $checkboxes = '';
        foreach ($questions as $value => $label) {
            $checkboxes .= '
        <div class="check">
            <input id="' . $value . '-question" type="checkbox" class="seoaic-checkbox terms-filter-input" value="' . $value . '">
            <label for="' . $value . '-question" class="label-checkbox">' . $label . '</label>
        </div>';
        }

        return '
            <div class="parameter waiting-for-ajax" data-filter="question">
                <div class="filter-name">
                    <div class="selected-values"><span title=""></span>
                        <button type="button" class="dashicons dashicons-no-alt un-check-questions"></button>
                    </div>
                    <div class="label-parameter">' . esc_html__('Question', 'seoaic') . ' <span class="dashicons dashicons-arrow-down-alt2"></span></div>
                </div>
                <div class="dropdown">
                    <label class="drop-title">' . esc_html__('Question', 'seoaic') . '</label>
                    <div class="sort-values checkboxes" id="seoaic_list_checkbox_questions">' . $checkboxes . '</div>
                    <button type="button" class="apply-btn close-dropdown">' . esc_html__('Apply', 'seoaic') . '</button>
                </div>
            </div>';
    }

    private function render_text_filter($label, $filter, $helpText)
    {
        return '
            <div class="parameter" data-filter="' . $filter . '">
                <div class="filter-name">
                    <div class="selected-values"><span title=""></span>
                        <button type="button" class="dashicons dashicons-no-alt"></button>
                    </div>
                    <div class="label-parameter">' . $label . ' <span class="dashicons dashicons-arrow-down-alt2"></span></div>
                </div>
                <div class="dropdown range">
                    <label class="drop-title">' . $label . '</label>
                    <div class="sort-values text">
                        <input name="comma_separated_input" data-default="" type="text" class="terms-filter-input">
                        <div class="help-text">' . $helpText . '</div>
                    </div>
                    <button type="button" class="apply-btn close-dropdown">' . esc_html__('Apply', 'seoaic') . '</button>
                </div>
            </div>';
    }

    private function get_questions_by_code($code)
    {
        $questionWords = [
            "en" => ["who", "what", "which", "whose", "where", "why", "how", "when"],
            "fi" => ["kuka", "mikä", "kenen", "missä", "minne", "mistä", "miksi", "miten", "kuinka", "milloin"],
            "es" => ["quién", "qué", "cuál", "cómo", "de quién", "dónde", "adónde", "de dónde", "por qué", "para qué", "cuánto", "cuándo"],
            "fr" => ["qui", "quoi", "quel", "comment", "où", "d'où", "pourquoi", "combien", "quand"],
            "de" => ["wer", "was", "welcher", "wie", "wessen", "wo", "wohin", "woher", "warum", "wozu", "wieviel", "wann"],
            "pt" => ["quem", "o que", "qual", "como", "de quem", "onde", "para onde", "de onde", "por que", "para que", "quanto", "quando"],
            "it" => ["chi", "che cosa", "quale", "come", "di chi", "dove", "da dove", "perché", "quanto", "quando"],
            "nl" => ["wie", "wat", "welke", "waar", "waarom", "hoe", "wanneer"],
            "sv" => ["vem", "vad", "vilken", "var", "varför", "hur", "när"],
            "da" => ["hvem", "hvad", "hvilken", "hvor", "hvorfor", "hvordan", "hvornår"],
            "no" => ["hvem", "hva", "hvilken", "hvor", "hvorfor", "hvordan", "når"],
            "pl" => ["kto", "co", "który", "czyj", "gdzie", "dlaczego", "jak", "kiedy"],
            "cs" => ["kdo", "co", "který", "čí", "kde", "proč", "jak", "kdy"],
            "ro" => ["cine", "ce", "care", "al cui", "unde", "de ce", "cum", "când"],
            "hu" => ["ki", "mi", "melyik", "kinek", "hol", "miért", "hogyan", "mikor"],
            "bg" => ["кой", "какво", "който", "чий", "къде", "защо", "как", "кога"],
            "hr" => ["tko", "što", "koji", "čiji", "gdje", "zašto", "kako", "kada"],
            "sl" => ["kdo", "kaj", "kateri", "čigav", "kje", "zakaj", "kako", "kdaj"],
            "sk" => ["kto", "čo", "ktorý", "čí", "kde", "prečo", "ako", "kedy"],
            "el" => ["ποιος", "τι", "ποιο", "τίνος", "πού", "γιατί", "πώς", "πότε"],
            "lv" => ["kas", "ko", "kāds", "kur", "kāpēc", "kā", "kad"],
            "lt" => ["kas", "ką", "kuris", "kieno", "kur", "kodėl", "kaip", "kada"],
            "et" => ["kes", "mis", "milline", "kelle", "kus", "miks", "kuidas", "millal"]
        ];

        return $questionWords[$code];
    }
}
