<?php

namespace auctionforge\inc\controllers;

require_once ABSPATH . "wp-admin/includes/class-wp-list-table.php";

use stdClass;
use auctionforge\inc\Debug;
use auctionforge\inc\InstanceDB;
use auctionforge\inc\model\ImportHistory;
use auctionforge\inc\model\Lot;
use WP_List_Table;
use WP_Term;

class HistoryTable extends WP_List_Table
{
    const COLUMN_PRIORITY = 'priority';
    const COLUMN_DATE_CREATED = 'createDatetime';
    const COLUMN_AUCTION_SLUG = 'auctionSlug';
    const COLUMN_SYNC_DATE_TIME = 'syncDatetime';

    private $model;

    public function __construct()
    {
        parent::__construct(array(
            'singular' => 'log',
            'plural'   => 'logs',
            'ajax'     => false,
        ));

        $this->setModel();

        $this->prepare_items();

        add_action( 'wp_print_scripts', array( __CLASS__, '_list_table_js' ) );
    }

    public static function _list_table_js()
    {
        ?>
        <script>
            document.addEventListener("DOMContentLoaded", function(event) {
                window.wp_nonce = '<?= wp_create_nonce("do_sync_now") ?>';
            });
        </script>
        <?php
    }

    protected function display_tablenav( $which ) {
        if ( 'top' === $which ) {
            wp_nonce_field( 'bulk-' . $this->_args['plural'] );
        }
        ?>
        <div class="tablenav bidspirit-plugin <?= esc_attr( $which ); ?>">
            <?php //Disabled bulk actions ?>
            <?php
            $this->extra_tablenav( $which );
            $this->pagination( $which );
            ?>

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

    public function prepare_items()
    {
        $per_page = 100;

        $params = (!empty($_POST)) ? $_POST : array();
        if (!empty($_GET)) {
            $params = array_merge($params, $_GET);
        }

        $this->set_pagination_args( array(
            'total_items' => $this->getModel()->getCountAllRows($params),
            'per_page' => $per_page,
        ) );
        $cur_page = (int) $this->get_pagenum();

        $this->items = $this->getModel()->getRows($params, $cur_page, $per_page);
    }

    function get_columns()
    {
        return array(
            'id' => 'ID',
            'lotId' => __( 'Lot ID (Bidspirit)' ),
            self::COLUMN_AUCTION_SLUG => __( 'Auction ID (Bidspirit)' ),
            'postId' => __( 'Lot ID (Wordpress)' ),
            self::COLUMN_PRIORITY => __( 'Priority' ),
            self::COLUMN_DATE_CREATED => __( 'Date created' ),
            self::COLUMN_SYNC_DATE_TIME => __( 'Date sync' ),
            'syncFinished' => __( 'Synchronized' ),
            'syncErrors' => __( 'Errors' ),
        );
    }

    function get_sortable_columns()
    {
        return array(
            self::COLUMN_AUCTION_SLUG => array( self::COLUMN_AUCTION_SLUG, 'asc' ),
            self::COLUMN_SYNC_DATE_TIME => array( self::COLUMN_SYNC_DATE_TIME, 'asc' ),
            self::COLUMN_PRIORITY => array( self::COLUMN_PRIORITY, 'asc' ),
            self::COLUMN_DATE_CREATED => array( self::COLUMN_DATE_CREATED, 'asc' ),
        );
    }

    protected function months_dropdown( $post_type )
    {
        global $wpdb, $wp_locale;

        if ( apply_filters( 'disable_months_dropdown', false, $post_type ) ) {
            return;
        }

        $extra_checks = "AND post_status != 'auto-draft'";
        if ( ! isset( $_GET['post_status'] ) || 'trash' !== $_GET['post_status'] ) {
            $extra_checks .= " AND post_status != 'trash'";
        } elseif ( isset( $_GET['post_status'] ) ) {
            $extra_checks = $wpdb->prepare( ' AND post_status = %s', $_GET['post_status'] );
        }

        $months = $wpdb->get_results(
            $wpdb->prepare(
                "
			SELECT DISTINCT YEAR( post_date ) AS year, MONTH( post_date ) AS month
			FROM $wpdb->posts
			WHERE post_type = %s
			$extra_checks
			ORDER BY post_date DESC
		",
                $post_type
            )
        );

        $months = apply_filters( 'months_dropdown_results', $months, $post_type );

        $month_count = count( $months );

        if ( ! $month_count || ( 1 == $month_count && 0 == $months[0]->month ) ) {
            return;
        }

        $m = isset( $_POST['m'] ) ? (int) $_POST['m'] : 0;
    }

    protected function auction_dropdown()
    {
        $status = [
            1 => "Yes",
            2 => "No",
        ];

        $auc = isset( $_POST['status'] ) ? (int) $_POST['status'] : 0;
        ?>
        <div class="actions-filters__item actions-filters__item-inline" style="margin-bottom: 0">
            <label for="filter-by-sync" class="lot-text"><?php _e( 'Synchronized' ); ?></label>
            <select name="status" id="filter-by-sync">
                <option<?php selected( $auc, 0 ); ?> value=""><?php _e( 'All' ); ?></option>
                <?php
                foreach ( $status as $key => $arc_row ) {
                    printf(
                        "<option %s value='%s'>%s</option>\n",
                        selected( $auc, $key, false ),
                        $key,
                        $arc_row
                    );
                }
                ?>
            </select>
        </div>
        <?php
    }

    public function extra_tablenav( $which )
    {

        if ( 'top' === $which && ! is_singular() ) {
            ob_start();
            echo "<div class=\"d-flex d-flex-inline actions-filters\">";
            $this->auction_dropdown();
            $output = ob_get_clean();

            if ( ! empty( $output ) ) {
                echo $output;
                submit_button( __( 'Filter' ), '', 'filter_action', false, array( 'id' => 'lot-query-submit' ) );
            }
        }
        if ( 'bottom' === $which && ! is_singular() ) {
            ob_start();
            echo "<div class=\"d-flex d-flex-wrap\">";
            $this->sync_now_template();
            $output = ob_get_clean();

            if ( ! empty( $output ) ) {
                echo $output;
            }
        }
        ?>
        </div>
        <?php
    }

    /**
     * @param object $item
     * @param string $colname
     * @return string|true|void
     */
    public function column_default($item, $colname )
    {
        if ( $colname === 'auctionSlug' ) {
            $actions = array();
            $actions['edit'] = sprintf( '<a target="_blank" href="%s">%s</a>', '/wp-admin/term.php?taxonomy=auction_number&tag_ID=' .
                $item->auctionSlug . '&post_type=lot', __('edit','hb-users') );

            $message = esc_html( $item->auctionSlug ) . $this->row_actions( $actions );
        } elseif ($colname === 'postId') {
            $link = (is_null($item->postId)) ? '' : $item->postId;
            if (!empty($item->postId)) {
                $link = "<a target='_blank' href=\"" . get_permalink($item->postId) . "\">" . $item->postId . "</a>";
            }
            $message = $link;
        } elseif ($colname === 'syncFinished') {
            $message = ($item->syncFinished == 0) ? __("No") : __("Yes");
        } elseif ($colname === 'syncErrors') {
            $errorMessage = "";
            $postId = intval($item->postId);
            if (!empty($item->syncErrors)) {
                 $obj = json_decode($item->syncErrors);
                 $errorMessage = var_export($obj);
            } elseif ($postId === 0 && !is_null($item->postId)) {
                $errorMessage = "Sync: true, error: \"Skipped because of last_update\"";
            }
            $message = $errorMessage;
        } else {
            $message = isset($item->$colname) ? $item->$colname : print_r($item->$colname, 1);
        }
        return $message;
    }

    /**
     * @return ImportHistory
     */
    public function getModel()
    {
        return $this->model;
    }

    /**
     * Set Model
     * @return void
     */
    public function setModel()
    {
        $this->model = new ImportHistory();
    }

    private function sync_now_template()
    {
        ?>
        <div class="actions-filters__item">
            <p class="title"><?= __('Get data from API to ImportHistory table', 'auctionforge') ?></p>
        </div>
        <div class="actions-filters__item">
            <button id="bs-get-now" type="submit" class="button"><?= __('Get data', 'auctionforge') ?></button>
            <select name="auction_type" id="auction_type">
                <option value="1" selected><?= __('Upcoming auctions', 'auctionforge') ?></option>
                <option value="0"><?= __('Past auctions', 'auctionforge') ?></option>
            </select>
        </div>
        <hr>
        <div class="actions-filters__item">
            <p class="title"><?= __('Sync data from ImportHistory table to posts', 'auctionforge') ?></p>
        </div>
        <div class="actions-filters__item">
            <label for="bs-count-lot" class="lot-text"><?= __('Number  of records', 'auctionforge') ?></label>
            <input id="bs-count-lot" type="text" name="lot_limit" value="" placeholder="<?= RAW_LOT_LIMIT ?>">
        </div>
        <div class="actions-filters__item">
            <button id="bs-sync-now" type="submit" class="button"><?= __('Sync data', 'auctionforge') ?></button>
        </div>
        <div class="actions-filters__item">
            <p class="lot-text">
                <?= sprintf(__('%s Sync can work for all data or changed data. See&nbsp;%s"Sync mode"%s&nbsp;setting in settings', 'auctionforge'),
                    "<strong>*</strong>",
                "<a href='/wp-admin/edit.php?post_type=lot&page=bidspirit_options#bidspirit_settings_sync_force' target='_blank'>", "</a>") ?>
            </p>
        </div>
        <?php
    }
}
