<?php

namespace RtmMail;

use RtmMail\Helpers\EventHelper;
use RtmMail\Helpers\LogHelper;
use WP_List_Table;

/**
 * EventsTable - Table construct for the events page, based on WP_List_Table
 */
class EventsTable extends WP_List_Table
{

    public function __construct()
    {
        parent::__construct([
            'singular' => 'event',
            'plural' => 'events',
            'ajax' => false,
        ]);
    }

    /**
     * get_columns - all the columns we want in our overview
     * @return array
     */
    public function get_columns()
    {
        return [
            'message' => __('Message', 'rtm-mail'),
            'level' => __('Level', 'rtm-mail'),
            'source' => __('Source', 'rtm-mail'),
            'wp' => __('WordPress Data', 'rtm-mail'),
            'date' => __('Date', 'rtm-mail'),
            'details' => __('Details', 'rtm-mail')
        ];
    }

    /**
     * get_sortable_columns - Sets column sortable based on 'column_name' => 'db_column_name'
     * @return array
     */
    public function get_sortable_columns()
    {
        return [
            'level' => ['level', false],
            'date' => ['date', false],
        ];
    }

    /**
     * column_message - column message row data
     * @param $item
     * @return string
     */
    public function column_message($item)
    {
        $html = $item['message'];
        if (isset($item['context']['log_id'])) {
            $log = LogHelper::get([
                'post_per_page' => null,
                'where' => [
                    'id' => [
                        'type' => '=',
                        'value' => $item['context']['log_id'],
                    ]
                ]
            ]);
            $mail_log = $log[0] ?? null;
            if ($mail_log != null) {
                $html = '<a href="' . get_admin_url() . 'admin.php?page=rtm-mail-details&log_id=' . $item['context']['log_id'] . '">' . $item['message'] . '</a>';
            }
        }
        return $html;
    }

    /**
     * column_level - column level row data
     * @param $item
     * @return string
     */
    public function column_level($item)
    {
        $html = '<div class="table-wp-data" style="display: flex;"><span class="badge">' . $item['level'] . '</span></div>';
        switch ($item['level']) {
            case 'DEBUG':
                $html = '<div class="table-wp-data" style="display: flex;"><span class="badge badge-caught">' . $item['level'] . '</span></div>';
                break;
            case 'ERROR':
                $html = '<div class="table-wp-data" style="display: flex;"><span class="badge badge-failed">' . $item['level'] . '</span></div>';
                break;
        }
        return $html;
    }

    /**
     * column_source - column source data
     * @param $item
     * @return string
     */
    public function column_source($item)
    {
        $html = __('No source was given');

        if (isset($item['context']['source'])) {
            // Get user_id from string
            $user_id = (int)filter_var($item['context']['source'], FILTER_SANITIZE_NUMBER_INT);
            $user_data = get_user_by('id', $user_id);
            if (!empty($user_data)) {
                $html = '<a href="' . get_admin_url() . 'user-edit.php?user_id=' . $user_id . '">' . $item['context']['source'] . '</a>';
            } else {
                $html = $item['context']['source'];
            }
        }

        return $html;
    }

    /**
     * column_wp - column wordpress row data
     * @param $item
     * @return string
     */
    public function column_wp($item)
    {
        $html = '<div class="table-wp-data">';
        foreach ($item['extra']['wp'] as $data_type => $data_value) {
            if ($data_type !== 'user_id') {
                $data_value = $data_value ? 'true' : 'false';
            }
            $html .= '<span class="button badge-wp-data" style="margin-right: 5px; font-size:12px;">' . $data_type . ': <strong>' . $data_value . '</strong></span>';
        }
        $html .= '</div>';

        return $html;
    }

    /**
     * column_date - column date row data
     * @param $item
     * @return string
     */
    public function column_date($item)
    {
        return '<div class="table-wp-data" style="display: flex;">' . $item['date']->format('d-m-Y h:i:s') . '</div>';
    }

