<?php
defined('ABSPATH') or wp_die('Denied');
if (!class_exists('WP_List_Table')) {
    require_once(ABSPATH . 'wp-admin/includes/class-wp-list-table.php');
}
class NBDeliveryTable extends WP_List_Table
{
    public $type = "delivery";
    public $_stt_item = 0;

    public function __construct()
    {
        
        $args = array(
            'singular' => __('Delivery','netbase-smart-invoice'),
            'plural' => __('Delivery','netbase-smart-invoice'),
            'ajax' => false
        );
        parent::__construct($args);
    }
    function no_items() {
		_e( 'No Template Items','netbase-smart-invoice');
	}
    public function prepare_items()
    {
        $columns               = $this->get_columns();
        $hidden                = array();
        $sortable              = $this->get_sortable_columns();
        $this->_column_headers = array(
            $columns,
            $hidden,
            $sortable
        );
        
        $this->process_bulk_action();
        $per_page     = $this->get_items_per_page('delivery_per_page', 10);
        $current_page = $this->get_pagenum();
        $total_items  = self::record_count();
        $this->items  = self::getItemsList($per_page, $current_page);
        $this->set_pagination_args(array(
            'total_items' => $total_items,
            'per_page' => $per_page
        ));
    }

    function get_columns()
    {
        $columns = array(
            'cb' => '<input type="checkbox" />',
            'id' => __('STT','netbase-smart-invoice'),
            'name_template' => __('Name','netbase-smart-invoice'),
            'public' => __('Published','netbase-smart-invoice')
        );
        return $columns;
    }
    function column_id($item)
    {
        $_number = $this->_stt_item + 1;
        $this->_stt_item = $_number;
        return $_number;
    }

    public function get_sortable_columns()
    {
        $sortable_columns = array(
            'name_template' => array(
                'name_template',
                true
            ),
            'public' => array(
                'public',
                true
            )
        );
        
        return $sortable_columns;
    }
    function column_default($item, $column_name)
    {
        switch ($column_name) {
            case 'id':
            case 'name_template':
            case 'public':
                return $item[$column_name];
            default:
                return print_r($item, true);
        }
    }

    function column_cb($item)
    {
        return sprintf('<input type="checkbox" name="bulk-delete[]" value="%s" />', $item['id']);
    }

    function column_public($item)
    {
        $w_nonce = wp_create_nonce('nb_public_delivery');
        $link    = '?page=' . esc_attr($_REQUEST['page'],'netbase-smart-invoice') . '&btask=changeInpublic&id=' . absint($item['id']) . '&_wpnonce=' . $w_nonce;
        switch ($item['public']) {
            case 1:
                return '<span class="button button_public_row button-primary">Public</span>';
                break;
            case 0:
                return 'UnPublic';
                break;
        }
    }

    function column_name_template($item)
    {
        
        $delete_nonce = wp_create_nonce('nb_delete_delivery');
        
        $title = '<strong><a class="row-title" href="?page=nb-smart-invoice-create-pages&edit='. $item['id'] .'&type_template=delivery">' . $item['name_template'] . '</a></strong>';
        
        $actions = array(
            'edit' => sprintf('<a href="?page=nb-smart-invoice-create-pages&edit='. $item['id'] .'&type_template=delivery">Edit</a>', esc_attr($_REQUEST['page'],'netbase-smart-invoice'), 'addInvoice', absint($item['id']), $delete_nonce, $this->type),
            'delete' => sprintf('<a href="?page=nb-smart-invoice-create-pages&delete='. $item['id'] .'&type_template=delivery">Delete</a>', esc_attr($_REQUEST['page'],'netbase-smart-invoice'), 'delete', absint($item['id']), $delete_nonce, $this->type)
        );
        
        return $title . $this->row_actions( $actions );
    }

