<?php

namespace SEOAIC\rest_api;

use Exception;
use SEOAIC\helpers\SEOPluginsHelper;
use SEOAIC\repositories\InteractiveArticleAddonRepository;
use SEOAIC\rest_api\http_resources\Result;
use SEOAIC\SeoaicContentImprovement;
use WP_REST_Request;
use WP_REST_Response;

class EditorSidebar
{
    private $seoaic;

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

        add_action('rest_api_init', function () {
            register_rest_route('seoaic/v1', '/sidebar/(?P<post_id>\d+)/top-keywords', [
                'methods' => 'GET',
                'callback' => [$this, 'getTopPageKeywordsWithStats'],
                'permission_callback' => function () {
                    return current_user_can('edit_posts');
                },
                'args' => [
                    'post_id' => [
                        'validate_callback' => function($param, $request, $key) {
                            return is_numeric($param);
                        }
                    ],
                    'count' => [
                        'validate_callback' => function($param, $request, $key) {
                            return is_numeric($param);
                        }
                    ],
                ],
            ]);

            // register_rest_route('seoaic/v1', '/sidebar/top-competitors-ranking/(?P<post_id>\d+)/(?P<keyword>[\p{L}\p{N}\-\.%20]+)', [
            //     'methods' => 'GET',
            //     'callback' => [$this, 'getTopCompetitorsRanking'],
            //     'permission_callback' => function () {
            //         return current_user_can('edit_posts');
            //     },
            //     'args' => [
            //         'post_id' => [
            //             'validate_callback' => function($param) {
            //                 return is_numeric($param);
            //             }
            //         ],
            //         'keyword' => [
            //             'validate_callback' => function($param) {
            //                 return is_string($param);
            //             }
            //         ],
            //     ],
            // ]);

            register_rest_route('seoaic/v1', '/sidebar/(?P<post_id>\d+)/competitor-comparison', [
                'methods' => 'GET',
                'callback' => [$this, 'getCompetitorComparison'],
                'permission_callback' => function () {
                    return current_user_can('edit_posts');
                },
                'args' => [
                    'post_id' => [
                        'validate_callback' => function($param) {
                            return is_numeric($param);
                        }
                    ],
                    'keyword' => [
                        'validate_callback' => function($param) {
                            return is_string($param);
                        }
                    ],
                ],
            ]);

            register_rest_route('seoaic/v1', '/sidebar/(?P<post_id>\d+)/ai-suggestions', [
                'methods' => 'GET',
                'callback' => [$this, 'getAISuggestions'],
                'permission_callback' => function () {
                    return current_user_can('edit_posts');
                },
                'args' => [
                    'post_id' => [
                        'validate_callback' => function($param) {
                            return is_numeric($param);
                        }
                    ],
                    'keyword' => [
                        'validate_callback' => function($param) {
                            return is_string($param);
                        }
                    ],
                    'page_url' => [
                        'validate_callback' => function($param) {
                            return is_string($param);
                        }
                    ],
                    'competitor_page_url' => [
                        'validate_callback' => function($param) {
                            return is_string($param);
                        }
                    ],
                ],
            ]);

            // register_rest_route('seoaic/v1', '/sidebar/competitor-analysis/(?P<post_id>\d+)/(?P<keyword>[\p{L}\p{N}\-\.%20]+)/(?P<page_url>.+)', [
            //     'methods' => 'GET',
            //     'callback' => [$this, 'getCompetitorAnalysis'],
            //     'permission_callback' => function () {
            //         return current_user_can('edit_posts');
            //     },
            //     'args' => array(
            //         'post_id' => array(
            //             'validate_callback' => function($param) {
            //                 return is_numeric($param);
            //             }
            //         ),
            //         'keyword' => array(
            //             'validate_callback' => function($param) {
            //                 return is_string($param);
            //             }
            //         ),
            //         'page_url' => array(
            //             'validate_callback' => function($param) {
            //                 return filter_var($param, FILTER_VALIDATE_URL) !== false;
            //             }
            //         ),
            //     ),
            // ]);

            register_rest_route('seoaic/v1', '/sidebar/(?P<post_id>\d+)/top-competitors-analysis', [
                'methods' => 'GET',
                'callback' => [$this, 'getTopCompetitorAnalysis'],
                'permission_callback' => function () {
                    return current_user_can('edit_posts');
                },
                'args' => array(
                    'post_id' => array(
                        'validate_callback' => function($param) {
                            return is_numeric($param);
                        }
                    ),
                    'keyword' => array(
                        'validate_callback' => function($param) {
                            return is_string($param);
                        }
                    ),
                ),
            ]);


            register_rest_route('seoaic/v1', '/sidebar/(?P<post_id>\d+)/content-improvement-ideas', [
                'methods' => 'GET',
                'callback' => [$this, 'getContentImprovementInfo'],
                'permission_callback' => function () {
                    return current_user_can('edit_posts');
                },
                'args' => array(
                    'post_id' => array(
                        'validate_callback' => function($param) {
                            return is_numeric($param);
                        }
                    ),
                ),
            ]);

            register_rest_route('seoaic/v1', '/sidebar/(?P<post_id>\d+)/content-improvement-ideas/status', [
                'methods' => 'GET',
                'callback' => [$this, 'getContentImprovementScanStatus'],
                'permission_callback' => function () {
                    return current_user_can('edit_posts');
                },
                'args' => array(
                    'post_id' => array(
                        'validate_callback' => function($param) {
                            return is_numeric($param);
                        }
                    ),
                ),
            ]);

            register_rest_route('seoaic/v1', '/sidebar/(?P<post_id>\d+)/content-improvement-ideas/generate', [
                'methods' => 'POST',
                'callback' => [$this, 'generateContentImprovementText'],
                'permission_callback' => function () {
                    return current_user_can('edit_posts');
                },
                'args' => array(
                    'post_id' => array(
                        'validate_callback' => function($param) {
                            return is_numeric($param);
                        }
                    ),
                    'index_suggestion' => array(
                        'validate_callback' => function($param) {
                            return is_numeric($param);
                        }
                    ),
                    'type' => array(
                        'validate_callback' => function($param) {
                            return is_string($param);
                        }
                    ),
                ),
            ]);

            register_rest_route('seoaic/v1', '/sidebar/(?P<post_id>\d+)/internal-links', [
                'methods' => 'GET',
                'callback' => [$this, 'getInternalLinks'],
                'permission_callback' => function () {
                    return current_user_can('edit_posts');
                },
                'args' => array(
                    'post_id' => array(
                        'validate_callback' => function($param) {
                            return is_numeric($param);
                        }
                    ),
                ),
            ]);

            register_rest_route('seoaic/v1', '/sidebar/(?P<post_id>\d+)/meta-description', [
                'methods' => 'GET',
                'callback' => [$this, 'getMetaDescription'],
                'permission_callback' => function () {
                    return current_user_can('edit_posts');
                },
                'args' => array(
                    'post_id' => array(
                        'validate_callback' => function($param) {
                            return is_numeric($param);
                        }
                    ),
                ),
            ]);

            register_rest_route('seoaic/v1', '/sidebar/(?P<post_id>\d+)/meta-description', [
                'methods' => 'PUT',
                'callback' => [$this, 'setMetaDescription'],
                'permission_callback' => function () {
                    return current_user_can('edit_posts');
                },
                'args' => array(
                    'post_id' => array(
                        'validate_callback' => function($param) {
                            return is_numeric($param);
                        }
                    ),
                ),
            ]);

            register_rest_route('seoaic/v1', '/sidebar/(?P<post_id>\d+)/interactive-article-stats', [
                'methods' => 'GET',
                'callback' => [$this, 'getInteractiveArticleStats'],
                'permission_callback' => function () {
                    return current_user_can('edit_posts');
                },
                'args' => [
                    'post_id' => [
                        'validate_callback' => function($param) {
                            return is_numeric($param);
                        }
                    ],
                ],
            ]);
        });
    }

    public function getTopCompetitorAnalysis(WP_REST_Request $request)
    {
        global $SEOAIC;

        $keyword = $request['keyword'];
        $postID = intval($request['post_id']);
        $competitorsData = $SEOAIC->content_improvement->getKeywordCompetitorsREST($keyword, $postID);
        // error_log('competitorsData '.print_r($competitorsData, true));
        $topCompetitorsData = [];

        if ($competitorsData) {
            foreach ($competitorsData as $competitor) {
                $pageURL = $competitor['url'];
                $domain = $competitor['domain'];

                $analysisData = $SEOAIC->content_improvement->getCompetitorAnalysisREST($postID, $keyword, $pageURL);
                // error_log(' - analysisData '.print_r($analysisData, true));

                $wordscount = '-';
                $h2Count = '-';

                if (!empty($analysisData['content_analysis']['words'])) {
                    $wordscount = $analysisData['content_analysis']['words'];
                }

                if (
                    !empty($analysisData['on_page_seo']['meta']['htags']['h2'])
                    && is_array($analysisData['on_page_seo']['meta']['htags']['h2'])
                ) {
                    $h2Count = count($analysisData['on_page_seo']['meta']['htags']['h2']);
                }

                $topCompetitorsData[] = [
                    'domain' => $domain,
                    'pageURL' => $pageURL,
                    'wordscount' => $wordscount,
                    'h2' => $h2Count,
                ];
            }

        } else {
            return new WP_REST_Response(Result::success(__FUNCTION__, esc_html__('No competitors data', 'seoaic'), $topCompetitorsData));
        }

        return new WP_REST_Response(Result::success(__FUNCTION__, esc_html__('OK', 'seoaic'), $topCompetitorsData));
    }

    public function getTopPageKeywordsWithStats(WP_REST_Request $request)
    {
        $post_id = $request->get_param('post_id');
        $countParam = $request->get_param('count');
        $count = $countParam ? $countParam : 10;
        $keywords = [];
        $permalink = get_permalink($post_id);
        // $permalink = 'https://wpseoai.com/'; // TODO: hardcode

        if (!$permalink) {
            return new WP_REST_Response(Result::success('getPageKeywordsWithStats', esc_html__('OK', 'seoaic'), $keywords));
        }

        $args = [
            'limit'     => $count,
            'orderBy'   => 'clicks',
            'dateFrom'  => wp_date('Y-m', strtotime('-3 months')),
            'dateTo'    => wp_date('Y-m', strtotime('-3 days')),
            'search'    => [$permalink],
        ];

        $result = $this->seoaic->content_improvement->getPageKeywordsWithStats($args);

        if (
            !empty($result)
            && !empty($result['keywords'])
            && is_array($result['keywords'])
        ) {
            $keywords = $result['keywords'];

            usort($keywords, function($a, $b) {
                return
                    ($b['clicks'] <=> $a['clicks']) * 100 + // desc
                    // ($b['position'] <=> $a['position']) * 10 + // desc
                    ($b['impressions'] <=> $a['impressions']); // desc
            });
        }

        return new WP_REST_Response(Result::success('getPageKeywordsWithStats', esc_html__('OK', 'seoaic'), $keywords));
    }

    // public function getTopCompetitorsRanking($request)
    // {
    //     global $SEOAIC;

    //     $keyword = $request['keyword'];
    //     $post_id = $request['post_id'];
    //     $keyword_data = $SEOAIC->content_improvement->getKeywordCompetitorsREST($keyword, $post_id);
    //     $is_valid = $keyword_data ? 'success' : 'keyword_or_post_not_exist';
    //     $result = $keyword_data ? Result::success(__FUNCTION__, esc_html__($is_valid, 'seoaic'), $keyword_data) : Result::error(__FUNCTION__, esc_html__($is_valid));

    //     return new WP_REST_Response($result);
    // }

    // public function getCompetitorAnalysis($request)
    // {
    //     global $SEOAIC;

    //     $keyword = $request['keyword'];
    //     $post_id = $request['post_id'];
    //     $page_url = $request['page_url'];
    //     $analysis_data = $SEOAIC->content_improvement->getCompetitorAnalysisREST($post_id, $keyword, $page_url);
    //     $is_valid = $analysis_data ? 'success' : 'keyword_or_post_or_url_not_exist';
    //     $result = $analysis_data ? Result::success(__FUNCTION__, esc_html__($is_valid, 'seoaic'), $analysis_data) : Result::error(__FUNCTION__, esc_html__($is_valid));

    //     return new WP_REST_Response($result);
    // }

    public function getCompetitorComparison(WP_REST_Request $request)
    {
        if (empty($request['keyword'])) {
            return new WP_REST_Response(Result::error(__FUNCTION__, esc_html__('Keyword is required', 'seoaic')));
        }

        if (empty($request['post_id'])) {
            return new WP_REST_Response(Result::error(__FUNCTION__, esc_html__('Post ID is required', 'seoaic')));
        }

        if (empty($request['page_url'])) {
            return new WP_REST_Response(Result::error(__FUNCTION__, esc_html__('Page URL is required', 'seoaic')));
        }

        return new WP_REST_Response(Result::success(__FUNCTION__, esc_html__('OK', 'seoaic'), [
            'html' => $this->seoaic->content_improvement->pageAnalyzeHTML(
                $this->seoaic->content_improvement->setupPageAnalyze(
                    $request['page_url'],
                    $request['keyword'],
                    $request['post_id']
                ),
                $request['page_url']
            ),
        ]));
    }

    public function getAISuggestions(WP_REST_Request $request)
    {
        if (empty($request['keyword'])) {
            return new WP_REST_Response(Result::error(__FUNCTION__, esc_html__('Keyword is required', 'seoaic')));
        }

        if (empty($request['post_id'])) {
            return new WP_REST_Response(Result::error(__FUNCTION__, esc_html__('Post ID is required', 'seoaic')));
        }

        if (empty($request['page_url'])) {
            return new WP_REST_Response(Result::error(__FUNCTION__, esc_html__('Page URL is required', 'seoaic')));
        }
        if (empty($request['competitor_page_url'])) {
            return new WP_REST_Response(Result::error(__FUNCTION__, esc_html__('Competitor page URL is required', 'seoaic')));
        }

        return new WP_REST_Response(Result::success(__FUNCTION__, esc_html__('OK', 'seoaic'), [
            'html' => $this->seoaic->content_improvement->AISuggestionsHTML(
                $this->seoaic->content_improvement->setupGPTSuggestions(
                    $request['post_id'],
                    $request['keyword'],
                    $request['competitor_page_url'],
                    $request['page_url']
                )
            ),
        ]));
    }

    public function getContentImprovementInfo(WP_REST_Request $request)
    {
        if (empty($request['post_id'])) {
            return new WP_REST_Response(Result::error(__FUNCTION__, esc_html__('Post ID is required', 'seoaic')));
        }

        $improvementIdeas = get_post_meta($request['post_id'], SeoaicContentImprovement::GOOGLE_POST_IMPROVEMENT_IDEAS, true);

        $intents = !empty($improvementIdeas['intents']['main']) ? $improvementIdeas['intents']['main'] : '';
        $audience = !empty($improvementIdeas['audience']) ? $improvementIdeas['audience'] : '';
        $suggestions = !empty($improvementIdeas['suggestions']) ? $improvementIdeas['suggestions'] : '';
        $isScanning = !!get_post_meta($request['post_id'], SeoaicContentImprovement::POST_CONTENT_IS_SCANNIG, true);

        return new WP_REST_Response(Result::success(__FUNCTION__, esc_html__('OK', 'seoaic'), [
            'intents' => $intents,
            'audience' => $audience,
            'suggestions' => $suggestions,
            'isScanning' => $isScanning,
        ]));
    }

    public function getContentImprovementScanStatus(WP_REST_Request $request)
    {
        if (empty($request['post_id'])) {
            return new WP_REST_Response(Result::error(__FUNCTION__, esc_html__('Post ID is required', 'seoaic')));
        }

        $isScanning = !!get_post_meta($request['post_id'], SeoaicContentImprovement::POST_CONTENT_IS_SCANNIG, true);

        if ($isScanning) {
            $this->setDataImprovementsLoadJob([$request['post_id']]);
        }

        return new WP_REST_Response(Result::success(__FUNCTION__, esc_html__('OK', 'seoaic'), [
            'isScanning' => $isScanning
        ]));
    }

    public function setDataImprovementsLoadJob($ids) {
        $data = ['page_ids' => $ids];

        $status = $this->seoaic->curl->init('/api/ai/pages/analyze/status', $data, true, true, true);
        $failed_ids = $status['failed'] ?? [];
        $pending_ids = $status['pending'] ?? [];
        $completed_ids = $status['completed'] ?? [];
        $loaded = [];

        if (array_intersect($data['page_ids'], $completed_ids)) {
            $data = ['page_ids' => $completed_ids];
            $response = $this->seoaic->curl->init('/api/ai/pages/analyze/content', $data, true, true, true);
            foreach ($response as $value) {
                if (!empty($value['pageId'])) {
                    $pageId = $value['pageId'];
                    $contentData = $value['content'] ?? '';
                    $contentKeywords = $value['params']['keywords'] ?? '';
                    update_post_meta($pageId, SeoaicContentImprovement::GOOGLE_POST_IMPROVEMENT_IDEAS, $contentData);
                    update_post_meta($pageId, SeoaicContentImprovement::QUERY_GOOGLE_FIELD, $contentKeywords);
                    update_post_meta($pageId, SeoaicContentImprovement::POST_CONTENT_IS_SCANNIG, '0');
                    $loaded[] = $pageId;
                }
            }
        }

        foreach ($failed_ids as $id) {
            update_post_meta($id, SeoaicContentImprovement::GOOGLE_POST_IMPROVEMENT_IDEAS, 'failed');
            update_post_meta($pageId, SeoaicContentImprovement::POST_CONTENT_IS_SCANNIG, '0');
            $loaded[] = [$id => 'failed'];
        }

        foreach ($data['page_ids'] as $id) {
            $loading_status = get_post_meta($id, SeoaicContentImprovement::GOOGLE_POST_IMPROVEMENT_IDEAS, true);
            if (
                !in_array($id, $pending_ids) &&
                !in_array($id, $completed_ids) &&
                !in_array($id, $failed_ids) &&
                $loading_status === 'loading') {

                update_post_meta($id, SeoaicContentImprovement::GOOGLE_POST_IMPROVEMENT_IDEAS, 'failed');
                update_post_meta($pageId, SeoaicContentImprovement::POST_CONTENT_IS_SCANNIG, '0');
                $loaded[] = [$id => 'failed'];
            }
        }

        return $loaded;
    }

    public function generateContentImprovementText(WP_REST_Request $request)
    {
        $data = [
            'post_id'           => $request['post_id'],
            'index_suggestion'  => $request['index_suggestion'],
            'type'              => $request['type'],
        ];

        try {
            $result = $this->seoaic->content_improvement->generateImprovementText($data);

            return new WP_REST_Response(Result::success(__FUNCTION__, esc_html__('OK', 'seoaic'), $result));

        } catch (Exception $e) {
            return new WP_REST_Response(Result::error(__FUNCTION__, esc_html__('Error', 'seoaic')));
        }
    }

    public function getInternalLinks(WP_REST_Request $request)
    {
        $postId = $request['post_id'];

        if (!get_post_status($postId)) {
            return new WP_REST_Response(Result::error(__FUNCTION__, esc_html__('Post not found.', 'seoaic')));
        }

        $internalLinks = $this->seoaic->internal_links->forIdea($postId, 100, false)->toOptionsDataArray();

        return new WP_REST_Response(Result::success(__FUNCTION__, esc_html__('OK', 'seoaic'), ['internal_links' => $internalLinks]));
    }

    public function getMetaDescription(WP_REST_Request $request)
    {
        $postId = $request['post_id'];

        if (!get_post_status($postId)) {
            return new WP_REST_Response(Result::error(__FUNCTION__, esc_html__('Post not found.', 'seoaic')));
        }

        $seoPlugin = SEOPluginsHelper::getAvailableSEOPlugin();

        if (!$seoPlugin) {
            return new WP_REST_Response(Result::error(__FUNCTION__, esc_html__("Plugins for setting Meta Description not found.", "")));
        }

        $description = $seoPlugin->getDescription($postId);

        return new WP_REST_Response(Result::success(__FUNCTION__, esc_html__('OK', 'seoaic'), ['meta_description' => $description]));
    }

    public function setMetaDescription(WP_REST_Request $request)
    {
        $postId = $request['post_id'];
        $description = $request['description'];

        if (!get_post_status($postId)) {
            return new WP_REST_Response(Result::error(__FUNCTION__, esc_html__('Post not found.', 'seoaic')));
        }

        try {
            $seoPlugins = SEOPluginsHelper::getAllSEOPlugins();
            $data = [];

            if (!empty($seoPlugins)) {
                foreach ($seoPlugins as $seoPlugin) {
                    $pluginId = $seoPlugin->getPluginID();

                    $result = $seoPlugin->setDescription($postId, $description);
                    $data[$pluginId] = !!$result;
                }

                if (in_array(true, array_values($data))) {
                    return new WP_REST_Response(Result::success(__FUNCTION__, esc_html__('Saved', 'seoaic'), [
                        'results' => $data,
                    ]));
                }
            }

            return new WP_REST_Response(Result::error(__FUNCTION__, esc_html__("Not saved.", "seoaic")));

        } catch (Exception $e) {
            return new WP_REST_Response(Result::error(__FUNCTION__, esc_html__("Error:", "seoaic") . ' ' . $e->getMessage()));
        }
    }

    public function getInteractiveArticleStats(WP_REST_Request $request)
    {
        $postId = $request->get_param('post_id');
        $repo = new InteractiveArticleAddonRepository();

        $sessions = $repo->getByPostId($postId);
        $stats = [];

        if (!empty($sessions)) {
            foreach ($sessions as $session) {
                if (empty($session->data)) {
                    continue;
                }

                $sessionData = json_decode($session->data);

                foreach ($sessionData as $sessionStat) {
                    if (!isset($stats[$sessionStat->id])) {
                        $stats[$sessionStat->id] = 0;
                    }

                    $stats[$sessionStat->id] += 1;
                }
            }
        }

        $data = [
            'views'             => count($sessions),
            'sessions_stats'    => $stats,
        ];

        return new WP_REST_Response(Result::success(__FUNCTION__, esc_html__('OK', 'seoaic'), $data));
    }
}