    /**
     * colum_details - column details row data
     * @param $item
     * @return string
     */
    public function column_details($item)
    {
        $html = '';
        if (isset($item['context']['log_id'])) {
            $html = '<a href="' . get_admin_url() . 'admin.php?page=rtm-mail-event_details&log_id=' . $item['context']['log_id'] . '" class="button button-action">' . __('Details', 'rtm-mail') . '</a>';
        }
        return $html;
    }

    /**
     * column_default - default way to show column data
     * @param array|object $item
     * @param string $column_name
     * @return string|void
     */
    public function column_default($item, $column_name)
    {
        return '<div class="table-wp-data" style="display: flex;">' . $item[$column_name] . '</div>';
    }

    /**
     * search_box - displays the search box
     * @param string $text
     * @param string $input_id
     */
    public function search_box($text, $input_id)
    {
        if (empty($_REQUEST['s']) && !$this->has_items()) {
            return;
        }

        $input_id = $input_id . '-search-input';

        if (!empty($_REQUEST['orderby'])) {
            echo '<input type="hidden" name="orderby" value="' . esc_attr($_REQUEST['orderby']) . '" />';
        }
        if (!empty($_REQUEST['order'])) {
            echo '<input type="hidden" name="order" value="' . esc_attr($_REQUEST['order']) . '" />';
        }
        if (!empty($_REQUEST['post_mime_type'])) {
            echo '<input type="hidden" name="post_mime_type" value="' . esc_attr($_REQUEST['post_mime_type']) . '" />';
        }
        if (!empty($_REQUEST['detached'])) {
            echo '<input type="hidden" name="detached" value="' . esc_attr($_REQUEST['detached']) . '" />';
        }
        ?>
        <div class="search-filter">
            <div class="search-box">
                <label class="screen-reader-text" for="<?php echo esc_attr($input_id); ?>"><?php echo $text; ?>:</label>
                <input type="search" id="<?php echo esc_attr($input_id); ?>" name="s"
                       placeholder="<?php echo __('Search on content', 'rtm-mail'); ?>"
                       value="<?php _admin_search_query(); ?>"/>
                <?php submit_button($text, '', '', false, array('id' => 'search-submit')); ?>
            </div>
            <div class="filter-box">
                <div class="filter-label-box">
                    <p class="filter-label"><?php echo __('Filter by', 'rtm-mail'); ?><i
                                class="fas fa-caret-down filter__icon"></i></p>
                </div>
                <div class="filter-input">
                    <div class="filter-input-item">
                        <input type="checkbox" id="search_log_id" name="search_filter[log_id]" checked>
                        <label for="search_log_id"><?php echo __('Log ID', 'rtm-mail'); ?></label>
                    </div>
                    <div class="filter-input-item">
                        <input type="checkbox" id="search_message" name="search_filter[message]" checked>
                        <label for="search_message"><?php echo __('Message', 'rtm-mail'); ?></label>
                    </div>
                    <div class="filter-input-item">
                        <input type="checkbox" id="search_level" name="search_filter[level]" checked>
                        <label for="search_level"><?php echo __('Level', 'rtm-mail'); ?></label>
                    </div>
                </div>
            </div>
        </div>
        <?php
    }

    /**
     * display_tablenav - displays top or bottom row for the table
     * @param string $which
     */
    public function display_tablenav($which)
    {
        // Only want things at the bottom so return when top
        if ('top' === $which) {
            return;
        }
        ?>
        <div class="tablenav <?php echo esc_attr($which); ?>">

            <?php if ($this->has_items()) : ?>
                <div class="alignleft actions bulkactions">
                    <div class="bulk-action">
                        <select class="filter_level_select" name="level_type">
                            <option value=""><?php _e('Filter by level'); ?></option>
                            <option value="error">ERROR</option>
                            <option value="debug">DEBUG</option>
                            <option value="info">INFO</option>
                        </select>
                        <input type="submit" name="filter_level" id="filter-level" class="button"
                               value="<?php _e('Filter', 'rtm-mail'); ?>">
                    </div>
                    <div class="bulk-action">
                        <input type="button" name="clear_events" id="clear-events" class="button button-delete"
                               value="<?php _e('Clear debug events', 'rtm-mail'); ?>">
                    </div>
                </div>
            <?php
            endif;
            $this->extra_tablenav($which);
            $this->pagination($which);
            ?>

            <br class="clear"/>
        </div>
        <?php
    }

