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

    global $SEOAIC, $SEOAIC_OPTIONS;

    $__GET = wp_unslash($_GET);

    $allowed_order_by   = ['date'];
    $allowed_order      = ['asc', 'desc'];
    $allowed_filter     = ['301', '410'];

    $order_by   = !empty($__GET['orderby']) && in_array($__GET['orderby'], $allowed_order_by) ? $__GET['orderby'] : 'date';
    $order      = !empty($__GET['order']) && in_array($__GET['order'], $allowed_order) ? $__GET['order'] : 'desc';
    $filter     = !empty($__GET['filter']) && in_array($__GET['filter'], $allowed_filter ) ? $__GET['filter'] : '';
    $paged      = !empty($__GET['paged']) ? $__GET['paged'] : 1;
    $per_page   = 25;

    $redirects = [];

    if (!empty($SEOAIC_OPTIONS['redirect'])) {
        foreach ( $SEOAIC_OPTIONS['redirect'] as $statusCode => $urls) {

            if( $filter && ( int ) $filter !== $statusCode ) {
                continue;
            }

            foreach ($urls as $url => $data) {
                if (empty($url)) {
                    continue;
                }

                $redirects[] = [
                    'code' => (int) $statusCode,
                    'url' => $url,
                    'destination' => $data['destination'],
                    'date' => $data['created_at'] ? $data['created_at'] : time(),
                ];
            }
        }

        usort($redirects, function ($a, $b) use ($order_by, $order) {
            if ($a[$order_by] == $b[$order_by]) return 0;

            if ($order === 'asc') {
                return $a[$order_by] <=> $b[$order_by];
            } else {
                return $b[$order_by] <=> $a[$order_by];
            }
        });
    }

    $total     = count($redirects);
    $offset    = ($paged - 1) * $per_page;
    $redirects_paged = array_slice($redirects, $offset, $per_page);
    $total_pages = ceil($total / $per_page);

    $big = 999999999;
    $paginationHTML = paginate_links([
        'base' => str_replace([$big, '&#038;'], ['%#%', '&'], get_pagenum_link($big)),
        'total' => $total_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' => '',
    ]);
    $paginationHTML = !empty($paginationHTML) ? $paginationHTML : '';
?>
<div class="seoaic-filter-rows">
    <div class="seoaic-action-row">
        <button
                type="button"
                id="redirects-create-bulk"
                class="button modal-button button-primary seoaic-button-primary"
                data-modal="#seoaic-create-redirects"
        >
            <input type='hidden' id='redirectsBulkItemsInput'>
            <?php esc_html_e('Create Redirects', 'seoaic');?>
        </button>
    </div>
</div>
<div class="seoaic-filter-rows">
    <div class="seoaic-filter-row">
        <button
                title="<?php esc_html_e( 'All redirects', 'seoaic' ); ?>"
                class="seoaic-filter-btn seoaic-filters-reset <?php echo empty( $_GET['filter'] ) ? 'active' : ''; ?>"
        >
            <?php esc_html_e( 'All redirects', 'seoaic' ); ?>
        </button>

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

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

    <div class="seoaic-action-row">
        <button
                type="button"
                class="button button-danger modal-button confirm-modal-button"
                id="redirects-remove-bulk"
                disabled
                data-post-id="all"
                data-modal="#seoaic-confirm-modal"
                data-action="seoaic_mass_suggestion"
                data-form-callback="window_reload"
                data-content="<?php esc_attr_e('Do you want to remove this redirects?', 'seoaic');?>"
        >
            <input type='hidden' id='redirectsBulkItemsInput'>
            <?php esc_html_e('Delete all redirects', 'seoaic');?>
        </button>
    </div>
</div>

<div class="seoaic-filter-rows">
    <div class="redirects-selected-count-wrapper position-relative">
        <?php esc_html_e( 'Selected:', 'seoaic' ); ?> <span id="redirects_selected_count" class="position-absolute">0</span>
    </div>
    <div class="seoaic-pagination">
        <?php
            echo wp_kses($paginationHTML, [
                'div' => [
                    'class' => [],
                ],
                'span' => [
                    'class'         => [],
                    'aria-current'  => [],
                ],
                'a' => [
                    'class' => [],
                    'href'  => [],
                ],
                'i' => [],
            ]);
        ?>
    </div>
</div>

<div class="bottom">
    <div class="flex-table">
        <div>
            <div class="row-line table-heading-row">
                <div class="redirect-checkbox check">
                    <input type="checkbox" class="seoaic-check-key" id="redirect-check-all">
                </div>
                <div class="redirect-code">
                    <span><?php esc_html_e('Status', 'seoaic') ?></span>
                </div>
                <div class="redirect-date sortable" data-orderby="date" data-order="<?php echo esc_attr($order_by === 'date' ? $order : '');?>">
                    <span><?php esc_html_e('Date', 'seoaic') ?></span>
                </div>
                <div class="redirect-page-url">
                    <span><?php esc_html_e('URL', 'seoaic') ?></span>
                </div>
                <div class="redirect-destination">
                    <span><?php esc_html_e('Destination', 'seoaic') ?></span>
                </div>
                <div class="redirect-actions">
                    <span><?php esc_html_e('Actions', 'seoaic') ?></span>
                </div>
            </div>

            <?php if (!empty( $redirects_paged )) : ?>
                <?php foreach ($redirects_paged as $key => $redirect ) : ?>
                    <div class="row-line table-body-row status-<?php echo esc_attr($redirect['code']); ?>">
                        <div class="redirect-checkbox check">
                            <input type="checkbox" class="redirect-checkbox" value="<?php echo esc_attr($key); ?>">
                        </div>

                        <div class="redirect-code" data-code="<?php echo esc_attr($redirect['code']); ?>">
                            <span><?php echo esc_html($redirect['code']); ?></span>
                        </div>

                        <div class="redirect-date" data-created-at="<?php echo esc_attr($redirect['date']); ?>">
                            <span><?php echo esc_html(date('F j, Y, g:i a', $redirect['date'])); ?></span>
                        </div>

                        <div class="redirect-page-url">
                            <a href="<?php echo esc_attr($redirect['url']);?>" title="<?php echo esc_attr($redirect['url']);?>">
                                <?php echo esc_html($redirect['url']);?>
                            </a>
                        </div>

                        <div class="redirect-destination">
                            <?php if( $redirect['code'] !== 410 ): ?>
                                <a href="<?php echo esc_attr($redirect['destination']);?>" title="<?php echo esc_attr($redirect['destination']);?>">
                                    <?php echo esc_html($redirect['destination']);?>
                                </a>
                            <?php endif; ?>
                        </div>

                        <div class="redirect-actions actions">
                            <button title="<?php esc_html_e('Restore post', 'seoaic');?>" type="button" class="seoaic-remove seoaic-redirects-restore-post"></button>
                        </div>
                    </div>
                <?php endforeach;  ?>
            <?php endif; ?>
        </div>
    </div>
</div>
