<?php

namespace RemoveUnusedMedia\HTML;

include 'rum_table.php';

include 'rum_core.php';

use RemoveUnusedMedia\Table as Table;

use function RemoveUnusedMedia\rum_fs;

function page_html()
{
    $table = new Table\Table(!isset($_REQUEST['tab']) ? 'unused' : $_REQUEST['tab']);
    $table->prepare_items();
    $data           = $table->get_data_for_html();
    $rum_error      = get_option('rum_error', false);
    $disabled       = (rum_fs()->is_free_plan() || rum_fs()->can_use_premium_code() )? '' : 'disabled';
    $start_analysis =
        $disabled ? __('License not activated', 'remove-unused-media') : __('Start Analysis', 'remove-unused-media');
    $trigger        = $disabled ? '' : 'onclick="triggerAnalysis()"';
    if (!$rum_error) {
        $time = get_option('rum_time');
        if ($time) {
            $time_format    = get_option('date_format') . ' ' . get_option('time_format');
            $time_formatted = date_i18n($time_format, $time);
            if (current_time('timestamp') - $time >= 604800) {
                $time_formatted .= ' - <span style="color:red">';
                $time_formatted .= __('More than 1 week ago. You should run a new analysis!', 'remove-unused-media');
                $time_formatted .= '</span>';
            } else {
                $time_formatted .= ' - ';
                $time_formatted .= __(
                    'Do not forget to run a new analysis if you performed changes on your website.',
                    'remove-unused-media'
                );
            }
        } else {
            $time_formatted = __('Never, please run analysis', 'remove-unused-media');
        }
        $last = sprintf(esc_html__('Last analysis: %s', 'remove-unused-media'), $time_formatted);
    } else {
        $last = '';
    }
    ?>
    <div class='wrap'>
        <h1 class="wp-heading-inline">Remove Unused Media</h1>
        <a class='page-title-action <?= $disabled ?>' <?= $trigger ?>><?= $start_analysis ?></a>
        <div><?= $last ?></div>
        <hr class="wp-header-end">
        <?php
        if (!empty($data['url_warning'])) {
            $header  = __(
                'Attention! Some of your media contain special characters in their URL. Because this causes multiple problems for browsers, devices and plugins such as Remove Unused Media, we recommend you adjust the URLs accordingly. Media with special characters in their URL will not be detected properly.',
                'remove-unused-media'
            );
            $header2 = __('List of media:', 'remove-unused-media') ?>
            <div class='notice notice-error'>
                <h3><?= $header ?></h3>
                <?= $header2 ?>
                <ul>
                    <?php
                    foreach ($data['url_warning'] as $index => $id) {
                        $link      = get_edit_post_link($id);
                        $title     = get_the_title($id);
                        $collapsed = $index >= 3 ? "rum-special-char" : '';
                        echo "<li class='$collapsed'><a href='$link' target='_blank'>$title</a></li>";
                    }
                    if (count($data['url_warning']) > 3) { ?>
                        <li class="rum-special-char-link">
                            <a onclick="jQuery('.rum-special-char').toggle();jQuery('.rum-special-char-link').toggle();">
                                <?= __('Show more...', 'remove-unused-media') ?>
                            </a>
                        </li>
                        <li style="display:none" class="rum-special-char-link">
                            <a onclick="jQuery('.rum-special-char').toggle();jQuery('.rum-special-char-link').toggle();">
                                <?= __('Show less...', 'remove-unused-media') ?>
                            </a>
                        </li>
                    <?php
                    } ?>
                </ul>
            </div>
        <?php
        } ?>
        <?php
        if (get_option('rum_error_types', false)) {
            $error_types = get_option('rum_error_types');
            $header      = __(
                'Attention! Some posts, pages or CPTs could not be searched.',
                'remove-unused-media'
            );
            $header2     = __(
                'This is likely because the CPT is not intended to be displayed. Normally these CPTs do not contain media. However, please review the following list of problematic post types for a possible problem on our end:',
                'remove-unused-media'
            ) ?>
            <div class='notice notice-error'>
                <h3><?= $header ?></h3>
                <?= $header2 ?>
                <ul>
                    <?php
                    foreach ($error_types as $index => $type) {
                        $collapsed = $index >= 3 ? "rum-special-char" : '';
                        echo "<li class='$collapsed'>$type</li>";
                    }
                    if (count($error_types) > 3) { ?>
                        <li class="rum-special-char-link">
                            <a onclick="jQuery('.rum-error-type').toggle();jQuery('.rum-error-type-link').toggle();">
                                <?= __('Show more...', 'remove-unused-media') ?>
                            </a>
                        </li>
                        <li style="display:none" class="rum-error-type-link">
                            <a onclick="jQuery('.rum-error-type').toggle();jQuery('.rum-error-type-link').toggle();">
                                <?= __('Show less...', 'remove-unused-media') ?>
                            </a>
                        </li>
                    <?php
                    } ?>
                </ul>
            </div>
        <?php
        } ?>
        <div id='rum-menu'>
            <a href='<?php
            echo add_query_arg(['tab' => 'unused']); ?>' <?php
            echo $data['unused']; ?>>
                <?php
                printf(esc_html__('Unused Media (%d)', 'remove-unused-media'), $data['num_unused']); ?>
            </a>
            <a href='<?php
            echo add_query_arg(['tab' => 'used']); ?>' <?php
            echo $data['used']; ?>>
                <?php
                printf(esc_html__('Used Media (%d)', 'remove-unused-media'), $data['num_used']); ?>
            </a>
            <a href='<?php
            echo add_query_arg(['tab' => 'ignored']); ?>' <?php
            echo $data['ignored']; ?>>
                <?php
                printf(esc_html__('Ignored (%d)', 'remove-unused-media'), $data['num_ignored']); ?>
            </a>
            <?php
            if (MEDIA_TRASH) { ?>
                <a href='<?php
                echo add_query_arg(['tab' => 'trash']); ?>' <?php
                echo $data['trash']; ?>>
                    <?php
                    echo _x('Trash', 'attachment filter'); ?> (<?php
                    echo $data['num_trash']; ?>)
                </a>
            <?php
            } ?>
        </div>
        <?php
        if (isset($_REQUEST['rum-debug'])) { ?>
            <div>
                <ul>
                    <?php
                    $time_format = get_option('date_format') . ' ' . get_option('time_format');
                    foreach (get_option("rum_log", []) as $entry) {
                        if ($entry) {
                            $time_formatted = date_i18n($time_format, $entry[0]);
                            echo count($entry) ? "<li>$time_formatted: $entry[1]</li>" : "";
                        }
                    }
                    ?>
                </ul>
            </div>
        <?php
        } ?>
        <div>
            <?php
            $table->display(); ?>
        </div>
        <div id="rum-overlay" style="display: none">
            <div id="rum-overlay-content">
                <h1 id="rum-overlay-header">
                    <?= __('Loading', 'remove-unused-media'); ?>
                </h1>
                <p id="analysis_status"></p>
                <p>
                    <?= __(
                        'Please wait, we are analyzing your media. This will only take a minute.',
                        'remove-unused-media'
                    ) ?>
                </p>
                <p>
                    <?= __(
                        'Please leave the window open until the scan is complete!',
                        'remove-unused-media'
                    ) ?>
                </p>
            </div>
        </div>
    </div>
    <?php
    do_action('remove_unused_media_ajax');
}