    /**
     * prepare_items - Sets table items and different pagination settings
     */
    public function prepare_items()
    {
        $columns = $this->get_columns();
        $sortable = $this->get_sortable_columns();
        $this->_column_headers = [$columns, [], $sortable];

        $defaults = EventHelper::DEFAULT_ARGS;
        $total_items = EventHelper::get_total_rows($_GET);
        $post_per_page = $defaults['post_per_page'];

        $total_pages = ceil($total_items / $post_per_page);

        $this->set_pagination_args([
            'total_items' => $total_items,
            'total_pages' => $total_pages,
            'per_page' => $post_per_page,
        ]);

        $this->items = EventHelper::get($_GET);
    }

    /**
     * display - Displays the table
     */
    public function display()
    {
        $singular = $this->_args['singular'];

        $this->display_tablenav('top');

        $this->screen->render_screen_reader_content('heading_list');
        /**** Generate desktop table ****/
        ?>
        <table class="wp-list-table desktop__view <?php echo implode(' ', $this->get_table_classes()); ?>">
            <thead>
            <tr>
                <?php $this->print_column_headers(); ?>
            </tr>
            </thead>

            <tbody id="the-list"
                <?php
                if ($singular) {
                    echo " data-wp-lists='list:$singular'";
                }
                ?>
            >
            <?php $this->display_rows_or_placeholder(); ?>
            </tbody>

            <tfoot>
            <tr>
                <?php $this->print_column_headers(false); ?>
            </tr>
            </tfoot>

        </table>
        <?php
        $this->display_mobile();
        $this->display_tablenav('bottom');
    }

    /**
     * display_mobile - Displays the table for mobile responsiveness
     */
    public function display_mobile()
    {
        ?>
        <table class="mobile-grid mobile__view <?php echo implode(' ', $this->get_table_classes()); ?>">
            <tbody>
            <?php
            foreach ($this->items as $item) {
                echo '<tr class="mobile-grid-row">';
                $this->mobile_row_columns($item);
                echo '</tr>';
            }
            ?>
            </tbody>
        </table>
        <?php
    }

    public function mobile_row_columns($item)
    {
        list($columns, $hidden, $sortable, $primary) = $this->get_column_info();
        foreach ($columns as $column_name => $column_display_name) {
            if ('cb' === $column_name) {
                echo '<td class="mobile-grid-cell">';
                echo '<span class="cell-label">' . $this->column_cb($item) . '</span>';
                echo '<span class="cell-data"></span>';
                echo '</td>';
            } elseif (method_exists($this, 'column_mobile_' . $column_name)) {
                echo '<td class="mobile-grid-cell">';
                echo '<span class="cell-label">' . $column_display_name . '</span>';
                echo '<span class="cell-data">' . call_user_func(array($this, 'column_mobile_' . $column_name), $item) . '</span>';
                echo '</td>';
            } elseif (method_exists($this, 'column_' . $column_name)) {
                echo '<td class="mobile-grid-cell">';
                echo '<span class="cell-label">' . $column_display_name . '</span>';
                echo '<span class="cell-data">' . call_user_func(array($this, 'column_' . $column_name), $item) . '</span>';
                echo '</td>';
            } else {
                echo '<td class="mobile-grid-cell">';
                echo '<span class="cell-label">' . $column_display_name . '</span>';
                echo '<span class="cell-data">' . $this->column_default($item, $column_name) . '</span>';
                echo '</td>';
            }
        }
    }
}