<?php
/**
 * Created by PhpStorm.
 * User: UGEN79
 * Date: 2015/8/6
 * Time: 16:51
 */


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


class viewHouseList extends WP_List_Table
{
    function __construct()
    {
        global $status, $page;
        //Set parent defaults
        parent::__construct(array(
            'singular' => 'house',     //singular name of the listed records
            'plural' => 'houses',    //plural name of the listed records
            'ajax' => false        //does this table support ajax?
        ));

    }

    function column_default($item, $column_name)
    {
        switch ($column_name) {
            case 'name':
                $handle = $item['handle'];
                if ($handle == 0) {
                    return '<a href="' . admin_url() . 'admin.php?page=view_house&id=' . $item['id'] . '">' . $item[$column_name] . '</a>';
                } else {
                    return $item[$column_name];
                }
            case 'handle':
                $handle = $item[$column_name];
                if ($handle == 1) {
                    return '已处理';
                } else {
                    return '未处理';
                }
            case 'handle_date':
                $handle = $item['handle'];
                if ($handle == 1) {
                    return $item[$column_name];
                } else {
                    return false;
                }
            default:
                return $item[$column_name];
        }
    }

    function column_title($item)
    {
        //Build row actions
        $actions = array(
            'edit' => sprintf('<a href="?page=%s&action=%s&house=%s">Edit</a>', $_REQUEST['page'], 'edit', $item['ID']),
            'delete' => sprintf('<a href="?page=%s&action=%s&house=%s">Delete</a>', $_REQUEST['page'], 'delete', $item['ID']),
        );

        //Return the title contents
        return sprintf('%1$s <span style="color:silver">(id:%2$s)</span>%3$s',
            /*$1%s*/
            $item['title'],
            /*$2%s*/
            $item['ID'],
            /*$3%s*/
            $this->row_actions($actions)
        );
    }

    function column_cb($item)
    {
        return sprintf(
            '<input type="checkbox" name="%1$s[]" value="%2$s" />',
            /*$1%s*/
            $this->_args['singular'],  //Let's simply repurpose the table's singular label ("house")
            /*$2%s*/
            $item['ID']                //The value of the checkbox should be the record's id
        );
    }

    function get_columns()
    {
        $columns = array(
            'cb' => '<input type="checkbox">', //Render a checkbox instead of text
            'name' => '楼盘名/房源名',
            'date' => '时间',
            'phone' => '手机号',
            'consultant' => '置业顾问',
            'handle' => '处理状态',
            'handle_date' => '处理时间'
        );
        return $columns;
    }

    function get_sortable_columns()
    {
        $sortable_columns = array(
            'name' => array('name', false),
            'date' => array('date', false),
            'phone' => array('phone', false),
            'consultant' => array('consultant', false),
            'handle' => array('handle', false),
            'handle_date' => array('handle_date', false)
        );
        return $sortable_columns;
    }

    function get_bulk_actions()
    {
        $actions = array(
            'delete' => 'Delete'
        );
        return $actions;
    }

    function process_bulk_action()
    {
        if ('delete' === $this->current_action()) {
            wp_die('Items deleted (or they would be if we had items to delete)!');
        }

    }

    function prepare_items()
    {
        global $wpdb;

        $per_page = 5;
        $columns = $this->get_columns();
        $hidden = array();
        //$sortable = $this->get_sortable_columns();

        $this->_column_headers = array($columns, $hidden);

        $this->process_bulk_action();

        $sql = 'SELECT v.id, h.name, u.user_login as phone, v.date, v.time, c.display_name as consultant, v.handle, v.handle_date FROM tospur_view_house v '
            . 'left join tospur_house h on v.house_id = h.id '
            . 'left join wp_users u on v.user_id = u.id '
            . 'left join wp_users c on v.consultant_id = c.id '
            . 'order by handle';
        $result = $wpdb->get_results($sql);
        $data = array();
        foreach ($result as $key => $value) {
            $data[$key] = array(
                'id' => $value->id,
                'name' => $value->name,
                'date' => $value->date,
                'phone' => $value->phone,
                'consultant' => $value->consultant,
                'handle' => $value->handle,
                'handle_date' => $value->handle_date
            );
        }

        /*function usort_reorder($a, $b)
        {
            $orderby = (!empty($_REQUEST['orderby'])) ? $_REQUEST['orderby'] : 'handle'; //If no sort, default to title
            $order = (!empty($_REQUEST['order'])) ? $_REQUEST['order'] : 'asc'; //If no order, default to asc
            $result = strcmp($a[$orderby], $b[$orderby]); //Determine sort order
            return ($order === 'asc') ? $result : -$result; //Send final sort direction to usort
        }

        usort($data, 'usort_reorder');*/

        $current_page = $this->get_pagenum();

        $total_items = count($data);

        $data = array_slice($data, (($current_page - 1) * $per_page), $per_page);

        $this->items = $data;

        $this->set_pagination_args(array(
            'total_items' => $total_items,                  //WE have to calculate the total number of items
            'per_page' => $per_page,                     //WE have to determine how many items to show on a page
            'total_pages' => ceil($total_items / $per_page)   //WE have to calculate the total number of pages
        ));
    }
}

function add_view_house_menu()
{
    add_menu_page('预约列表', '预约列表', 'activate_plugins', 'view_house', 'view_house_page', 'dashicons-menu', 27);
}

add_action('admin_menu', 'add_view_house_menu');

function view_house_page()
{
    if ($_GET['id']) {
        require_once('handle_view_house.php');
    } else {
        //Create an instance our package class...
        $viewHouseList = new viewHouseList();
        //Fetch, prepare, sort, and filter our data...
        $viewHouseList->prepare_items();
        ?>
        <div class="wrap">
            <h2>预约列表</h2>

            <form id="houses-filter" method="get">
                <!-- For plugins, we also need to ensure that the form posts back to our current page -->
                <input type="hidden" name="page" value="<?php echo $_REQUEST['page'] ?>"/>
                <!-- Now we can render the completed list table -->
                <?php $viewHouseList->display() ?>
            </form>
        </div>
    <?php
    }
}

?>