<?php
if (!class_exists('WP_List_Table')) {
    require_once ABSPATH . 'wp-admin/includes/class-wp-list-table.php';
}

class Dealer_list extends WP_List_Table {

    /**
     * This is variable which is used for the store all the data.
     *
     * @var array $example_data variable for store data.
     */
    public $table_data;

    /**
     * This is variable which is used for the total count.
     *
     * @var array $table_row_total_count variable for total count.
     */
    public $table_row_total_count;

    /**
     * This construct colomns in contacts report table.
     *
     * @name get_columns.
     * @since      1.0.0
     */
    public function get_columns() {

        $columns = array(
            'cb' 				=> '<input type="checkbox" />',
            'license_number'	=> __('License number', 'ffl-dealers'),
            'license_name'		=> __('License name', 'ffl-dealers'),
            'business_name'		=> __('Business name', 'ffl-dealers'),
            'premise_street'	=> __('Street', 'ffl-dealers'),
            'premise_city'		=> __('City', 'ffl-dealers'),
            'premise_state'		=> __('State', 'ffl-dealers'),
            'premise_zip_code'	=> __('Zipcode', 'ffl-dealers'),
            'voice_phone'		=> __('Phone', 'ffl-dealers'),
            'action'			=> __('Action', 'ffl-dealers'),
        );
        return apply_filters('ffl_dealers_table_column', $columns);
    }
	
    /**
     * This show susbcriptions table list.
     *
     * @name column_default.
     * @since      1.0.0
     * @param array  $item  array of the items.
     * @param string $column_name name of the colmn.
     */
    public function column_default($item, $column_name) {
		if($column_name == 'action'){
			$status = ($item['check_status'] ==1)?__('Active','ffl-dealers'):__('Deactive','ffl-dealers');
			$actions = [];
			$actions['delete'] = sprintf('<a href="%s" class="submitdelete" onclick="return confirm(\'Are you sure?\');" title="%s">%s</a>', wp_nonce_url(admin_url('admin-post.php?action=delete-dealer&id=' . $item['id']), 'ffl-dealers'), $item['id'], __('Delete', 'ffl-dealers'), __('Delete', 'ffl-dealers'));
			$actions['edit']   = sprintf( '<a href="%s" title="%s">%s</a>', admin_url( 'admin.php?page=ffl-dealers&action=edit&id=' . $item['id'] ), $item['id'], __( 'Edit', 'ffl-dealers' ), __( 'Edit', 'ffl-dealers' ) );
			return sprintf(
				'<a href="%1$s"><strong>%2$s</strong></a> %3$s', '', $status, $this->row_actions($actions)
			);
		}else{
			return isset($item[$column_name])?$item[$column_name]:'';
		}
		
        
    }
    /**
     * Perform admin bulk action setting for contacts table.
     *
     * @name process_bulk_action.
     */
    public function process_bulk_action() {
		global $wpdb; 	
		$table_name = $wpdb->prefix . 'ffl_dealers ';
        if ('bulk-delete' === $this->current_action()) {
                if (wp_verify_nonce($_POST['ffl_dealer_list_table_fields'], 'ffl_dealer_list_table_fields_nonce')) {
                    if (isset($_POST['dealer_ids']) && !empty($_POST['dealer_ids'])) {
                        $all_id = $_POST['dealer_ids'];
						if(is_array($all_id)){
							foreach ($all_id as $key => $id) {
								$contact_id = sanitize_text_field( $id );
								$wpdb->delete($table_name, ['id' => $contact_id]);
							}
						}
                    }
                }
            
            ?>
            <div class="notice notice-success is-dismissible"> 
                <p><strong><?php esc_html_e('User deleted Successfully', 'biogas-calculator'); ?></strong></p>
            </div>
            <?php
        }
        do_action('ffl_dealer_bulk_action', $this->current_action(), $_POST);
    }

    /**
     * Returns an associative array containing the bulk action
     *
     * @name process_bulk_action.
     * @since      1.0.0
     * @return array
     */
    public function get_bulk_actions() {
        $actions = array(
            'bulk-delete' => __('Delete', 'ffl_dealer'),
        );
        return apply_filters('ffl_dealer_bulk_option', $actions);
    }

