<?php

    use SEOAIC\SEOAIC;

    if ( ! current_user_can( 'seoaic_edit_plugin' ) ) {
        return;
    }

    $get = wp_unslash($_GET); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    if ( isset( $get['settings-updated'] ) ) {
        add_settings_error( 'seoaic_messages', 'seoaic_message', esc_html_e( 'Settings Saved', 'mdsf' ), 'updated' );
    }

    settings_errors( 'seoaic_messages' );

    global $SEOAIC, $SEOAIC_OPTIONS;


    function SEOAIC_postsPagination($query) {
        $get = wp_unslash($_GET);  // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $paged = isset($get['paged']) && !empty(wp_unslash($get['paged'])) ? absint($get['paged']) : 1;
        ?>
        <div class="seoaic-pagination pagination">
            <?php
            $big = 999999999;
            $pagination_links = paginate_links([
                'base'         => str_replace([$big, '&#038;'], ['%#%', '&'], get_pagenum_link($big)),
                'total'        => $query->max_num_pages,
                'current'      => max(1, $paged),
                'format'       => '?paged=%#%',
                'show_all'     => false,
                'type'         => 'plain',
                'end_size'     => 2,
                'mid_size'     => 1,
                'prev_next'    => true,
                'prev_text'    => sprintf('<i></i> %1$s', esc_html__('Prev', 'seoaic')),
                'next_text'    => sprintf('%1$s <i></i>', esc_html__('Next', 'seoaic')),
                'add_args'     => false,
                'add_fragment' => '',
            ]);

            if ( $pagination_links ) {
                echo wp_kses_post( $pagination_links );
            }

            ?>
        </div>
        <?php
    }

    function SEOAIC_makeDateQuery() {
        $get = wp_unslash($_GET);  // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $date_query = [];

        if (
            !empty($get['seoaic_publ_datefrom'])
            && SEOAIC_isValidDate(urldecode($get['seoaic_publ_datefrom']))
        ) {
            $date_query['after'] = urldecode($get['seoaic_publ_datefrom']);
        }
        if (
            !empty($get['seoaic_publ_dateto'])
            && SEOAIC_isValidDate(urldecode($get['seoaic_publ_dateto']))
        ) {
            $date_query['before'] = urldecode($get['seoaic_publ_dateto']) . ' 23:59:59';
        }
        if (!empty($date_query)) {
            $date_query['inclusive'] = true;
        }

        return [$date_query];
    }

    function SEOAIC_isValidDate($dateString='') {
        return (bool)strtotime($dateString);
    }

    function SEOAIC_countPostsByLang($langs) {
        global $SEOAIC;

        return array_combine(
            $langs,
            array_map(
                function($item) use ($SEOAIC) {
                    return $SEOAIC->multilang->countPostsMapLang(
                        $item,
                        function () {
                            return SEOAIC_makeDateQuery();
                        },
                        function (&$args) {
                            SEOAIC_addTitleQuery($args);
                            SEOAIC_changeAttr($args);
                        }
                    );
                },
                $langs
            )
        );
    }

    function SEOAIC_addTitleQuery(&$args) {
        $get = wp_unslash($_GET);  // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        if (!empty($get['seoaic_title'])) {
            $args['post_title_like'] = $get['seoaic_title'];
        }
    }

    function SEOAIC_changeAttr(&$args) {
        $get = wp_unslash($_GET); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $active_post = !empty($get['posts']) ? sanitize_text_field($get['posts']) : '';
        $args['post_status'] = 'publish';
        $args['post_type'] = seoaic_get_post_types();
        unset($args['meta_key'], $args['meta_value']);

        if (!empty($active_post)) {
            if ($active_post === 'not-seoai') {
                $args['meta_query'][] = [
                    'relation' => 'AND',
                    [
                        'key' => 'seoaic_posted',
                        'compare' => 'NOT EXISTS',
                    ],
                ];
            }

            if ($active_post === 'seoai') {
                $args['meta_query'][] = [
                    'relation' => 'AND',
                    [
                        'key' => 'seoaic_posted',
                        'value' => 1,
                        'compare' => '='
                    ],
                ];
            }
        }
    }

    $available_per_page_options = [10, 20, 50, 100, 200, 500, 1000];
    $selected_per_page = !empty($get['per_page']) && is_numeric($get['per_page']) && in_array($get['per_page'], $available_per_page_options) ? absint($get['per_page']) : 50;
    $paged = !empty($get['paged']) ? absint($get['paged']) : 1;
    $category_slug = !empty($get['category']) ? sanitize_text_field($get['category']) : '';
    $pillar_is_active = !empty($get['pillar-links']) ? sanitize_text_field($get['pillar-links']) : '';
    $active_post = !empty($get['posts']) ? sanitize_text_field($get['posts']) : '';
    $seoaic_search = !empty($get['seoaic_search']) ? sanitize_text_field(urldecode($get['seoaic_search'])) : '';
    $lang = !empty($get['lang']) ? sanitize_text_field(urldecode($get['lang'])) : '';
    $post_types = seoaic_get_post_types();
    $active_post_type = !empty($get['post-types']) ? sanitize_text_field($get['post-types']) : '';
    $publishedDateFromValue = !empty($get['seoaic_publ_datefrom']) && SEOAIC_isValidDate(urldecode($get['seoaic_publ_datefrom'])) ? urldecode($get['seoaic_publ_datefrom']) : '';
    $publishedDateToValue = !empty($get['seoaic_publ_dateto']) && SEOAIC_isValidDate(urldecode($get['seoaic_publ_dateto'])) ? urldecode($get['seoaic_publ_dateto']) : '';
    $selectedPostType = $active_post_type !== '' ? $active_post_type : $post_types;
    $selectedLang = !empty($get['lang-filter']) && $SEOAIC->multilang->is_multilang() ? esc_sql($get['lang-filter']) : '';
    $category_slug = !empty($get['category']) ? sanitize_text_field($get['category']) : '';

    $args = [
        'posts_per_page'    => $selected_per_page,
        'paged'             => $paged,
        'post_type'         => $selectedPostType,
        'post_title_like' => $seoaic_search,
        'date_query'        => SEOAIC_makeDateQuery(),
        'post_status' => 'publish',
        'lang'              => $selectedLang,
        'meta_query'        => [ // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
            'relation'      => 'AND',
            [
                'relation'      => 'OR',
                [
                    'key' => 'seoaic_posted',
                    'compare' => 'EXISTS'
                ],
                [
                    'key' => 'seoaic_posted',
                    'compare' => 'NOT EXISTS'
                ],
            ]
        ],
    ];

    if (!empty($pillar_is_active)) {
        if ($pillar_is_active === 'true') {
            $args['meta_query'][] = [
                'relation' => 'AND',
                [
                    'key' => 'seoaic_tracked_pillar_link',
                    'value'   => 'true',
                    'compare' => '='
                ],
            ];
        } elseif ($pillar_is_active === 'false') {
            $args['meta_query'][] = [
                'relation' => 'AND',
                [
                    'key'     => 'seoaic_tracked_pillar_link',
                    'compare' => 'NOT EXISTS'
                ],
            ];
        }
    }

    if (!empty($active_post)) {
        if ($active_post === 'not-seoai') {
            $args['meta_query'][] = [
                'relation' => 'AND',
                [
                    'key' => 'seoaic_posted',
                    'compare' => 'NOT EXISTS',
                ],
            ];
        }

        if ($active_post === 'seoai') {
            $args['meta_query'][] = [
                'relation' => 'AND',
                [
                    'key' => 'seoaic_posted',
                    'value' => 1,
                    'compare' => '='
                ],
            ];
        }
    }

    if (!empty($publishedDateFromValue)) {
        $args['date_query'][] = [
            'after'  => $publishedDateFromValue,
            'inclusive' => true,
        ];
    }

    if (!empty($category_slug)) {
        $args['category_name'] = $category_slug;
    }

    $query = new WP_Query($args);

    // search by something different from the title/words
    if (
        !empty($seoaic_search)
        && !$query->have_posts()
    ) {
        unset($args['post_title_like']);

        // trying find by post's URL
        $maybePostID = url_to_postid($seoaic_search);

        if (!empty($maybePostID)) {
            $args['post__in'] = [$maybePostID];
            $query = new WP_Query($args);
        }

        // trying find by post's slug
        if (!$query->have_posts()) {
            $args['name'] = $seoaic_search;
            $query = new WP_Query($args);
        }
    }

    $SEOAIC->pillar_links->update_pillar_links();
    $adminUrl = SEOAIC::getAdminUrl('admin.php');

    $languageCode = '';
    if ($SEOAIC->multilang->is_multilang()) {
        $language = $SEOAIC->multilang->get_current_language();
        $languageArgs = $SEOAIC->multilang->get_language_by($language);
        $languageCode = is_array($languageArgs) && !empty($languageArgs['code']) ? $languageArgs['code'] : null;
    }
