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

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

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

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

        $link = admin_url('admin.php?page=salesloo-order');
        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" />',                                                    // Render a checkbox instead of text.
            'detail'      => __('Detail', 'salesloo'),
            'customer'  => __('Customer', 'salesloo'),
            //'affiliate' => __('Affiliate', 'salesloo'),
            'product'   => __('Product', 'salesloo'),
            //'code'      => __('Purchase Code', 'salesloo'),
            //'status'    => sprintf('<div style="text-align: right">%s</div>', __('Status', 'salesloo')),
            //'action'    => '&nbsp',
        );
        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 detail order
     * @param  [type] $item [description]
     * @return [type]       [description]
     */
    protected function column_detail($item)
    {
        $color = 'salesloo-orange';

        if ($item->status == 'active') {
            $color = 'salesloo-green';
        } else if ($item->status == 'expired') {
            $color = 'salesloo-purple';
        }

        $expired_at = $item->expired_at ? $item->expired_at : 'onetime';

        $affiliate = get_userdata($item->get_affiliate_id());
        $affiliated_by = '';
        if ($affiliate) {
            $affiliated_by = $affiliate->user_login;
            $affiliated_by .= sprintf(' (%s)', $affiliate->user_email);
        }

        $invoices = $item->invoices();
        $inv = [];
        foreach ($invoices as $invoice) {
            $inv[] = $invoice->number;
        }

        $renew_price = salesloo_convert_money($item->get_renew_price());

        if (empty($item->expired_at) || date('Y-m-d', strtotime($item->expired_at)) == '1970-01-01') {
            $renew_price = '';
        }

        return sprintf(
            '<div><span class="salesloo-label" style="background:#82878C; color: #FFFFFF">%1$s</span></div>
            <div style="margin: 2px 0 2px 0;"><span class="salesloo-label" style="background:#00A0D2; color: #FFFFFF">%2$s</span></div>
            <div><span class="salesloo-label" style="background:#00A0D2; color: #FFFFFF">Date: %3$s</span></div>
            <div style="margin: 2px 0 2px 0;"><span class="salesloo-label" style="background:#00A0D2; color: #FFFFFF">Expired: %4$s</span></div>
            <div><span class="salesloo-label" style="background:#00A0D2; color: #FFFFFF">Affiliated By: %5$s</span></div>
            <div style="margin: 2px 0 2px 0;"><span class="salesloo-label" style="background:#00A0D2; color: #FFFFFF">Renew Price: %6$s</span></div>
            <div style="margin-top:5px;margin-bottom: 5px;"><span class="salesloo-label ' . $color . '">%7$s</span></div>
            <div>%8$s</div>',
            $item->code,
            implode(',', $inv),
            $item->created_at,
            $expired_at,
            $affiliated_by,
            $renew_price,
            ucfirst($item->status),
            '<a href="' . admin_url('/admin.php?page=salesloo-order&order_id=' . $item->ID) . '" class="button button-primary">' . __('Manage', 'salesloo') . '</a>'
        );
    }

    /**
     * Define column name
     * @param  [type] $item [description]
     * @return [type]       [description]
     */
    protected function column_customer($item)
    {
        $customer = get_userdata(($item->user_id));
        if ($customer->first_name) {
            $output = $customer->first_name . ' ' . $customer->last_name;
        } else {
            $output = $customer->display_name;
        }

        return sprintf(
            '<div style="font-weight: bold">%1$s</div><div style="font-size: 10px">(%2$s)</div><div style="font-size: 10px">(%3$s)</div><div style="font-size: 10px">(%4$s)</div>',
            $output,
            $customer->user_login,
            $customer->user_email,
            get_user_meta($customer->ID, 'phone', true)
        );
    }

    /**
     * Define column product
     * @param  [type] $item [description]
     * @return [type]       [description]
     */
    protected function column_product($item)
    {
        $product = salesloo_get_product($item->product_id);

        $nonce = wp_create_nonce('salesloo-update-order-access');
        $btn = '<a class="button salesloo-update-order-access" data-order-id="' . $item->ID . '" data-nonce="' . $nonce . '">' . __('Update Access', 'salesloo') . '</a>';

        if ($item->status != 'active') {
            $btn = '';
        }

        return sprintf(
            '<div style="font-weight: bold">%1$s</span></div><br/><div>%2$s</div>',
            $product->title,
            $btn
        );
    }

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

        return sprintf(
            '<textarea style="font-weight: bold" readonly>%1$s</textarea>',
            $item->code,
        );
    }

    protected function column_affiliate($item)
    {
        $affiliate = get_userdata($item->get_affiliate_id());

        $affiliated_by = '~';

        if ($affiliate) {
            $affiliated_by = salesloo_user_get_name($affiliate);
            $affiliated_by .= '<br/>';
            $affiliated_by .= sprintf('(%s)', $affiliate->user_email);
        }

        return sprintf(
            '<div>%1$s</div>',
            $affiliated_by,
        );
    }

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

        $color = 'salesloo-orange';

        if ($item->status == 'active') {
            $color = 'salesloo-green';
        } else if ($item->status == 'expired') {
            $color = 'salesloo-purple';
        }
        return sprintf(
            '<div style="text-align:right"><span class="salesloo-label ' . $color . '">%1$s</span></div>',
            ucfirst($item->status),
        );
    }

    protected function column_action($item)
    {
        $nonce = wp_create_nonce('salesloo-update-order-access');
        ob_start();
?>
        <a class="button salesloo-update-order-access" data-order-id="<?php echo $item->ID; ?>" data-nonce="<?php echo $nonce; ?>"><?php _e('Update Access', 'salesloo'); ?></a>
<?php
        $btn = ob_get_clean();

        if ($item->status != 'active') {
            $btn = '~';
        }

        return sprintf(
            '<div style="text-align:right">%1$s</div>',
            $btn,
        );
    }


    protected function get_bulk_actions()
    {
        return;
    }

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

        $order_query = Order::paginate($per_page, $this->get_pagenum())->order('ID', 'DESC');
        $sql = '';

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

        if (!empty($_REQUEST['status'])) :
            $status = sanitize_text_field($_REQUEST['status']);
            if ($status) {
                $sql .= sprintf(' status = %s', "'$status'");
            }
        endif;

        if ($sql) {
            $order_query->query("WHERE$sql");
        }

        $orders = $order_query->get();

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