<?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;

class Coupons 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?
            )
        );
    }

    protected function get_views()
    {
        $statuses = salesloo_get_coupon_statuses();

        $current_status = isset($_REQUEST['status']) ? sanitize_text_field($_REQUEST['status']) : '';

        $link = admin_url('admin.php?page=salesloo-coupon');
        if (!$current_status) {
            $tag = __('All', 'salesloo');
        } else {
            $tag = sprintf('<a href="%s">%s</a>', $link, __('All', 'salesloo'));
        }
        $status_links = array(
            'all' => $tag,
        );

        foreach ((array)$statuses as $status_key => $status_title) {
            $new_link = $link . '&status=' . $status_key;
            if ($current_status == $status_key) {
                $status_links[$status_key] = $status_title;
            } else {
                $status_links[$status_key] = sprintf('<a href="%s">%s</a>', $new_link, $status_title);
            }
        }

        return $status_links;
    }

    /**
     * Get columns
     * @return [type] [description]
     */
    public function get_columns()
    {
        $columns = array(
            //'cb'       => '<input type="checkbox" />', 
            'title'    => __('Title', 'salesloo'),
            'code'     => __('General Code', 'salesloo'),
            'rebate'   => __('Rebate', 'salesloo'),
            'products' => __('Products', 'salesloo'),
            'limit'    => __('Max Used', 'salesloo'),
            'status'   => sprintf('<div style="text-align:center">%s</div>', __('Status', 'salesloo')),
            'action'   => __(' ', '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 title
     * @param  [type] $item [description]
     * @return [type]       [description]
     */
    protected function column_title($item)
    {
        return sprintf(
            '<span style="font-weight:bold">%1$s</span></a>',
            $item->title,
        );
    }

    /**
     * Define column general code
     * @param  [type] $item [description]
     * @return [type]       [description]
     */
    protected function column_code($item)
    {
        $query = \Salesloo\Models\Coupon_Code::query(
            <<<SQL
            WHERE coupon_id = $item->ID AND user_id IS NULL
            SQL
        )->first();

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

    /**
     * Define column products
     *
     * @param  mixed $item
     * @return string
     */
    protected function column_products($item)
    {
        $products = [];
        if ($item->products) {
            foreach ($item->products as $product_id) {
                $product = salesloo_get_product($product_id);
                $products[] = isset($product->title) ? sanitize_text_field($product->title) : '~';
            }
        }

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

    /**
     * Define column usage limit
     *
     * @param  mixed $item
     * @return string
     */
    protected function column_limit($item)
    {
        return sprintf(
            '<span>%1$s</span></a>',
            $item->max_usage,
        );
    }


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

    /**
     * Define column gender
     * @param  [type] $item [description]
     * @return [type]       [description]
     */
    protected function column_status($item)
    {

        switch ($item->status) {
            case 'active':
                $color = '#46B450';
                break;

            case 'inactive':
                $color = '#DC3232';
                break;

            default:
                $color = '#82878C';
        }

        return sprintf(
            '<div style="text-align: center;color:%1$s">%2$s</span></a>',
            $color,
            ucfirst($item->status),
        );
    }


    /**
     * define column total hit
     * @param  [type] $item [description]
     * @return [type]       [description]
     */
    protected function column_action($item)
    {
        $item_id = $item->ID;
        ob_start();

        echo '<div style="text-align:right;">';
        echo '<a target="" href="' . admin_url('admin.php?page=salesloo-coupon&action=edit&coupon_id=' . intval($item_id)) . '" class="button">Edit</a>';
        echo '&nbsp;';
        //echo '<a href="admin.php?page=salesloo-coupon&delete=" class="button">Delete</a>';
        echo '</div>';

        $html = ob_get_contents();
        ob_end_clean();

        return $html;
    }

    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();

        /*
		 * 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::paginate($per_page, $this->get_pagenum())->order('ID', 'DESC');

        $where = [];

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

        if (!empty($_REQUEST['status'])) :
            $status = sanitize_text_field($_REQUEST['status']);
            $where[] = sprintf('status = %s', "'$status'");
        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(),
            )
        );
    }
}