?>
<div id="seoaic-admin-container" class="wrap">
    <h1 id="seoaic-admin-title">
        <?php echo wp_kses_post(seoai_get_logo( 'logo.svg' )); ?>
        <span><?php echo esc_html( get_admin_page_title() ); ?></span>
    </h1>
    <?php
        $loader_content = $SEOAIC->get_background_process_loader(true);
        if (!empty($loader_content)) {
            echo wp_kses($loader_content, [
                'div' => [
                    'id'    => [],
                    'class' => [],
                    'style' => [],
                    'title' => [],
                ],
                'p' => [
                    'class' => [],
                ],
                'b' => [],
                'button' => [
                    'type'              => [],
                    'class'             => [],
                    'data-modal'        => [],
                    'data-action'       => [],
                    'data-form-callback' => [],
                    'data-content'      => [],
                ],
            ]);
        }
    ?>
    <div id="seoaic-admin-body" class="seoaic-with-loader posts-page">
        <div class="seoaic-posts-table full-width">
            <div class="filters-switcher mt-15">
                <div class="seoaic-filter-rows">
                    <div class="seoaic-filter-row top">
                        <div class="filter-row-wrap">
                            <div class="d-flex ai-center">
                                <label class="mr-15 mb-13"><?php echo esc_html_e('Pillar links', 'seoaic'); ?>:</label>
                                <?php
                                    $get['paged'] = 1;
                                ?>
                                <a href="<?php echo esc_url($adminUrl . '?' . http_build_query(array_merge($get, array('pillar-links'=>'true')))); ?>" class="seoaic-filter-btn <?php echo $pillar_is_active === 'true' ? 'active' : '';?>"><span class="dashicons dashicons-star-filled seoaic-track-btn"></span></a>
                                <a href="<?php echo esc_url($adminUrl . '?' . http_build_query(array_merge($get, array('pillar-links'=>'false')))); ?>" class="seoaic-filter-btn <?php echo $pillar_is_active === 'false' ? 'active' : '';?>"><span class="dashicons dashicons-star-empty seoaic-track-btn"></span></span></a>
                            </div>
                            <div class="d-flex ai-center">
                                <label class="mr-15 mb-13"><?php echo esc_html_e('Show posts', 'seoaic'); ?>:</label>
                                <?php
                                    $get['paged'] = 1;
                                ?>
                                <a href="<?php echo esc_url($adminUrl . '?' . http_build_query(array_merge($get, array('posts'=>'all')))); ?>" class="seoaic-filter-btn <?php echo $active_post === 'all' ? 'active' : '';?>"><?php esc_html_e('All', 'seoaic') ?></a>
                                <a href="<?php echo esc_url($adminUrl . '?' . http_build_query(array_merge($get, array('posts'=>'seoai')))); ?>" class="seoaic-filter-btn <?php echo $active_post === 'seoai' ? 'active' : '';?>"><?php esc_html_e('SEO AI', 'seoaic') ?></a>
                                <a href="<?php echo esc_url($adminUrl . '?' . http_build_query(array_merge($get, array('posts'=>'not-seoai')))); ?>" class="seoaic-filter-btn <?php echo $active_post === 'not-seoai' ? 'active' : '';?>"><?php esc_html_e('Not SEO AI', 'seoaic') ?></a>
                            </div>
                            <div class="d-flex ai-center">
                                <label class="mr-15 mb-13"><?php echo esc_html_e('Select the post type', 'seoaic'); ?>:</label>
                                <?php
                                    $get['paged'] = 1;
                                ?>
                                <?php foreach ($post_types as $post_type) : ?>
                                    <a href="<?php echo esc_url($adminUrl . '?' . http_build_query(array_merge($get, array('post-types'=>$post_type)))); ?>" class="seoaic-filter-btn <?php echo $active_post_type === $post_type ? 'active' : '';?>"><?php echo esc_html(ucfirst($post_type)) ?></a>
                                <?php endforeach; ?>
                            </div>
                            <div class="d-flex ai-center categories">
                                <label class="mr-15 mb-13"><?php echo esc_html_e('Categories', 'seoaic'); ?>:</label>
                                <select name="pillar_links_category" class="seoaic-form-item form-select" onchange="location.href=this.value;">
                                    <?php
                                        $__get = $_GET; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
                                        $__get['paged'] = 1;
                                        unset($__get['category']);
                                    ?>
                                    <option value="<?php echo esc_url($adminUrl . '?' . http_build_query(array_merge($__get))); ?>" <?php echo empty($category_slug) ? 'selected' : '';?>><?php esc_html_e('All', 'seoaic'); ?></option>
                                    <?php
                                        $get['paged'] = 1;
                                        $taxonomies = get_taxonomies([], 'objects');
                                        $excluded_taxonomies = ['language', 'term_language', 'term_translations', 'post_translations', 'product_visibility', 'product_type'];

                                        foreach ($taxonomies as $taxonomy) {
                                            if (strpos($taxonomy->name, 'pa_') === 0) {
                                                continue;
                                            }

                                            if (!in_array($taxonomy->name, $excluded_taxonomies)) {
                                                $post_ids = get_posts([
                                                    'post_type'   => $post_types,
                                                    'fields'      => 'ids',
                                                    'numberposts' => -1,
                                                    'meta_query'        => [ // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
                                                        'relation'      => 'AND',
                                                        [
                                                            'relation'      => 'OR',
                                                            [
                                                                'key' => 'seoaic_posted',
                                                                'compare' => 'EXISTS'
                                                            ],
                                                            [
                                                                'key' => 'seoaic_posted',
                                                                'compare' => 'NOT EXISTS'
                                                            ],
                                                        ]
                                                    ],
                                                ]);

                                                if (!empty($post_ids)) {
                                                    $terms = get_terms([
                                                        'taxonomy'   => $taxonomy->name,
                                                        'hide_empty' => true,
                                                        'object_ids' => $post_ids,
                                                    ]);

                                                    if (!empty($terms) && !is_wp_error($terms)) {
                                                        foreach ($terms as $term) {
                                                            $termName = esc_html(ucfirst($term->name));
                                                            $term_language = $SEOAIC->multilang->get_term_language($term->term_id);

                                                            if (!empty( $term_language)) {
                                                                $termName .= ' (' . esc_html( $term_language ) . ')';
                                                            }
                                                        ?>
                                                            <option value="<?php echo esc_url($adminUrl . '?' . http_build_query(array_merge($get, array('category'=>$term->slug)))); ?>" <?php echo $category_slug === $term->slug ? 'selected' : '';?>>
                                                                <?php echo esc_html($termName); ?>
                                                            </option>
                                                            <?php
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    ?>
                                </select>
                            </div>
                            <?php
                                if ($SEOAIC->multilang->is_multilang()) {
                                    $langs = $SEOAIC->multilang->get_multilanguages();
                                    $countsByLang = SEOAIC_countPostsByLang(array_merge(['all'], array_map(function ($lang) {
                                        return $lang['code'];
                                    }, $langs)));
                                    $__get = $_GET; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
                                    $__get['paged'] = 1;
                                    unset($__get['lang-filter']);
                                    ?>
                                    <div class="seoaic-filter-row">
                                        <label class="mr-15 mb-13"><?php esc_html_e('Post language:', 'seoaic');?></label>
                                        <a
                                            href="<?php echo esc_attr($adminUrl);?>?<?php echo http_build_query(array_merge($__get, array('lang-filter'=>'all'))); //phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped?>"
                                            title="<?php esc_attr_e('All languages', 'seoaic');?>"
                                            class="seoaic-filter-btn <?php echo 'all' == $selectedLang ? 'active' : '';?>"
                                        >
                                            <?php esc_html_e('All', 'seoaic');?>: <?php echo esc_html($countsByLang['all']);?>
                                        </a>
                                        <?php
                                        if (
                                            !empty($langs)
                                            && is_array($langs)
                                        ) {
                                            foreach ($langs as $lang) {
                                                ?>
                                                <a
                                                    href="<?php echo esc_attr($adminUrl);?>?<?php echo http_build_query(array_merge($__get, array('lang-filter'=>esc_js($lang['code'])))); //phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped?>"
                                                    title="<?php echo esc_attr($lang['name']);?>"
                                                    class="seoaic-filter-btn <?php echo $lang['code'] == $selectedLang ? 'active' : '';?>"
                                                >
                                                    <?php if (!empty($lang['flag'])) : ?>
                                                        <img src="<?php echo esc_url($lang['flag']); ?>">
                                                    <?php else : ?>
                                                        <?php echo esc_html(strtoupper($lang['code'])); ?>:
                                                    <?php endif; ?>
                                                    <?php echo esc_html($countsByLang[$lang['code']]);?>
                                                </a>
                                                <?php
                                            }
                                        }
                                        ?>
                                    </div>
                                    <?php
                                }
                            ?>
                        </div>

                        <div class="actions">
                            <div class="d-flex mb-30">
                                <div class="search form-item">
                                    <input type="text" name="s" id="seoaic-search" value="<?php echo !empty($get['seoaic_search']) ? esc_attr(urldecode($get['seoaic_search'])) : ''; ?>" placeholder="Search...">
                                    <button id="seoaic-search-button" class="seoaic-button"></button>
                                </div>

                                <a href="<?php echo esc_url($adminUrl) ?>?page=seoaic-pillar-links" class="clear seoaic-filter-clear-btn" title="Clear data for graph"></a>
                            </div>
                            <div class="d-flex">
                                <div class="f-date mr-15">
                                    <label class="text-label"><?php esc_html_e('Published', 'seoaic');?></label>
                                    <div class="position-relative">
                                        <input type="text" id="seoaic-from-date" name="filter_post_date_from"
                                            value="<?php echo esc_attr($publishedDateFromValue);?>"
                                            class="mt-0 seoaic-form-item form-input"
                                            placeholder="<?php esc_attr_e('Published from', 'seoaic');?>"
                                        >
                                        <div class="picker-call"></div>
                                    </div>
                                </div>
                                <div class="f-date">
                                    <label class="text-label"></label>
                                    <div class="position-relative">
                                        <input type="text" id="seoaic-to-date" name="filter_post_date_to"
                                            value="<?php echo esc_attr($publishedDateToValue);?>"
                                            class="mt-0 seoaic-form-item form-input"
                                            placeholder="<?php esc_attr_e('Published to', 'seoaic');?>"
                                        >
                                        <div class="picker-call"></div>
                                    </div>
                                </div>
                            </div>
                            <div class="posts-per-page">
                                <label class="text-label"><?php esc_html_e('Posts per page', 'seoaic'); ?></label>
                                <select id="posts_per_page_ci" class="form-select-ci pp-select">
                                    <?php
                                    foreach ($available_per_page_options as $option_value) {
                                        $selected_attr = $selected_per_page == $option_value ? ' selected="selected"' : '';
                                        ?>
                                        <option value="<?php echo esc_attr(strval($option_value)) ?>" <?php echo esc_attr($selected_attr); ?>><?php echo esc_html(strval($option_value)); ?></option>
                                        <?php
                                    }
                                    ?>
                                </select>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <?php
            if ($query->have_posts()) {
                ?>
                <div class="seoaic-posts-table__container seoaic-pillar-link-table">
                    <div class="seoaic-posts-table__row seoaic-posts-table__row--head">
                        <div class="seoaic-track-col"></div>
                        <div class="seoaic-posts-table__row-item"><?php esc_html_e('Title', 'seoaic');?></div>
                        <div class="seoaic-posts-category"><?php esc_html_e('Category', 'seoaic');?></div>
                        <div class="date"><?php esc_html_e('Published', 'seoaic');?></div>
                        <div class="seoaic-posts-table__row-action-item seoaic-posts-table__row-action-item--head"></div>
                    </div>
                    <?php
                    while ($query->have_posts()) {
                        $query->the_post();
                        $id = get_the_ID();
                        $trackedPillar = get_post_meta($id, 'seoaic_tracked_pillar_link', true);
                        $isTracked = !empty($trackedPillar) ? "true" == $trackedPillar : false;
                        $trackedClass = $isTracked ? ' seoaic-tracked-pillar_link' : '';
                        $trackedStatus = $isTracked ? 'checked="checked"' : '';
                        $post_type = get_post_type();
                        $categories_list = [];
                        ?>
                        <div class="seoaic-posts-table__row post <?php echo esc_attr($trackedClass) ?>" id="seoaic_post_<?php echo esc_attr($id);?>">
                            <div class="main-info">
                                <div class="seoaic-track-col">
                                    <div class="seoaic-track">
                                        <input type="checkbox"
                                            <?php echo esc_attr($trackedStatus) ?>
                                            class="seoaic-track-key"
                                            name="seoaic-track-key"
                                            data-id="<?php echo esc_attr($id) ?>"
                                            id="pillar_link_<?php echo esc_attr($id) ?>"
                                        >
                                        <label for="pillar_link_<?php echo esc_attr($id) ?>">
                                            <span class="dashicons dashicons-star-empty seoaic-track-btn" title="<?php esc_html_e('Add pillar link', 'seoaic') ?>"></span>
                                            <span class="dashicons dashicons-star-filled seoaic-track-btn" title="<?php esc_html_e('Added pillar link', 'seoaic') ?>"></span>
                                        </label>
                                    </div>
                                </div>
                                <div class="seoaic-posts-table__row-item">
                                    <div class="seoaic-post-title"><?php echo esc_html(get_the_title());?></div>
                                </div>
                                <div class="seoaic-posts-category">
                                    <?php
                                        if ($post_type === 'post') {
                                            $categories = get_the_category();
                                            if (!empty($categories)) {
                                                foreach ($categories as $category) {
                                                    $categories_list[] = esc_html($category->name);
                                                }
                                            }
                                        } elseif ($post_type === 'page') {
                                            echo '';
                                        } else {
                                            $taxonomies = get_object_taxonomies($post_type, 'objects');
                                            foreach ($taxonomies as $taxonomy) {
                                                if ($taxonomy->hierarchical) {
                                                    $terms = get_the_terms(get_the_ID(), $taxonomy->name);
                                                    if (!empty($terms)) {
                                                        foreach ($terms as $term) {
                                                            $categories_list[] = esc_html($term->name);
                                                        }
                                                    }
                                                }
                                            }
                                        }

                                        if (!empty($categories_list)) {
                                            echo esc_html(implode(', ', $categories_list));
                                        }
                                    ?>
                                </div>
                                <div class="seoaic-post-datetime"><?php echo esc_html(get_post_datetime()->format('F j, Y, h:i a'));?></div>
                            </div>
                            <div class="seoaic-posts-table__row-action-item">
                                <a title="<?php esc_html_e('Edit post', 'seoaic'); ?>" target="_blank" href="<?php echo esc_url(get_edit_post_link());?>">
                                    <span class="dashicons dashicons-arrow-right-alt2"></span>
                                </a>
                            </div>
                        </div>
                        <?php
                    }
                    ?>
                </div>
                <?php
                SEOAIC_postsPagination($query);
                wp_reset_postdata();
            } else {
                ?>
                <p><?php esc_html_e('No posts at the moment.', 'seoaic');?></p>
                <?php
            }
            ?>
        </div>
        <div class="lds-dual-ring"></div>
    </div>
</div>