<?php

namespace Salesloo\AdminTable;

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly.
}


if (!class_exists('WP_List_Table')) {
    require_once(ABSPATH . 'wp-admin/includes/class-wp-list-table.php');
}

use Salesloo\Models\Coupon_Code;

class Coupon_Codes extends \WP_List_Table
{
    /**
     * constructor
     */
    public function __construct()
    {
        parent::__construct(
            array(
                'singular' => 'coupon',     // Singular name of the listed records.
                'plural'   => 'coupons',    // Plural name of the listed records.
                'ajax'     => false,       // Does this table support ajax?
            )
        );
    }

    /**
     * Get columns
     * @return [type] [description]
     */
    public function get_columns()
    {
        $columns = array(
            //'cb'           => '<input type="checkbox" />', // Render a checkbox instead of text.
            'code'   => _x('Code', 'Column label', 'salesloo'),
            'user'   => _x('User', 'Column label', 'salesloo'),
            'usage'   => _x('Usage', 'Column label', 'salesloo'),
        );
        return $columns;
    }

    /**
     * Define checkbox column
     * @param  [type] $item [description]
     * @return [type]       [description]
     */
    protected function column_cb($item)
    {
        return sprintf(
            '<input type="checkbox" name="%1$s[]" value="%2$s" />',
            $this->_args['singular'],
            $item->ID
        );
    }

    /**
     * Define column user
     * @param  [type] $item [description]
     * @return [type]       [description]
     */
    protected function column_user($item)
    {
        $output = 'General';

        $user = get_userdata(intval($item->user_id));
        if ($user) {
            $output = $user->user_login;
        }

        return sprintf(
            '<span>%1$s</span></a>',
            $output,
        );
    }


    /**
     * Define column usage
     * @param  [type] $item [description]
     * @return [type]       [description]
     */
    protected function column_usage($item)
    {
        $usage = 0;

        $result = \Salesloo\Models\Coupon_Usage::select('COUNT(usage_id) as count')
            ->query(
                <<<SQL
                WHERE code_id = $item->code_id
                SQL
            )
            ->result();

        return sprintf(
            '<span>%1$s</span></a>',
            $result[0]->count,
        );
    }

    /**
     * Define column code
     * @param  [type] $item [description]
     * @return [type]       [description]
     */
    protected function column_code($item)
    {
        return sprintf(
            '<span>%1$s</span></a>',
            $item->code,
        );
    }

    protected function extra_tablenav($which)
    {
        return;
    }

    protected function display_tablenav($which)
    {
?>
        <div class="tablenav <?php echo esc_attr($which); ?>">

            <?php if ($this->has_items()) : ?>
                <div class="alignleft actions bulkactions">
                    <?php $this->bulk_actions($which); ?>
                </div>
            <?php
            endif;
            $this->extra_tablenav($which);
            $this->pagination($which);
            ?>

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

    /**
     * prepare items list
     * @return [type] [description]
     */
    public function prepare_items()
    {
        $current_screen = get_current_screen();
        $per_page = 20;
        $columns  = $this->get_columns();
        $hidden   = array();
        $sortable = $this->get_sortable_columns();
        $coupon_id = isset($_GET['coupon_id']) ? intval($_GET['coupon_id']) : 0;

        /*
		 * REQUIRED. Finally, we build an array to be used by the class for column
		 * headers. The $this->_column_headers property takes an array which contains
		 * three other arrays. One for all columns, one for hidden columns, and one
		 * for sortable columns.
		 */
        $this->_column_headers = array($columns, $hidden, $sortable);

        /**
         * Optional. You can handle your bulk actions however you see fit. In this
         * case, we'll handle them within our package just to keep things clean.
         */
        $this->process_bulk_action();

        $coupon_query = Coupon_Code::paginate($per_page, $this->get_pagenum());
        $where = [
            sprintf('coupon_id = %d', $coupon_id),
        ];

        if (!empty($_REQUEST['s'])) :
            $search = sanitize_text_field($_REQUEST['s']);
            if ($search) {
                $where[] = sprintf('code LIKE %s', "'%$search%'");
            }
        endif;

        if ($where) {
            $where = implode(' AND ', $where);
            $coupon_query->query("WHERE $where");
        }

        $coupons = $coupon_query->get();

        $this->items = $coupons->found > 0 ? $coupons : 0;
        $this->set_pagination_args(
            array(
                'total_items' => $coupons->found(),
                'total_pages' => $coupons->max_num_pages(),
                'per_page' => $coupons->results_per_page(),
            )
        );
    }
}
