<?php

namespace auctionforge\inc\controllers;

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

use auctionforge\inc\model\SubmissionFormData;
use auctionforge\inc\shortcodes\SubmissionForm;
use WP_List_Table;

class SubmissionsTable extends WP_List_Table
{
    const COLUMN_DATA_ID = 'id';

    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($cur_page, $per_page);
    }

    function get_columns()
    {
        $columns = array(
            'id' => __('ID'),
        );

        $form = new SubmissionForm();
        $fields = $form->getFields();

        if (!empty($fields)) {
            foreach ($fields as $key => $field) {
                $columns[$key] = $field['short_label'];
            }
        }

        $columns = array_merge($columns, [
            'is_exported' => __('Is exported'),
            'ip' => __('IP user'),
            'created' => __('Created')
        ]);

        return $columns;
    }

    function get_sortable_columns()
    {
        return [self::COLUMN_DATA_ID => array(self::COLUMN_DATA_ID, '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()
    {

    }

    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;
                echo "<input type=\"hidden\" name=\"export_submissions_trigger\" value=\"1\" />";
                submit_button(__('Export'), '', 'export_submissions_action', false, array('id' => 'export-submissions-action'));
            }
        }
        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)
    {
        $itemData = [];
        $value = '';

        if (!empty($item->data)) {
            $itemData = json_decode($item->data, true);
        }

        if (!empty($itemData[$colname])) {
            $value = $itemData[$colname];
        } else if (isset($item->$colname)) {
            $value = isset($item->$colname) ? $item->$colname : print_r($item->$colname, 1);
        }
        return $value;
    }

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

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

    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
    }
}
