<?php
if (!current_user_can('seoaic_edit_plugin')) {
    return;
}

if (isset($_GET['settings-updated'])) {
    add_settings_error('seoaic_messages', 'seoaic_message', esc_html__('Settings Saved', 'mdsf'), 'updated');
}

settings_errors('seoaic_messages');

global $SEOAIC, $SEOAIC_OPTIONS;

// $SEOAIC->keywords->convertKeywordsToPosts();
$SEOAIC->onboarding->migrateClusters();

$keywords = $SEOAIC->keywords->getKeywords();
$keywords = $SEOAIC->keywords->sanitizeKeywords($keywords);
// $keywords = $SEOAIC->keywords->generateKeywordsStat(false, $keywords);
$isRankInProgress = $SEOAIC->keywords->isBackgroundRankProcessInProgress();
$settings_location = $SEOAIC->settings::getLocation();
$settings_language = $SEOAIC->settings::getLanguage();
$manualNextTime = $SEOAIC->keywords::getNextUpdateTimestamp();
$mu = time() > $manualNextTime ? '' : 'disabled';
$refreshDisabledAttr = time() > $manualNextTime ? '' : 'disabled';
$lastUpdatedTimestamp = $SEOAIC->keywords::getLastUpdateTimestamp();
$lastUpdatedStr = !empty($lastUpdatedTimestamp) ? ' ' . esc_html__("Data can be refreshed again on: ", 'seoaic') . gmdate('d/m/Y H:i e', $manualNextTime) : '';
$searchValue = $_GET['s'] ?? '';

$sortingOrderAttr = function ($field) {
    if (!empty($_GET['sortby'])) {
        if (
            empty($_GET['order'])
            || !in_array(strtolower($_GET['order']), ['asc', 'desc'])
        ) {
            $order = 'desc';
        } else {
            $order = strtolower($_GET['order']);
        }

        if ($field == $_GET['sortby']) {
            return ' data-order="' . $order . '"';
        }

    } else {
        if ('search-vol' == $field) {
            return ' data-order="desc"';
        }
    }

    return '';
}

