<?php

namespace SEOAIC;

use SeoaicAjaxValidation;

class SeoaicKnowledgeBase
{

    private $seoaic;

    public function __construct($_seoaic)
    {
        $this->seoaic = $_seoaic;
        add_action('wp_ajax_seoaic_get_knowledge_base_list', [$this, 'get_knowledge_base_list']);
        add_action('wp_ajax_seoaic_create_knowledge_base', [$this, 'create_knowledge_base']);
        add_action('wp_ajax_seoaic_save_knowledge_base', [$this, 'save_knowledge_base']);
        add_action('wp_ajax_seoaic_remove_knowledge_base', [$this, 'remove_knowledge_base']);
        add_action('wp_ajax_seoaic_save_knowledge_base_data_sources', [$this, 'save_knowledge_base_data_sources']);
        add_action('wp_ajax_seoaic_get_data_sources_list', [$this, 'get_data_sources_list']);

        add_action('wp_ajax_seoaic_rerun_data_source', [$this, 'rerun_data_source']);
        add_action('wp_ajax_seoaic_remove_data_source', [$this, 'remove_data_source']);
        add_action('wp_ajax_seoaic_train_data_source', [$this, 'train_data_source']);
        add_action('wp_ajax_seoaic_train_data_source_item', [$this, 'train_data_source_item']);
        add_action('wp_ajax_seoaic_train_knowledge_base', [$this, 'train_knowledge_base']);
        add_action('wp_ajax_seoaic_rerun_knowledge_base', [$this, 'rerun_knowledge_base']);
        add_action('wp_ajax_seoaic_get_crawled_pages', [$this, 'get_crawled_pages']);

        add_action('wp_ajax_seoaic_rerun_sources', [$this, 'rerun_sources']);
        add_action('wp_ajax_seoaic_remove_sources', [$this, 'remove_sources']);

        add_action('wp_ajax_seoaic_generate_ai_summary_content', [$this, 'generateAiSummaryContent']);
    }

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

        $_post = wp_unslash($_POST);
        $skipTokens = !empty($_post['skipTokens']);
        $data = [
            'skipTokens' => $skipTokens
        ];

        $result = $this->seoaic->curl->init('api/knowledge/get-list', $data, true, true, true);

