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

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

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

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

        $link = admin_url('admin.php?page=salesloo-product');
        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" />',
            'thumbnail' => __('Thumbnail', 'salesloo'),
            'title'     => __('Title', 'salesloo'),
            'duration'  => sprintf('<div style="text-align:right">%s</div>', __('Duration', '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 profile pic
     * @param  [type] $item [description]
     * @return [type]       [description]
     */
    protected function column_thumbnail($item)
    {
        return sprintf(
            '<div style="width: 100px;height:100px;position: relative;"><img src="%1$s" style="height: auto;max-width:%2$s;"/></div>',
            $item->get_thumbnail_url(),
            '100%'
        );
    }

    /**
     * Define column name
     * @param  [type] $item [description]
     * @return [type]       [description]
     */
    protected function column_title($item)
    {
        $checkout_link = salesloo_url_checkout($item->slug);

        return sprintf(
            '<div style="font-weight:bold;margin-bottom:5px;">%1$s</div><div><a href="%2$s" target="_blank">Checkout Link</a></div>',
            $item->title,
            $checkout_link
        );
    }

    /**
     * Define column locale
     * @param  [type] $item [description]
     * @return [type]       [description]
     */
    protected function column_duration($item)
    {
        $duration = salesloo_translate_product_duration($item->duration);

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

    /**
     * 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-product&product_id=' . intval($item_id)) . '" class="button">Edit</a>';
        echo '&nbsp;';
        //echo '<a href="admin.php?page=salesloo-product&delete=" class="button">Delete</a>';
        echo '</div>';

        $html = ob_get_contents();
        ob_end_clean();

        return $html;
    }

    protected function get_bulk_actions()
    {
        $actions = array(
            'deleted' => __('Delete', 'salesloo'),
            'activated' => __('Activated', 'salesloo'),
            'inactivated' => __('Inactivated', 'salesloo'),
            'drafted' => __('Drafted', 'salesloo'),
        );
        return $actions;
    }
    /**
     * Handle bulk actions.
     *
     * Optional. You can handle your bulk actions anywhere or anyhow you prefer.
     * For this example package, we will handle it in the class to keep things
     * clean and organized.
     *
     * @see $this->prepare_items()
     */
    protected function process_bulk_action()
    {

        if (!isset($_REQUEST['_wpnonce'])) return;

        if (check_admin_referer('bulk-' . $this->_args['plural'])) {
            $products = isset($_GET['product']) ? (array)$_GET['product'] : [];
            // Detect when a bulk action is being triggered.
            if ('deleted' === $this->current_action()) {
                foreach ($products as $key => $id) {
                    salesloo_delete_product($id);
                }
            }

            if ('activated' === $this->current_action()) {
                foreach ($products as $key => $id) {
                    salesloo_update_product_status($id, 'active');
                }
            }

            if ('inactivated' === $this->current_action()) {
                foreach ($products as $key => $id) {
                    salesloo_update_product_status($id, 'inactive');
                }
            }

            if ('drafted' === $this->current_action()) {
                foreach ($products as $key => $id) {
                    salesloo_update_product_status($id, 'draft');
                }
            }
        }
    }

    protected function extra_tablenav($which)
    {
        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();

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

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

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

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

        $products = $product_query->get();

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