<?php

namespace SEOAIC;

use SEOAIC\repositories\PostRepository;
use SeoaicAjaxValidation;

class SEOAIC_DASHBOARD
{
    private $seoaic;

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

        add_action('wp_ajax_seoaic_dashboard_counters', [$this, 'dashboardCountersAjax']);
        add_action('wp_ajax_seoaic_dashboard_leads_export', [$this, 'dashboardLeadsExport']);
        add_action('wp_ajax_seoaic_dashboard_get_keywords_table', [$this, 'dashboardGetKeywodTable']);
        add_action('wp_ajax_seoaic_dashboard_get_pages_table', [$this, 'dashboardGetPages']);
    }

    public function dashboard_HTML()
    {
        global $SEOAIC, $SEOAIC_OPTIONS;

        $keywordsCount = $SEOAIC->keywords->getAllKeywordsCount();

        $our_website_ID = $SEOAIC->competitors->our_own_website_index();
        $search_terms = get_term_meta($our_website_ID, 'search_terms', true) ?? [];
        $ranked_pages = is_array($search_terms) ? reset($search_terms) : [];
        $ranked_pages = !empty($ranked_pages['positions']['count']) ? $ranked_pages['positions']['count'] : 0;
        $getPostCountsByMonth = $this->getPostCountsByMonth();

        $pages_html = $keywords = '';

        if (SEOAIC_SETTINGS::isGSCIntegrated()) {
            $googleGraph = '<div id="chart_pruning_gsc" style="max-width: 100%"></div>';
            $rankingGraph = '<div id="seoaic_rankings_chart" style="max-width: 100%"></div>';
        } else {
            $pages_html = $keywords = '<a href="" class="integrate-gsc integrate-gsc-modal">'. esc_html('Integrate site with Google', 'seoaic') .'</a>';
            $googleGraph = '<div class="blur"><img src="'. esc_url(SEOAIC_URL . 'assets/img/google-graph.jpg') . '" >' . $pages_html . '</div>';
            $rankingGraph = '<div class="blur"><img src="'. esc_url(SEOAIC_URL . 'assets/img/ranking-graph.jpg') . '" >' . $pages_html . '</div>';
        }

        $html = '
        <div class="col dashboard-ranking-graph tabs-wrapper">
            <div class="inner">' . $googleGraph . '</div>
        </div>';

        $html .= '
        <div class="col dashboard-ranking-graph tabs-wrapper">
            <div class="inner">' . $rankingGraph . '</div>
        </div>';

        $html .= '
        <div class="col number-value">
            <div class="inner">
                <div class="value">' . esc_html($keywordsCount) . '</div>
                <div class="title">' . esc_html__('Keywords generated', 'seoaic') . '</div>
            </div>
        </div>

        <div class="col number-value">
            <div class="inner">
                <div class="value">' . esc_html(array_sum($getPostCountsByMonth['posts_by_month'])) . '</div>
                <div class="title">' . esc_html__('Content generated', 'seoaic') . '</div>
            </div>
        </div>

        <div class="col number-value">
            <div class="inner">
                <div class="value seoaic-dashboard-competitors-count">
                    <span class="loader-ellipsis small"></span>
                </div>
                <div class="title">' . esc_html__('Competitors tracked', 'seoaic') . '</div>
            </div>
        </div>

        <div class="col number-value">
            <div class="inner">
                <div class="value">' . esc_html($ranked_pages) . '</div>
                <div class="title">' . esc_html__('Ranked pages', 'seoaic') . '</div>
            </div>
        </div>';

        $html .= '
        <div class="col dashboard-ranking-graph tabs-wrapper">
            <div class="inner">
                <div id="seoaic_created_post_chart" data-charts="'.esc_attr(json_encode($getPostCountsByMonth['posts_by_month'])).'" style="max-width: 100%"></div>
            </div>
        </div>';

        $html .= '
        <div class="col dashboard-ranking-graph tabs-wrapper">
            <div class="inner">
                <div id="seoaic_posts_by_statusses_chart" data-charts="'.esc_attr(json_encode($getPostCountsByMonth['posts_by_status'])).'" style="max-width: 100%"></div>
            </div>
        </div>';

        $html .= '
        <div class="col table-list two-columns">
            <div class="inner">
                <div class="title">' . esc_html__('Top keywords', 'seoaic') . '</div>
                <div class="table">
                    <div class="flex-table top-keywords-dashboard">
                        <div class="row-line heading">
                            <div class="keyword">' . esc_html__('Keyword', 'seoaic') . '
                                <span class="sorting"></span>
                            </div>
                            <div class="impressions">' . esc_html__('Impressions', 'seoaic') . '<span class="sorting"></span></div>
                            <div class="clicks" data-order="DESC">' . esc_html__('Clicks', 'seoaic') . '<span class="sorting"></span></div>
                            <div class="rank">' . esc_html__('Rank', 'seoaic') . '<span class="sorting"></span></div>
                            <div class="ctr">' . esc_html__('CTR', 'seoaic') . '<span class="sorting"></span></div>
                        </div>
                    </div>
                    <div class="flex-table top-keywords-dashboard output-results">
                        ' . $keywords . '
                    </div>
                </div>
            </div>
        </div>';

        $html .=
            '<div class="col table-list three-columns">
            <div class="inner">
                <div class="title">' . esc_html__('Top pages', 'seoaic') . '</div>
                <div class="table">
                    <div class="flex-table top-pages-dashboard">
                        <div class="row-line heading">
                            <div class="page">' . esc_html__('Page', 'seoaic') . '</div>
                            <div class="impressions">' . esc_html__('Impressions', 'seoaic') . '<span class="sorting"></span></div>
                            <div class="clicks" data-order="DESC">' . esc_html__('Clicks', 'seoaic') . '<span class="sorting"></span></div>
                            <div class="rank">' . esc_html__('Rank', 'seoaic') . '<span class="sorting"></span></div>
                            <div class="ctr">' . esc_html__('CTR', 'seoaic') . '<span class="sorting"></span></div>
                        </div>
                    </div>
                    <div class="flex-table top-pages-dashboard output-results">
                        ' . $pages_html . '
                    </div>
                </div>
            </div>
        </div>';

        $html .= '
        <div class="seoaic-dashboard-leads-stats">
            <div class="row full-width">
            ' . $SEOAIC->leadsAddon->makeStatsHTML() . '
            </div>
        </div>
        ';

        return $html;
    }

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

        $params = [
            'page' => 1,
            'limit' => 100,
            'order' => 'DESC',
            'orderBy' => 'clicks',
            'dateFrom' => date('Y-m-d', strtotime('-33 days')),
            'dateTo' => date('Y-m-d', strtotime('-3 days')),
        ];

        $result = $this->seoaic->curl->init('api/pruning/google/inspection/keywords', $params, true, true, true);

        if (!empty($result['keywords'])) {
            $rowsData = $this->makeRankingKeywordRows($result['keywords']);
        }

        SEOAICAjaxResponse::success()->addFields([
            'data' => [
                'rows' => !empty($rowsData) ? $rowsData : '<div class="error-info">' . esc_html__('There are no data', 'seoaic') . '</div>',
            ],
        ])->wpSend();
    }

    public function makeRankingKeywordRows($rows)
    {
        ob_start();
        foreach ($rows as $key => $row) {
            $title = $row['title'];
            $impressions = intval($row['impressions']);
            $clicks = intval($row['clicks']);
            $position = floor($row['position']);
            $ctr = round($row['ctr'] * 100, 2);
            ?>
            <div class="row-line">
                <div class="keyword"><?php echo esc_html($title); ?></div>
                <div class="impressions"><?php echo esc_html($impressions); ?></div>
                <div class="clicks"><?php echo esc_html($clicks); ?></div>
                <div class="rank"><?php echo esc_html($position); ?></div>
                <div class="ctr"><?php esc_html_e($ctr); ?>%</div>
            </div>
            <?php
        }

        $html = ob_get_clean();

        return $html;
    }

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

        global $SEOAIC;

        $SEOAIC->content_improvement->checkIntegratedSiteWithGoogle();

        $params = [
            'page' => 1,
            'limit' => 100,
            'order' => 'DESC',
            'orderBy' => 'clicks',
            'dateFrom' => date('Y-m-d', strtotime('-33 days')),
            'dateTo' => date('Y-m-d', strtotime('-3 days')),
        ];

        $result = $this->seoaic->curl->init('api/pruning/google/inspection', $params, true, true, true);

        if (!empty($result['links'])) {
            $rowsData = $this->makeContentImprovementRows($result['links']);
        }

        SEOAICAjaxResponse::success()->addFields([
            'data' => [
                'rows' => !empty($rowsData) ? $rowsData : '<div class="error-info">' . esc_html__('There are no data', 'seoaic') . '</div>',
            ],
        ])->wpSend();
    }

    public function makeContentImprovementRows($rows)
    {
        $postsRepository = new PostRepository();

        ob_start();
        foreach ($rows as $key => $row) {
            $link = $row['url'];
            $ID = url_to_postid($link);
            $title = get_the_title($ID);
            $impressions = intval($row['impressions']);
            $clicks = intval($row['clicks']);
            $position = floor($row['position']);
            $ctr = round($row['ctr'] * 100, 2);

            if (empty($title)) {
                $path = wp_parse_url($link, PHP_URL_PATH);
                $pageData = $postsRepository->check_page_type_with_regex_and_message($path);
                $title = $pageData['content'];
            }
            ?>
            <div class="row-line">
                <div class="page">
                    <a href="<?php echo esc_url($link);?>" target="_blank"><?php echo esc_html($title);?></a>
                </div>
                <div class="impressions"><?php esc_html_e($impressions) ?></div>
                <div class="clicks"><?php esc_html_e($clicks) ?></div>
                <div class="rank"><?php esc_html_e($position) ?></div>
                <div class="ctr"><?php esc_html_e($ctr) ?>%</div>
            </div>
            <?php
        }

        $html = ob_get_clean();

        return  $html;
    }

    public function getPostCountsByMonth()
    {
        global $SEOAIC;

        $results = $SEOAIC->posts->get_post_statuses_with_dates(false);
        $posts_by_month = $this->count_posts_by_month($results);
        $posts_by_status = $this->count_posts_by_month_and_status($results);

        return [
            'posts_by_month' => $posts_by_month,
            'posts_by_status' => $posts_by_status,
        ];
    }

    public function count_posts_by_month($posts) {
        $post_counts = [];

        if (is_array($posts) && count($posts)) {
            foreach ($posts as $post) {
                $month_key = date('Y-m', strtotime($post->post_date));

                if (!isset($post_counts[$month_key])) {
                    $post_counts[$month_key] = 0;
                }

                $post_counts[$month_key]++;
            }
        }

        return $post_counts;
    }

    public function count_posts_by_month_and_status($posts) {
        $post_counts = [];

        if (is_array($posts) && count($posts)) {
            foreach ($posts as $post) {
                $month_key = date('Y-m', strtotime($post->post_date));
                $status = $post->post_status;

                if (!isset($post_counts[$month_key])) {
                    $post_counts[$month_key] = [];
                }

                if (!isset($post_counts[$month_key][$status])) {
                    $post_counts[$month_key][$status] = 0;
                }

                $post_counts[$month_key][$status]++;
            }
        }

        return $post_counts;
    }

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

        $__REQUEST = wp_unslash($_REQUEST);
        $count = 0;

        switch ($__REQUEST['type']) {
            case 'competitors':
                $competitors = $this->seoaic->competitors->get_competitors();
                $count = !empty($competitors) && $competitors > 0 ? count($competitors) - 1 : 0;
                break;

            default:
                # code...
                break;
        }

        SEOAICAjaxResponse::success()->addFields([
            'data' => [
                'count' => $count,
            ],
        ])->wpSend();
    }

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

        $__REQUEST = wp_unslash($_REQUEST);

        $this->seoaic->leadsAddon->exportLeads($__REQUEST);
    }
}