        wp_send_json(
            $result
        );
    }

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

        $_post = wp_unslash($_POST);
        $name = sanitize_text_field(trim($_post['seoaicKBFormData']['knowledge-base-name']));
        $description = $_post['seoaicKBFormData']['knowledge-base-description'];

        if (empty($name)) {
            wp_send_json([
                'status' => 'error',
                'message' => 'Name can`t be empty!',
            ]);
        }

        $data = [
            'name' => $name,
            'description' => $description,
        ];

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

        wp_send_json(
            $result
        );
    }

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

        $_post = wp_unslash($_POST);
        $name = sanitize_text_field(trim($_post['seoaicKBFormData']['knowledge-base-name']));
        $description =  sanitize_text_field($_post['seoaicKBFormData']['knowledge-base-description']);
        $id = $_post['knowledge_id'];

        if (empty($name)) {
            wp_send_json([
                'status' => 'alert',
                'message' => 'Name can`t be empty!',
            ]);
        }

        if (empty($id)) {
            wp_send_json([
                'status' => 'alert',
                'message' => 'ID is missing!',
            ]);
        }

        $data = [
            'name' => $name,
            'description' => $description,
        ];

        $result = $this->seoaic->curl->init('api/knowledge/' . $id .'/update-info', $data, true, true, true);

        wp_send_json(
            $result
        );
    }

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

        $__REQUEST = wp_unslash($_REQUEST);
        $id = $__REQUEST['item_id'];

        if (empty($id)) {
            wp_send_json([
                'status' => 'error',
                'message' => 'ID can`t be empty!',
            ]);
        }

        $data = [
            'version' => 5
        ];

        $result = $this->seoaic->curl->init('api/knowledge/' . $id . '/delete', $data, true, true, true);

        wp_send_json(
            $result
        );
    }

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

        $_post = wp_unslash($_POST);
        $data = $_post['dataSources'];
        $filtered_sources = [];

        foreach ($data['sources'] as $key => $source) {
            $maxPages = $source['maxPages'];
            $mode = $source['mode'];
            $entry = [];

            foreach ($source['data'] as $v) {
                $val = trim(stripslashes($v));
                if (!empty($val)) {
                    $entry[] = sanitize_textarea_field($val);
                }
            }

            if (!empty($entry)) {
                $cleaned_data = [
                    'id' => $source['id'],
                    'data' => $entry,
                    'maxPages' => $maxPages,
                    'mode' => $mode,
                ];

                $filtered_sources[] = $cleaned_data;
            }
        }

        $data['sources'] = $filtered_sources;

        $id = $_post['data_id'];

        if (empty($id)) {
            wp_send_json([
                'status' => 'error',
                'message' => 'You have not created a Knowledge Base',
            ]);
        }

        $url = 'api/knowledge/' . $id . '/add-data-source';

        $result = $this->seoaic->curl->init($url, $data, true, true, true);

        wp_send_json(
            $result
        );
    }

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

        $_post = wp_unslash($_POST);
        $id = $_post['item_id'];
        if (empty($id)) {
            wp_send_json([
                'status' => 'error',
                'message' => 'ID is missing!',
            ]);
        }

        $data = [
            'version' => 5
        ];

        $url = 'api/knowledge/' . $id . '/info';

        $result = $this->seoaic->curl->init($url, $data, true, true, true);

        wp_send_json(
            $result
        );
    }

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

        $_post = wp_unslash($_POST);
        $id = $_post['item_id'];
        $limit = !empty($_post['limit']) ? $_post['limit'] : 100;
        $page = !empty($_post['page']) ? $_post['page'] : 1;
        $searchBy = !empty($_post['searchBy']) ? sanitize_text_field($_post['searchBy']) : '';
        $status = !empty($_post['status']) ? sanitize_text_field($_post['status']) : null;

        if (empty($id)) {
            wp_send_json([
                'status' => 'error',
                'message' => 'ID is missing!',
            ]);
        }

        $data = [
            'version' => 5,
            'limit' => $limit,
            'page' => $page,
            'searchBy' => $searchBy ,
            'status' => $status,
        ];

        $url = 'api/knowledge/' . $id . '/get-sources-list';

        $result = $this->seoaic->curl->init($url, $data, true, true, true);

        wp_send_json(
            $result
        );
    }

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

        $_post = wp_unslash($_POST);
        $id = $_post['item_id'];
        $dsId = $_post['data_id'];
        $data = [
            'version' => 5
        ];

        $url = 'api/knowledge/' . $id . '/rerun/' . $dsId;

        $result = $this->seoaic->curl->init($url, $data, true, true, true);

        wp_send_json(
            $result
        );
    }

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

        $_post = wp_unslash($_POST);
        $id = $_post['item_id'];
        $dsId = $_post['data_id'];
        $data = [
            'version' => 5
        ];

        if (empty($id)) {
            wp_send_json([
                'status' => 'error',
                'message' => 'ID is missing!',
            ]);
        }

        $url = 'api/knowledge/' . $id . '/delete-data-source/' . $dsId;

        $result = $this->seoaic->curl->init($url, $data, true, true, true);

        wp_send_json(
            $result
        );
    }

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

        $_post = wp_unslash($_POST);
        $id = $_post['item_id'];
        $dsId = $_post['data_id'];
        $data = [
            'version' => 5
        ];

        if (empty($id)) {
            wp_send_json([
                'status' => 'error',
                'message' => 'ID is missing!',
            ]);
        }

        $url = 'api/knowledge/' . $id . '/training/' . $dsId;

        $result = $this->seoaic->curl->init($url, $data, true, true, true);

        wp_send_json(
            $result
        );
    }

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

        $_post = wp_unslash($_POST);
        $id = $_post['item_id'];
        $data = [
            'version' => 5
        ];

        if (empty($id)) {
            wp_send_json([
                'status' => 'error',
                'message' => 'ID is missing!',
            ]);
        }

        $url = 'api/knowledge/' . $id . '/training';

        $result = $this->seoaic->curl->init($url, $data, true, true, true);

        wp_send_json(
            $result
        );
    }

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

        $_post = wp_unslash($_POST);
        $id = $_post['item_id'];
        $data = [
            'version' => 5
        ];

        if (empty($id)) {
            wp_send_json([
                'status' => 'error',
                'message' => 'ID is missing!',
            ]);
        }

        $url = 'api/knowledge/' . $id . '/rerun';

        $result = $this->seoaic->curl->init($url, $data, true, true, true);

        wp_send_json(
            $result
        );
    }

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

        $_post = wp_unslash($_POST);
        $id = $_post['item_id'];
        $data = $_post['ids'];

        if (empty($id)) {
            wp_send_json([
                'status' => 'error',
                'message' => 'ID is missing!',
            ]);
        }

        $url = 'api/knowledge/' . $id . '/rescan-source';

        $result = $this->seoaic->curl->init($url, $data, true, true, true);

        wp_send_json(
            $result
        );
    }

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

        $_post = wp_unslash($_POST);
        $id = $_post['item_id'];
        $data = $_post['ids'];

        if (empty($id)) {
            wp_send_json([
                'status' => 'error',
                'message' => 'ID is missing!',
            ]);
        }

        $url = 'api/knowledge/' . $id . '/delete-source';

        $result = $this->seoaic->curl->init($url, $data, true, true, true);

        wp_send_json(
            $result
        );
    }

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

        $_post = wp_unslash($_POST);
        $id = $_post['id'];
        $dsId = $_post['dataSourceId'];
        $sourceId = $_post['sourceId'];

        $data = [
            'version' => 5
        ];

        if (empty($id)) {
            wp_send_json([
                'status' => 'error',
                'message' => 'ID is missing!',
            ]);
        }

        $url = 'api/knowledge/' . $id . '/training/' . $dsId . '/' . $sourceId;

        $result = $this->seoaic->curl->init($url, $data, true, true, true);

        wp_send_json(
            $result
        );
    }

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

        $_post = wp_unslash($_POST);
        $ID = $_post['item_id'];
        $dataId = $_post['dataId'];
        $aiSummaryAction = $_post['aiSummaryAction'];
        $aiSummaryContent = $_post['aiSummaryContent'];
        $url = '';
        $postData = [];

        if (empty($ID)) {
            SEOAICAjaxResponse::alert(esc_html__("Knowledge Base ID is missing!", "seoaic"))->wpSend();
        }

        if (empty($dataId)) {
            SEOAICAjaxResponse::alert(esc_html__("Data Source ID is missing!", "seoaic"))->wpSend();
        }

        if (empty($aiSummaryAction)) {
            SEOAICAjaxResponse::alert(esc_html__("AI Summary Action is missing!", "seoaic"))->wpSend();
        }

        switch ($aiSummaryAction) {
            case 'generate':
                $url = "api/knowledge/$ID/$dataId/generate-summary";
                break;

            case 'delete':
                $url = "api/knowledge/$ID/$dataId/update-summary";
                $postData = ['summary' => ''];
                break;

            case 'update':
                if (empty($aiSummaryContent)) {
                    SEOAICAjaxResponse::alert(esc_html__("Content is missing for save action!", "seoaic"))->wpSend();
                }

                $url = "api/knowledge/$ID/$dataId/update-summary";
                $postData = ['summary' => sanitize_textarea_field($aiSummaryContent)];
                break;

            default:
                SEOAICAjaxResponse::alert(esc_html__("Invalid AI Summary Action!", "seoaic"))->wpSend();
        }

        $result = $this->seoaic->curl->init($url, $postData, true, true, true);

        SEOAICAjaxResponse::success()->addFields(['result' => $result, 'action' => $aiSummaryAction])->wpSend();
    }
}