<?php
defined('ABSPATH') or die("You can't access this file directly.");

/**
 * PART 2. Defining Custom Table List
 * ============================================================================
 */

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

/**
 * qcld_seohelp_Scan_result_List_Table class that will display our custom table
 * records in nice table
 */
class qcld_seohelp_Scan_result_List_Table extends WP_List_Table
{
    /**
     * [REQUIRED] You must declare constructor and give some basic params
     */
    function __construct()
    {
        global $status, $page;

        parent::__construct(array(
            'singular'  => 'qcld-seo-help-scan',
            'plural'    => esc_html('Seo Help', 'seo-help'),
            'ajax'      => true
        ));
    }


    /**
     * [OPTIONAL] this is example, how to render specific column
     *
     */
    function column_anchor($item)
    {
        //return $item['anchor'];
        /*$actions = array(
            'edit'          => sprintf('<a href="?page=qcld-seo-help-scan&view=edit_scan&id=%s">%s</a>', $item['loc_id'], __('Edit anchor text', 'seo-help')),
        );*/

        $actions = array();

        return sprintf('%s %s',
            $item['anchor'],
            $this->row_actions($actions)
        );
        
    }

    /**
     * [OPTIONAL] this is example, how to render specific column
     *
     */
    function column_content($item)
    {
    	//return $item['content'];Edit anchor text

        $item_content = $item['content'];
        if($item_content )

        $actions = array(
            'edit'          => sprintf('<a href="%s" target="_blank">%s</a>', $item['object_edit'], esc_html('Edit', 'seo-help')),
            'delete'        => sprintf('<a href="%s" target="_blank">%s</a>', $item['object_trash'], esc_html('Trash', 'seo-help')),
            'show_results'  => sprintf('<a href="%s" target="_blank">%s</a>', $item['object_view'], esc_html('View', 'seo-help')),
        );

        return sprintf('%s %s',
            $item['content'],
            $this->row_actions($actions)
        );
    	
    }

    /**
     * [OPTIONAL] this is example, how to render column with actions,
     * when you hover row "Edit | Delete" links showed
     */
    function column_chunk($item)
    {

       // return $item['chunk'];
        $actions = array(
            'visit' => sprintf('<a href="%s" target="_blank">%s</a>', $item['chunk'], esc_html('Visit URL', 'seo-help')),
        );

        return sprintf('%s %s',
            $item['chunk'],
            $this->row_actions($actions)
        );
    }

     function column_status_code($item)
    {
    	//return $item['status_code'];

        $actions = array();

        $status_check = esc_attr($item['status_code'], 'seo-help');

        switch ($status_check) {
            case "200":
                $status_check = '<p><strong style="color:green">'.$status_check. ' '.esc_html(' OK ', 'seo-help').' </strong></p>';
                break;
            default:
                $status_check = '<p><strong style="color:red">'.$status_check. ' '.esc_html(' Not Found ', 'seo-help').' </strong></p>';
        }

        return sprintf('%s %s',
            $status_check,
            $this->row_actions($actions)
        );
    }

    /**
     * [REQUIRED] this is how checkbox column renders
     */
    function column_cb($item)
    {
        return sprintf(
            '<input type="checkbox" name="id[]" value="%s" />',
            $item['loc_id']
        );
    }

    /**
     * [REQUIRED] This method return columns to display in table
     */
    function get_columns()
    {
        $columns = array(
            'cb' 		=> '<input type="checkbox" />',
            'chunk' 	=> esc_html('URL', 'seo-help'),
        );
        //return $columns;
		
		// All columns
		return array_merge($columns, array(
            'status_code' 	=> esc_html('Status', 'seo-help'),
            'anchor'        => esc_html('Anchor Text', 'seo-help'),
            'content'       => esc_html('Content',  'seo-help'),
		));

    }

    /**
     * This method return columns that may be used to sort table
     */
    function get_sortable_columns()
    {
        $sortable_columns = array(
            'chunk'         => array('chunk', true),
            'status_code'   => array('status_code', true),
            'anchor'        => array('anchor', false),
            'content' 	    => array('content', false),
        );

        return $sortable_columns;
    }

    /**
     * Return array of bult actions if has any
     */
    function get_bulk_actions()
    {
        $actions = array(
            'delete' => 'Delete'
        );
        return $actions;
    }

    /**
     * This method processes bulk actions
     */
    function process_bulk_action()
    {
        global $wpdb;
        $table_name = $wpdb->prefix . 'qcld_seohelp_urls_locations'; // do not forget about tables prefix

        if ('delete' === $this->current_action()) {
            $ids = isset($_GET['id']) ? sanitize_text_field(wp_unslash($_GET['id'])) : array();
            if (is_array($ids)) $ids = implode(',', $ids);

            if (!empty($ids)) {
                $wpdb->query("DELETE FROM $table_name WHERE loc_id IN($ids)");
            }
        }
    }