function admin_notice()
{
    if (!get_option('rum_analytics', false)) {
        if ('media_page_rum' == get_current_screen()->id) { ?>
            <div class='notice notice-info'>
                <p>
                    <?= __(
                        'Would you like to support our plugin development and share non-sensitive usage data (runtime, installed plugins, website size, media library size,...) with us?',
                        'remove-unused-media'
                    ) ?>
                </p>
                <p>
                    <a href='<?= add_query_arg(['analytics' => 'opt-in']) ?>' class='button-primary'>
                        <?= __("Sure, I'd like to help!", 'remove-unused-media') ?>
                    </a>
                    <a href='<?= add_query_arg(['analytics' => 'opt-out']) ?>' class='button'>
                        <?= __('No thanks!', 'remove-unused-media') ?>
                    </a>
                </p>
            </div>
        <?php
        }
    }
    if (get_option('rum_error', false)) {
        $error = get_option('rum_error'); ?>
        <div class='notice notice-error is-dismissible'>
            <h2>
                <?= __('Unfortunately Remove Unused Media encountered an error.', 'remove-unused-media') ?>
            </h2>
            <p>
                <?= __(
                    'Please allow us to analyze and correct this error by submitting the error information. No personal data is being transmitted.',
                    'remove-unused-media'
                ) ?>
            </p>
            <p>
                <label for="rum_error">
                    <?= __('Error information:', 'remove-unused-media') ?>
                </label><br/>
                <?= $error['error'] ?>:<br/>
                <textarea id="rum_error" cols='100' rows='5' disabled>
                  <?= json_encode($error['error_detail']) ?>
                </textarea>
            </p>
            <p>
                <a href='<?= add_query_arg(['submit-error' => true]) ?>' class='button-primary'>
                    <?= __('Submit to help resolve the error', 'remove-unused-media') ?>
                </a>
            </p>
        </div>
        <?php
    }
    if ('media_page_rum' == get_current_screen()->id && get_option('rum_analysis_counter')
        && !get_option(
            'rum_dismissed_backup',
            false
        )) {
        $backup_link = _x(
            'https://wp-ninjas.de/wordpress-backup',
            'Link to backup explanation',
            'remove-unused-media'
        ); ?>
        <div class='notice notice-info'>
            <p>
                <?= __(
                    'Please make sure you have a backup of your media library before deleting media, in case something you still need goes missing!',
                    'remove-unused-media'
                ) ?>
            </p>
            <p>
                <a target="_blank" href="<?= $backup_link ?>">
                    <?= __('How to backup your site', 'remove-unused-media') ?>
                </a>
            </p>
        </div>
        <?php
    }
}
