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

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

    /**
     * Get columns
     * @return array [description]
     */
    public function get_columns()
    {
        $columns = array(
            'code'      => __('Purchase Code', 'salesloo'),
            'user'      => __('User', 'salesloo'),
            'Item'      => __('Item', 'salesloo'),
            //'limitused' => __('Activation', 'salesloo'),
            'action'    => sprintf('<div style="text-align: center">%s</div>', __('Activation', 'salesloo')),
        );
        return $columns;
    }

    /**
     * Define column code
     * @param  [type] $item [description]
     * @return [type]       [description]
     */
    protected function column_code($item)
    {
        return sprintf(
            '<div style="width:300px;">%1$s</div>',
            $item->code,
        );
    }


    /**
     * Define column user
     * @param  [type] $item [description]
     * @return [type]       [description]
     */
    protected function column_user($item)
    {
        $customer = get_userdata(($item->user_id));

        if (!$customer) return;

        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>',
            $output,
            $customer->user_login,
            $customer->user_email
        );
    }

    /**
     * Define column item
     * @param  [type] $item [description]
     * @return [type]       [description]
     */
    protected function column_item($item)
    {
        $post = get_post($item->item_id);

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

    /**
     * Define column limitused
     * @param  [type] $item [description]
     * @return [type]       [description]
     */
    protected function column_limitused($item)
    {
        $used = $item->meta('license') ? count((array)$item->meta('license')) : 0;
        $limitused = $item->license_limit . '/' . $used;

        return sprintf(
            '<div style="">%1$s</div>',
            $limitused,
        );
    }

    /**
     * define column total hit
     * @param  [type] $item [description]
     * @return [type]       [description]
     */
    protected function column_action($item)
    {
        $order = salesloo_get_order($item->order_id);
        $used = $item->meta('license') ? count((array)$item->meta('license')) : 0;
        $limitused = $used . '/' . $order->get_license_limit();

        $licenses = [];
        foreach ((array)$item->meta('license') as $license) {
            $data = salesloo_get_access_meta($item->ID, 'license_' . $license, true);
            if ($data) {
                $licenses[] = [
                    'host' => $license,
                    'activate_at' => $data['activate_at'],
                    'last_checked' => $data['last_checked'],
                ];
            }
        }

        $license_url = admin_url('edit.php?post_type=salesloo-file&page=license&code=' . $item->code);

        $nonce = wp_create_nonce('salesloo-delete-access-license-host');

        ob_start();

        echo sprintf(
            '<div style="text-align:center;font-weight:bold;color:red;margin-bottom: 10px;">%1$s</div>',
            $limitused,
        );
?>
        <div style="text-align:right">
            <a href="<?php echo $license_url; ?>" class="button" title="<?php _e('Manage License') ?>"><?php _e('Manage License', 'salesloo'); ?></a>
        </div>

        <div style="text-align:right;display:none">
            <a href="#TB_inline?height=800&amp;width=600&amp;inlineId=invoice-<?php echo $item->ID; ?>" class="button thickbox" title="<?php _e('Manage License') ?>"><?php _e('Manage', 'salesloo'); ?></a>
        </div>

        <div id="invoice-<?php echo $item->ID; ?>" style="display:none">
            <section>
                <article>
                    <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('Host', 'salesloo'); ?></th>
                                    <th><?php _e('Activate Date', 'salesloo'); ?></th>
                                    <th><?php _e('Last Checked Date', 'salesloo'); ?></th>
                                    <th>&nbsp;</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                foreach ($licenses as $license) {
                                ?>
                                    <tr>
                                        <td><?php echo $license['host']; ?></td>
                                        <td><?php echo $license['activate_at']; ?></td>
                                        <td><?php echo $license['last_checked']; ?></td>
                                        <td style="text-align:right">
                                            <span class="dashicons dashicons-dismiss salesloo-delete-access-license-host" style="cursor:pointer" data-host="<?php echo $license['host']; ?>" data-access-id="<?php echo $item->ID; ?>" data-nonce="<?php echo $nonce; ?>"></span>
                                        </td>
                                    </tr>
                                <?php
                                }
                                ?>
                            </tbody>
                        </table>
                    </div>

                </article>
                <footer>
                    <div class="inner">
                        <div>

                        </div>
                    </div>
                </footer>
            </section>
        </div>
    <?php

        $html = ob_get_contents();
        ob_end_clean();

        return $html;
    }


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

        $wheres = [
            'meta_key = "enable_license"',
            'code != ""'
        ];

        if (isset($_GET['s'])) {
            $wheres[] =  'code = "' . sanitize_text_field($_GET['s']) . '"';
        }

        $query = '';

        if ($wheres) {
            $ww = implode(' AND ', $wheres);
            $query = <<<SQL
                WHERE $ww
            SQL;
        }

        $access = Access::join('left', 'salesloo_order', ['order_id', 'ID', '='])
            ->join('left', 'postmeta', ['item_id', 'post_id', '='])
            ->select(
                ['salesloo_access.*'],
                ['salesloo_order.code'],
                ['salesloo_order.user_id'],
                ['salesloo_order.product_id'],
                ['salesloo_order.status'],
                ['{prefix}postmeta.meta_value as enable_license']
            )
            ->query($query)
            ->paginate($per_page, $this->get_pagenum())
            ->order('created_at', 'DESC')
            ->get();

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

    public function search_box($text, $input_id)
    {
        if (empty($_REQUEST['s']) && !$this->has_items()) {
            return;
        }

        $input_id = $input_id . '-search-input';
    ?>
        <input type="hidden" name="post_type" value="salesloo-file" />
        <input type="hidden" name="page" value="license" />
        <p class="search-box">
            <label class="screen-reader-text" for="<?php echo esc_attr($input_id); ?>"><?php echo $text; ?>:</label>
            <input type="search" id="<?php echo esc_attr($input_id); ?>" name="s" value="<?php _admin_search_query(); ?>" />
            <?php submit_button($text, '', '', false, array('id' => 'search-submit')); ?>
        </p>
<?php
    }
}