?>
<div id="seoaic-admin-container" class="wrap">
    <h1 id="seoaic-admin-title">
        <?php
        echo wp_kses(seoai_get_logo('logo.svg'), [
            'img' => [
                'title' => [],
                'src'	=> [],
                'alt'	=> [],
            ],
        ]);
        ?>
        <span>
            <?php echo esc_html( get_admin_page_title() ); ?>
        </span>
    </h1>
    <?php
    echo wp_kses($SEOAIC->get_background_process_loader(true), [
        '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 keywords" <?php echo $SEOAIC->keywords->isNotMigratedTerms(); ?>
         data-keywords-json="<?php esc_attr_e( json_encode( array_column( $keywords, 'name' ) ) ); ?>">
        <div class="inner">

            <div class="top">
                <div class="search seoaic-mr-20">
                    <input id="keywords_search_input" type="text"
                           placeholder="<?php esc_html_e( 'Enter a keyword', 'seoaic' ); ?>"
                           value="<?php echo esc_attr( sanitize_text_field( $searchValue ) ); ?>"
                           class="seoaic-h-100-i">
                    <button type="submit" id="keywords_search_do_search"></button>
                </div>

                <button type="button"
                        title="<?php esc_html_e( 'Generate ideas', 'seoaic' ); ?>"
                        class="button-primary seoaic-button-primary seoaic-generate-ideas-button generate-keyword-based modal-button seoaic-mr-20"
                        data-action="seoaic_generate_ideas_new_keywords"
                        data-modal="#generate-ideas-new-keywords"
                >
                    <?php esc_html_e( 'Generate keyword-based ideas', 'seoaic' ); ?>
                </button>

                <button title="<?php esc_html_e( 'Manage Clusters', 'seoaic' ); ?>"
                        data-title="Manage Clusters" type="button"
                        class="manage-categories secondary-btn outline modal-button seoaic-mr-20"
                        data-modal="#seoaic-manage-clusters"
                >
                    <?php esc_html_e( 'Clusters', 'seoaic' ); ?></button>

                <button title="<?php esc_html_e( 'Set Cluster', 'seoaic' ); ?>"
                        data-title="Set Cluster" type="button"
                        class="seoaic-keywords-mass-set-cluster secondary-btn outline modal-button seoaic-mr-20 display-none"
                        data-modal="#keywords-set-category-modal"
                        data-action="seoaic_add_keyword"
                >
                    <?php esc_html_e( 'Set Cluster', 'seoaic' ); ?></button>

                <button data-title="<?php esc_html_e( 'Open keywords explorer', 'seoaic' ); ?>" type="button"
                        class="add-keyword generate-keywords button-primary outline modal-button ml-auto seoaic-mr-20"
                        data-modal="#keywords-explorer-popup"
                        data-mode="generate"
                        data-lang="<?php echo esc_attr( $settings_language ) ?>"
                        data-location="<?php echo esc_attr( $settings_location ) ?>"
                >
                    <?php esc_html_e( 'Keywords explorer', 'seoaic' ); ?>
                    <div class="dn edit-form-items">
                        <input type="hidden" name="item_name" value="" data-label="Name">
                        <input type="hidden" name="action" value="seoaic_add_keyword">
                    </div>
                </button>

                <button data-title="Generate keywords" type="button"
                        class="add-keyword generate-keywords button-primary outline modal-button ml-auto seoaic-mr-20"
                        data-modal="#generate-keywords"
                        data-mode="generate"
                        data-form-callback="window_reload"
                >
                    <span class="dashicons dashicons-admin-generic"></span>
                    <?php esc_html_e( 'Generate keywords', 'seoaic' ); ?>
                    <div class="dn edit-form-items">
                        <input type="hidden" name="item_name" value="" data-label="Name">
                        <input type="hidden" name="action" value="seoaic_add_keyword">
                    </div>
                </button>

                <button title="<?php esc_html_e( 'Add new keywords', 'seoaic' ); ?>"
                        data-title="<?php esc_html_e( 'Add new keywords', 'seoaic' ); ?>" type="button"
                        class="add-keyword add-keyword-manual small-btn button-primary outline modal-button"
                        data-modal="#add-keyword-modal"
                        data-mode="add"
                        data-action="seoaic_add_keyword"
                        data-form-callback="window_reload"
                >
                    <span class="vertical-align-middle dashicons dashicons-plus-alt2"></span>
                    <div class="dn edit-form-items">
                        <input type="hidden" name="action" value="seoaic_add_keyword">
                    </div>
                </button>

                <button type="button"
                    <?php echo esc_attr($refreshDisabledAttr);?>
                    class="seoaic_update_keywords seoaic-ajax-button small-btn <?php echo esc_attr($mu);?>"
                    data-callback="update_keywords_manual"
                    data-action="seoaic_update_keywords"
                    title="<?php echo esc_html__('Refresh data.', 'seoaic') . esc_attr($lastUpdatedStr);?>"
                ></button>

                <button type="button"
                        title="<?php esc_html_e('Remove', 'seoaic');?>"
                        disabled
                        class="seoaic-remove-keywords-bulk modal-button confirm-modal-button small-btn"
                        data-modal="#seoaic-confirm-modal"
                        data-action="seoaic_remove_keyword"
                        data-form-callback="window_reload"
                        data-content="<?php esc_html_e('Do you want to remove selected keywords?', 'seoaic');?>"
                        data-selected="get-selected-keywords"
                        data-post-id=""
                ></button>
            </div>

            <?php
            if (!empty($lastUpdatedTimestamp)) {
                ?>
                <div class="d-flex justify-end">
                    <span class="seoaic-keywords-last-updated"><?php echo esc_html__("Last updated: ", "seoaic") . gmdate("d/m/Y H:i e", $lastUpdatedTimestamp);?></span>
                </div>
                <?php
            }
            ?>

            <div class="seoaic-filter-rows">
                <div class="seoaic-filter-row">
                    <button
                            title="<?php esc_html_e( 'All keywords', 'seoaic' ); ?>"
                            class="seoaic-filter-btn seoaic-filters-reset <?php echo empty( $_GET['filter'] ) ? 'active' : ''; ?>"
                    >
                        <?php esc_html_e( 'All', 'seoaic' ); ?>
                    </button>

                    <button
                            title="<?php esc_html_e( 'Tracked keywords', 'seoaic' ); ?>"
                            class="seoaic-filter-btn seoaic-filter-tracked <?php echo ! empty( $_GET['filter'] ) && 'tracked' == $_GET['filter'] ? 'active' : ''; ?>"
                    >
                        <?php esc_html_e( 'Tracked keywords', 'seoaic' ); ?>
                    </button>

                    <button
                            title="<?php esc_html_e( 'All ranked keywords', 'seoaic' ); ?>"
                            class="seoaic-filter-btn seoaic-filter-all-ranked <?php echo ! empty( $_GET['filter'] ) && 'ranked' == $_GET['filter'] ? 'active' : ''; ?>"
                    >
                        <?php esc_html_e( 'All ranked keywords', 'seoaic' ); ?>
                    </button>

                    <button
                            title="<?php esc_html_e( 'Keywords which position was changed', 'seoaic' ); ?>"
                            class="seoaic-filter-btn seoaic-filter-position-changes <?php echo ! empty( $_GET['filter'] ) && 'rank-changed' == $_GET['filter'] ? 'active' : ''; ?>"
                    >
                        <?php esc_html_e( 'Position changes', 'seoaic' ); ?>
                    </button>

                    <button
                            title="<?php esc_html_e( 'Keywords which started to be ranked', 'seoaic' ); ?>"
                            class="seoaic-filter-btn seoaic-filter-new-ranked <?php echo ! empty( $_GET['filter'] ) && 'new-ranked' == $_GET['filter'] ? 'active' : ''; ?>"
                    >
                        <?php esc_html_e( 'New ranked keywords', 'seoaic' ); ?>
                    </button>
                </div>
                <div class="keywords-selected-count-wrapper position-relative">
                    <?php esc_html_e( 'Selected:', 'seoaic' ); ?> <span id="keywords_selected_count" class="position-absolute">0</span>
                </div>
            </div>

            <div class="top-scrollbar-wrapper">
                <div class="top-scrollbar">
                </div>
            </div>
            <div class="bottom">
                <div class="seoaic-keywords-table">
                    <?php
                    if ($isRankInProgress) {
                        ?>
                        <input type="hidden" name="is_rank_in_progress" id="is_rank_in_progress" value="1">
                        <?php
                    }
                    if (!empty($keywords)) {
                        ?>
                        <div class="row-line heading">
                            <div class="row-line-container">
                                <div class="check">
                                    <input name="seoaic-keywords-select-all-keywords" type="checkbox">
                                </div>

                                <div class="keyword sortable" <?php echo $sortingOrderAttr( "keyword" ); ?>
                                     data-column="keyword">
                                    <?php esc_html_e( 'Keywords', 'seoaic' ); ?>
                                </div>

                                <div class="category text-center">
                                    <select
                                        multiple="multiple"
                                        id="category-filter"
                                        class="clusters"
                                        style="position:absolute;"
                                    >
                                        <?php
                                            echo $SEOAIC->keywords->makeKeywordsCategoriesOptions(
                                                $SEOAIC->keywords->getKeywordsCategories()
                                            );
                                        ?>
                                    </select>
                                </div>

                                <div class="search-vol sortable text-center" <?php echo $sortingOrderAttr( "search-vol" ); ?>
                                     data-column="search-vol">
                                    <?php esc_html_e( 'Search', 'seoaic' ); ?>
                                    <br>
                                    <?php esc_html_e( 'volume', 'seoaic' ); ?>
                                </div>

                                <div class="difficulty sortable text-center" <?php echo $sortingOrderAttr( "difficulty" ); ?>
                                     data-column="difficulty">
                                    <?php esc_html_e( 'Difficulty', 'seoaic' ); ?>
                                </div>

                                <div class="cpc sortable text-center" <?php echo $sortingOrderAttr( "cpc" ); ?>
                                     data-column="cpc">
                                    <?php esc_html_e( 'CPC', 'seoaic' ); ?>
                                </div>

                                <div class="rank sortable text-center">
                                    <?php esc_html_e( 'Rank', 'seoaic' ); ?>
                                </div>

                                <div class="serp competitors text-center">
                                    <?php esc_html_e( 'SERP', 'seoaic' ); ?>
                                    <br>
                                    <?php esc_html_e( 'Competitors', 'seoaic' ); ?>
                                </div>

                                <div class="search-intent">
                                    <label for="intent-filter"></label>
                                    <select id="intent-filter">
                                        <?php echo $SEOAIC->keywords->makeKeywordsIntentsOptions(); ?>
                                    </select>
                                </div>
                                <div class="created text-center">
                                    <?php esc_html_e( 'Created', 'seoaic' ); ?>
                                </div>

                                <div class="location text-center">
                                    <?php esc_html_e( 'Country', 'seoaic' ); ?>
                                    <br>
                                    <?php esc_html_e( 'Language', 'seoaic' ); ?>
                                </div>

                                <div class="link text-center">
                                    <?php esc_html_e( 'Link', 'seoaic' ); ?>
                                </div>

                                <div class="delete"></div>
                            </div>
                        </div>
                        <?php echo $SEOAIC->keywords->makeKeywordsTableMarkup( $keywords );
                    } else {
                        esc_html_e( 'No keywords at the moment', 'seoaic' );
                    }
                    ?>
                </div>
                <div>
                    <button id="show_competitors_ranked_btn" class="modal-button"
                            data-modal="#keywords-show-ranked-keywords-modal">
                        <?php esc_html_e( 'Show Ranked from Competitors', 'seoaic' ); ?>
                    </button>
                </div>
            </div>

        </div>
        <div class="lds-dual-ring"></div>
    </div>
</div>