    /**
     * It will get rows from database and prepare them to be showed in table
     */
    function prepare_items()
    {
        global $wpdb;
        $id  = isset($_GET['id']) ? sanitize_text_field(wp_unslash($_GET['id'])) : ''; // constant, how much records will be shown per page

        $msg  = isset($_GET['msg']) ? sanitize_text_field(wp_unslash($_GET['msg'])) : '';
        
        $table_name = $wpdb->prefix . "qcld_seohelp_urls_locations"; // do not forget about tables prefix

        $per_page = 20; // constant, how much records will be shown per page

        $columns = $this->get_columns();
        // Data items
		//$columns = $this->setup_items();
        $hidden = array();
        $sortable = $this->get_sortable_columns();

        // here we configure table headers, defined in our methods
        $this->_column_headers = array($columns, $hidden, $sortable);

        // [OPTIONAL] process bulk action if any
        $this->process_bulk_action();

        // will be used in pagination settings
        if(empty($msg)){
        $total_items = $wpdb->get_var("SELECT COUNT(loc_id) FROM $table_name WHERE scan_id IN($id)" );
        }else{
        $total_items = $wpdb->get_var("SELECT COUNT(loc_id) FROM $table_name WHERE status_code=$msg AND scan_id IN($id)");            
        }

        // prepare query params, as usual current page, order by and order direction
        $paged = isset($_GET['paged']) ? intval(sanitize_text_field(wp_unslash($_GET['paged']))) : 1;
        $orderby = (isset($_GET['orderby']) && in_array($_GET['orderby'], array_keys($this->get_sortable_columns()))) ? sanitize_text_field(wp_unslash($_GET['orderby'])) : 'loc_id';
        $order = (isset($_GET['order']) && in_array($_GET['order'], array('asc', 'desc'))) ? sanitize_text_field(wp_unslash($_GET['order'])) : 'desc';

        $offset   = ( $paged * $per_page ) - $per_page;

        // [REQUIRED] define $items array
        // notice that last argument is ARRAY_A, so we will retrieve array
        if(empty($msg)){
            $this->items = $wpdb->get_results("SELECT * FROM $table_name  WHERE scan_id IN($id) ORDER BY $orderby $order LIMIT $per_page OFFSET $offset", ARRAY_A);  
        }else{
            $this->items = $wpdb->get_results("SELECT * FROM $table_name  WHERE status_code=$msg AND scan_id IN($id) ORDER BY $orderby $order LIMIT $per_page OFFSET $offset", ARRAY_A);  

        }

        // [REQUIRED] configure pagination
        $this->set_pagination_args(array(
            'total_items' 	=> $total_items, // total items defined above
            'per_page' 		=> $per_page, // per page constant defined at top of method
            'total_pages' 	=> ceil($total_items / $per_page) // calculate pages count
        ));
    }
}


/**
 * List page handler
 */
function qcld_seohelp_scan_result_data_view()
{
    global $wpdb;

    $table = new qcld_seohelp_Scan_result_List_Table();
    $table->prepare_items();

    $id = isset($_GET['id']) ? sanitize_text_field(wp_unslash( $_GET['id'] )) : '';

    $message = '';
    if ('delete' === $table->current_action()) {
        $message = '<div class="updated below-h2" id="message"><p>' . sprintf(esc_html('Items deleted: %d', 'seo-help'), count($id) ) . '</p></div>';
    }
    ?>

	<div class="wrap">

	    <div class="icon32 icon32-posts-post" id="icon-edit"><br></div>
	    <h2><?php esc_html_e('Scan Results', 'seo-help')?> </h2>
	    <?php 

        echo wp_kses_post(isset($message) ? $message : ''); 
        $wp_create_nonce = wp_create_nonce( 'seo-help' );
        ?>
        <?php $seo_help_url = esc_url(admin_url('admin.php?page=qcld-seo-help-scan')); ?>
        <div style="margin: 15px 0 15px 0;">
            <a href="<?php echo esc_url($seo_help_url); ?>" class="button button-secondary">
                <span class="dashicons dashicons-arrow-left-alt"></span>
                <?php esc_html_e('Back to Scan Results Page', 'seo-help'); ?>
            </a>
        </div>
        <div class="qcld-sorting below-h2" id="message">
            <a href="<?php echo esc_url(admin_url('admin.php?page=qcld-seo-help-scan&view=view_scan&id='.esc_attr($id).'&_wpnonce='.$wp_create_nonce )); ?>"><?php esc_html_e('All Results', 'seo-help')?></a>
            <a href="<?php echo esc_url(admin_url('admin.php?page=qcld-seo-help-scan&view=view_scan&id='.esc_attr($id).'&msg=200&_wpnonce='.$wp_create_nonce)); ?>"><?php esc_html_e('200s Success', 'seo-help')?></a>
            <a href="<?php echo esc_url(admin_url('admin.php?page=qcld-seo-help-scan&view=view_scan&id='.esc_attr($id).'&msg=404&_wpnonce='.$wp_create_nonce)); ?>"><?php esc_html_e('404s Errors', 'seo-help')?></a>
        </div>

	    <form id="qcld-scan-body-result-table" method="GET">
	        <input type="hidden" name="page" value="<?php echo esc_attr(isset($_GET['page']) ? sanitize_text_field(wp_unslash($_GET['page'])) : 'page'); ?>"/>
	        <?php $table->display() ?>
	    </form>

	</div>


<?php
	

}