    public function getItemsList($per_page = 10, $page_number = 1)
    {
        
        global $wpdb;
        
        $sql = "SELECT * FROM {$wpdb->prefix}netbase_invoice_templates WHERE type ='" . esc_sql($this->type) . "'";
        
        if (!empty($_REQUEST['orderby'])) {
            $sql .= ' ORDER BY ' . esc_sql($_REQUEST['orderby']);
            $sql .= !empty($_REQUEST['order']) ? ' ' . esc_sql($_REQUEST['order']) : ' ASC';
        }
        if (empty($_REQUEST['orderby'])) {
            $sql .= ' ORDER BY id DESC' ;
        }
        
        $sql .= " LIMIT $per_page";
        
        $sql .= ' OFFSET ' . ($page_number - 1) * $per_page;
        
        $result = $wpdb->get_results($sql, 'ARRAY_A');
        
        return $result;
    }

    public function get_bulk_actions()
    {
        $actions = array(
            'bulk-delete' => 'Delete'
        );
        
        return $actions;
    }
    public function process_bulk_action()
    {
        
        $link = sprintf('?page=%s', esc_attr($_REQUEST['page'],'netbase-smart-invoice'));
        $link = add_query_arg('tab', @$_REQUEST['tab'], $link);
        if ('delete' === $this->current_action()) {

            $nonce = esc_attr($_REQUEST['_wpnonce'],'netbase-smart-invoice');
            
            if (!wp_verify_nonce($nonce, 'nb_delete_delivery')) {
                wp_die(__('Go get a life script kiddies','netbase-smart-invoice'));
            } else {
                self::delivery_checkDemo();
                self::delete_invoice(absint($_GET['id']));
                self::NB_delivery_addMsg(__('Item is deleted','netbase-smart-invoice'));
                wp_redirect(esc_url(add_query_arg('msg', 'updated', $link)));
                exit;
            }
            
        }
        
        if ((isset($_POST['action']) && $_POST['action'] == 'bulk-delete') || (isset($_POST['action2']) && $_POST['action2'] == 'bulk-delete')) {
            self::delivery_checkDemo();
            $delete_ids = esc_sql($_POST['bulk-delete']);
            
            foreach ($delete_ids as $id) {
                self::delete_invoice($id);
                
            }
            if (count($delete_ids) > 1)
            self::NB_delivery_addMsg(__('Items are deleted','netbase-smart-invoice'));
            else
            self::NB_delivery_addMsg(__('Item is deleted','netbase-smart-invoice'));

            wp_redirect(esc_url(add_query_arg('msg', 'updated', $link)));
            exit;
        }
    }
    public static function delete_invoice($id)
    {
        self::delivery_checkDemo();
        global $wpdb;
        
        $wpdb->delete("{$wpdb->prefix}netbase_invoice_templates", array(
            'id' => $id
        ), array(
            '%d'
        ));
    }

    public function record_count()
    {
        global $wpdb;
        
        $sql = "SELECT COUNT(*) FROM {$wpdb->prefix}netbase_invoice_templates WHERE type ='" . esc_sql($this->type) . "'";
        
        return $wpdb->get_var($sql);
    }

    public function getTemplateByIdDelivery($id){
        global $wpdb;
        
        $sql = "SELECT * FROM {$wpdb->prefix}netbase_invoice_templates WHERE id=" . $id . " AND type ='" . esc_sql($this->type) . "'";
        
        $result = $wpdb->get_results($sql, 'ARRAY_A');
        
        return $result[0];
    }

    public static function delivery_checkDemo() {
        if(NETBASE_TEPLATE_DEMO == true) {
            self::NB_delivery_addMsg(__('You are use Demo Mode, so some buttons, functions will be disabled because of security. You can use them in Live mode after you puchase our plugin.','netbase-smart-invoice'));
            wp_redirect( esc_url('?page=nb-smart-delivery-listing-pages') );
            exit();
        }
    }
    public static function NB_delivery_addMsg($msg, $type='') {
        if(!isset($_SESSION["invoice_msg"])) {
            $_SESSION["invoice_msg"] = array();
        }
        $_SESSION["invoice_msg"][] = array($msg, $type);
    }
}