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

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

    /**
     * get_views
     *
     * @return array
     */
    protected function get_views()
    {
        $statuses = salesloo_get_invoice_statuses();

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

        $link = admin_url('admin.php?page=salesloo-payment');
        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 array();
    }

    /**
     * Get columns
     * @return [type] [description]
     */
    public function get_columns()
    {
        $columns = array(
            //'cb'       => '<input type="checkbox" />',
            'number'   => __('Number', 'salesloo'),
            'customer' => __('Customer', 'salesloo'),
            'orders'   => __('Orders', 'salesloo'),
            'total'    => __('Total', 'salesloo'),
            'type'     => __('Type', 'salesloo'),
            'status'   => sprintf('<div style="text-align: right">%s</div>', __('Status', '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 number
     * @param  [type] $item [description]
     * @return [type]       [description]
     */
    protected function column_number($item)
    {

        return sprintf(
            '<div style="font-weight: bold">%1$s</div><div>%2$s</div>',
            $item->number,
            $item->created_at,
        );
    }

    /**
     * Define column customer
     * @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 orders
     * @param  [type] $item [description]
     * @return [type]       [description]
     */
    protected function column_orders($item)
    {
        $output = '';
        foreach ($item->orders() as $order) {
            $product = salesloo_get_product($order->product_id);
            $link = admin_url() . 'admin.php?page=salesloo-order&order_id=' . $order->ID;
            $output .= sprintf(
                '<a target="_blank" href="%1$s" style="font-weight: bold">%2$s</a>',
                $link,
                $product->title,
            );
            $output .= '<br/>';
        }

        return $output;
    }

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

        return sprintf(
            '<div>%1$s</div>',
            salesloo_convert_money($item->total)
        );
    }

    /**
     * Define column type
     * @param  [type] $item [description]
     * @return [type]       [description]
     */
    protected function column_type($item)
    {
        $type = __('New Order', 'salesloo');

        if ($item->type == 'renew_order') {
            $type = __('Renew Order', 'salesloo');
        }
        return sprintf(
            '<div>%1$s</span></a>',
            $type,
        );
    }

    /**
     * Define column status
     * @param  [type] $item [description]
     * @return [type]       [description]
     */
    protected function column_status($item)
    {
        $color = 'salesloo-orange';

        if ($item->status == 'checking_payment') {
            $color = 'salesloo-yellow';
        } else if ($item->status == 'completed') {
            $color = 'salesloo-green';
        } else if ($item->status == 'refunded') {
            $color = 'salesloo-purple';
        } else if ($item->status == 'cancelled') {
            $color = 'salesloo-purple';
        }

        $status = salesloo_get_invoice_statuses($item->status);

        $customer = get_userdata(($item->user_id));
        if ($customer->first_name) {
            $full_name = $customer->first_name . ' ' . $customer->last_name;
        } else {
            $full_name = $customer->display_name;
        }

        $summary = $item->summary;
        $products = $summary['products'];
        unset($summary['products']);

        $action = 'mark-invocice-status';
        $nonce = wp_create_nonce($action);
        $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
        $url = admin_url('admin-ajax.php?action=' . $action . '&__nonce=' . $nonce);

        if ($paged > 1) {
            $url = $url . '&paged=' . $paged;
        }

        $actions = [
            [
                'url'   => $url . '&status=completed&id=',
                'title' => __('Change invoice status to completed', 'salesloo'),
                'label' => __('Completed', 'salesloo'),
                'class' => 'button-primary'
            ],
            [
                'url'   => $url . '&status=refunded&id=',
                'title' => __('Change invoice status to Refunded', 'salesloo'),
                'label' => __('Refunded', 'salesloo'),
                'class' => ''
            ],
            [
                'url'   => $url . '&status=cancelled&id=',
                'title' => __('Change invoice status to cancelled', 'salesloo'),
                'label' => __('Cancelled', 'salesloo'),
                'class' => ''
            ]
        ];

        ob_start();
?>
        <div style="text-align:right">
            <span class="salesloo-label <?php echo $color; ?>"><?php echo $status; ?></span>
            <br />
            <br />
            <a href="#TB_inline?height=800&amp;width=320&amp;inlineId=invoice-<?php echo $item->ID; ?>" class="button thickbox" title="<?php echo $item->number; ?>"><?php _e('View', 'salesloo'); ?></a>
        </div>

        <div id="invoice-<?php echo $item->ID; ?>" style="display:none">
            <section>
                <header>
                    <h1 class="salesloo-label <?php echo $color; ?>" style="line-height:40px;border-radius: 5px;"><?php echo $status; ?></h1>
                </header>
                <article>
                    <div style="margin-bottom: 50px;">
                        <div>
                            <h3><?php _e('Customers :', 'salesloo'); ?></h3>
                            <strong><?php echo $full_name; ?></strong>
                            (<a href="mailto:<?php echo $customer->user_meial; ?>"><?php echo $customer->user_email; ?></a>)
                        </div>
                    </div>
                    <div style="margin-bottom: 50px;">
                        <div>
                            <h3><?php _e('Payment Method :', 'salesloo'); ?></h3>
                            <strong><?php echo \Salesloo\Plugin::instance()->payment_method->get($item->payment_method)->get_name(); ?></strong>
                        </div>
                    </div>
                    <div style="margin-bottom: 50px;">
                        <div>
                            <h3><?php _e('Due date :', 'salesloo'); ?></h3>
                            <strong><?php echo $item->due_date_at; ?></strong>
                        </div>
                    </div>
                    <div style="margin-bottom: 50px;">
                        <table cellspacing="0" class="widefat fixed striped" style="border:none">
                            <thead>
                                <tr style="border: 1px solid red">
                                    <th><?php _e('Product', 'salesloo'); ?></th>
                                    <th style="text-align: right"><?php _e('Total', 'salesloo'); ?></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                foreach ($products as $product) {
                                ?>
                                    <tr>
                                        <td style="font-weight:bold"><?php echo $product['label']; ?></td>
                                        <td style="text-align: right"><?php echo $product['print']; ?></td>
                                    </tr>
                                <?php

                                }
                                ?>
                            </tbody>
                        </table>
                        <table cellspacing="0" class="widefat fixed striped" style="border:none;margin-top:50px">
                            <tbody>
                                <?php
                                foreach ($summary as $summ) {
                                    $val = isset($summ['converted']['print']) ? $summ['converted']['print'] : $summ['print'];
                                ?>
                                    <tr>
                                        <td>
                                            <div><?php echo $summ['label']; ?></div>
                                            <div style="font-size:11px;font-style:italic"><?php echo $summ['message']; ?></div>
                                        </td>
                                        <td>
                                            <div style="text-align: right;font-weight:bold"><?php echo $val; ?></div>
                                        </td>
                                    </tr>
                                <?php

                                }
                                ?>
                            </tbody>
                        </table>
                    </div>

                </article>
                <footer>
                    <div class="inner">
                        <div>
                            <label><?php _e('Change status: ', 'salesloo'); ?></label>
                            <div style="margin-top:20px;">
                                <?php foreach ($actions as $action) : ?>
                                    <a class="button <?php echo $action['class']; ?>" href="<?php echo esc_url($action['url']) . $item->ID; ?>" title="<?php echo $action['title'] ?>"><?php echo $action['label']; ?></a>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>
                </footer>
            </section>
        </div>
<?php
        $html = ob_get_contents();
        ob_end_clean();

        return $html;
    }


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

        $invoice_query = Invoice::paginate($per_page, $this->get_pagenum())->order('ID', 'DESC');
        $where = [];

        if (!empty($_REQUEST['s'])) :
            $search = sanitize_text_field($_REQUEST['s']);
            $where[] = sprintf('number 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);
            $invoice_query->query("WHERE $where");
        }

        $invoices = $invoice_query->get();

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