    /**
     * Returns an associative array containing the bulk action for sorting.
     *
     * @name get_sortable_columns.
     * @since      1.0.0
     * @return array
     */
    public function get_sortable_columns() {
        $sortable_columns = array(
            'created_at' => array('created_at', false),
        );
        return $sortable_columns;
    }

    /**
     * Prepare items for sorting.
     *
     * @name prepare_items.
     * @since      1.0.0
     */
    public function prepare_items() {
        $per_page = 5;
        $columns = $this->get_columns();
        $hidden = array();
        $sortable = $this->get_sortable_columns();
        $this->_column_headers = array($columns, $hidden, $sortable);
        $this->process_bulk_action();
        $current_page = $this->get_pagenum();
        $this->table_data = $this->get_ffl_dealer_list();
        $data = $this->table_data;
        usort($data, array($this, 'ffl_dealer_usort_reorder'));
        $data = array_slice($data, ( ( $current_page - 1 ) * $per_page), $per_page);
        $total_items = $this->table_row_total_count;
        $this->items = $data;
        $this->set_pagination_args(
                array(
                    'total_items' => $total_items,
                    'per_page' => $per_page,
                    'total_pages' => ceil($total_items / $per_page),
                )
        );
    }

    /**
     * Return sorted associative array.
     *
     * @name ffl_dealer_usort_reorder.
     * @since      1.0.0
     * @return array
     * @param array $cloumna column of the contacts report.
     * @param array $cloumnb column of the contacts report.
     */
    public function ffl_dealer_usort_reorder($cloumna, $cloumnb) {

        $orderby = (!empty($_REQUEST['orderby']) ) ? sanitize_text_field(wp_unslash($_REQUEST['orderby'])) : 'created_at';
        $order = (!empty($_REQUEST['order']) ) ? sanitize_text_field(wp_unslash($_REQUEST['order'])) : 'desc';

        if (is_numeric($cloumna[$orderby]) && is_numeric($cloumnb[$orderby])) {
            if ($cloumna[$orderby] == $cloumnb[$orderby]) {
                return 0;
            } elseif ($cloumna[$orderby] < $cloumnb[$orderby]) {
                $result = -1;
                return ( 'asc' === $order ) ? $result : -$result;
            } elseif ($cloumna[$orderby] > $cloumnb[$orderby]) {
                $result = 1;
                return ( 'asc' === $order ) ? $result : -$result;
            }
        } else {
            $result = strcmp($cloumna[$orderby], $cloumnb[$orderby]);
            return ( 'asc' === $order ) ? $result : -$result;
        }
    }

    /**
     * THis function is used for the add the checkbox.
     *
     * @name column_cb.
     * @since      1.0.0
     * @return array
     * @param array $item array of the items.
     */
    public function column_cb($item) {
        return sprintf(
                '<input type="checkbox" name="dealer_ids[]" value="%s" />',
                $item['id']
        );
    }

    /**
     * This function used to get all contacts reports list.
     *
     * @name get_ffl_dealer_list.
     * @since      1.0.0
     * @return array
     */
    public function get_ffl_dealer_list() {
		global $wpdb;
		$table_name = $wpdb->prefix.'ffl_dealers  ';
		 $search_text = "%%";
		if (isset($_REQUEST['s']) && !empty($_REQUEST['s'])) {
			$search_request_text = sanitize_text_field($_REQUEST['s']);
			$search_text = "%".$search_request_text."%";
        }
        $results = $wpdb->get_results( 
                $wpdb->prepare( "SELECT * FROM {$table_name} WHERE voice_phone LIKE %s",$search_text),
				ARRAY_A
        );
		$total_count = count( $results);	
        $this->table_row_total_count = $total_count;
        return $results;
    }

    /**
     * Create the extra table option.
     *
     * @name extra_tablenav.
     * @since      1.0.0
     * @param string $which which.
     */
    public function extra_tablenav($which) {
        do_action('ffl_dealer_extra_tablenav_html', $which);
    }

}