<?php

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

class customerList extends WP_List_Table
{
    function __construct()
    {
        parent::__construct(array(
            'singular' => 'customerList',
            'plural' => 'customerList',
            'ajax' => false
        ));
    }

    function column_default($item, $column_name)
    {
        switch ($column_name) {
            case 'name':
                return '<a href="' . admin_url('admin.php?page=customer&edit=true&id=' . $item['id']) . '">' . $item[$column_name] . '</a>';
            default:
                return $item[$column_name];
        }
    }

    function column_cb($item)
    {
        return sprintf(
            '<input type="checkbox" name="%1$s[]" value="%2$s" data-consultant="%3$s"/>',
            $this->_args['singular'],
            $item['id'],
            $item['consultant_id']
        );
    }

    function get_columns()
    {
        $columns = array(
            'cb' => '<input type="checkbox"/>'
        );
        $columns['name'] = '姓名';
        $columns['demand_type'] = '需求类型';
        $columns['consultant_name'] = '置业顾问';
        $columns['status_name'] = '状态';
        $columns['customer_remark'] = '客户备注';
        return $columns;
    }
    function get_bulk_actions()
    {
        $actions = array(
            'allot' => '分配置业顾问'
        );
        return $actions;
    }

    function process_bulk_action()
    {
        $action = $this->current_action();
        if ($action) {
            $string = null;
            switch ($action) {
                case 'allot':
                    $consultant_id = $_POST['allot_consultant_id'];
                    if ($consultant_id) {
                        $string = '(' . implode(',', array_map('intval', $_POST['customerlist'])) . ')';
                        global $wpdb;
                        $result = $wpdb->query('update ' . Config::TOSPUR_CUSTOMER_TABLE
                            . ' SET consultant_id = ' . $consultant_id
                            . ' where id in ' . $string);
                        if($result){
                            echo '<script>alert("分配置业顾问成功");</script>';
                        }
                    }
                    break;
            }
        }
    }

    function prepare_items()
    {
        global $wpdb;
        $per_page = 10;
        $columns = $this->get_columns();
        $hidden = array();

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

        $this->process_bulk_action();

        $sql = "SELECT tcs.*,tc.name as consultant_name,ts.status_name FROM tospur_customer tcs" .
            " left join (SELECT * FROM tospur_status where status_type = 5) as ts on tcs.status = ts.status_id" .
            " left join tospur_consultant tc on tcs.consultant_id = tc.id where 1 = 1";
        $current_user = wp_get_current_user();
        if($current_user->roles[0] == 'author'){
            $sql = $sql . " and tcs.consultant_id = " . $current_user->ID;
        }
        if (isset($_REQUEST['status']) && $_REQUEST['status'] != -1) {
            $sql = $sql . " and tcs.status = " . $_REQUEST['status'];
        }
        if (isset($_REQUEST['customer_type']) && $_REQUEST['customer_type'] != -1) {
            $sql = $sql . " and tcs.customer_type = " . $_REQUEST['customer_type'];
        }
        if (isset($_REQUEST['demand_type']) && $_REQUEST['demand_type'] != -1) {
            $demand_type = null;
            switch ($_REQUEST['demand_type']) {
                case 0:
                    $demand_type = 'tcs.new_house';
                    break;
                case 1:
                    $demand_type = 'tcs.secondHand_house';
                    break;
                case 2:
                    $demand_type = 'tcs.rent_house';
                    break;
            }
            if ($demand_type) {
                $sql = $sql . " and " . $demand_type . " = 1";
            }
        }
        if (isset($_REQUEST['listCity']) && $_REQUEST["listCity"] != -1) {
            $sql = $sql . " and tcs.city_id = " . $_REQUEST["listCity"];
        }
        if (isset($_REQUEST['listDistrict']) && $_REQUEST["listDistrict"] != -1) {
            $sql = $sql . " and tcs.district_id = " . $_REQUEST["listDistrict"];
        }
        if (isset($_REQUEST['listPlate']) && $_REQUEST["listPlate"] != -1) {
            $sql = $sql . " and tcs.plate_id = " . $_REQUEST["listPlate"];
        }
        if ($_REQUEST["totalPrice"] != null) {
            $priceArray = explode("-", $_REQUEST['totalPrice']);
            $sql = $sql . " and (tcs.min_totalPrice >= " . $priceArray[0] . " and tcs.max_totalPrice <= " . $priceArray[1] . ")";
        }
        if ($_REQUEST["rentalPrice"] != null) {
            $priceArray = explode("-", $_REQUEST['rentalPrice']);
            $sql = $sql . " and (tcs.min_rent >= " . $priceArray[0] . " and tcs.max_rent <= " . $priceArray[1] . ")";
        }
        if (isset($_REQUEST['buildProperty']) && $_REQUEST["buildProperty"] != -1) {
            if ($_REQUEST["buildProperty"] == 5) {
                $sql = $sql . " and (tcs.bedroom >= " . $_REQUEST["buildProperty"] . " or tcs.bedroom = -1)";
            } else {
                $sql = $sql . " and (tcs.bedroom = " . $_REQUEST["buildProperty"] . " or tcs.bedroom = -1)";
            }
        }
        if ($_REQUEST["acreage"] != null) {
            $areaArray = explode("-", $_REQUEST['acreage']);
            $sql = $sql . " and (tcs.min_coveredArea >= " . $areaArray[0] . " and tcs.max_coveredArea <= " . $areaArray[1] . ")";
        }
        if (isset($_REQUEST['search_name'])) {
            $sql = $sql . " and tcs.name like '%" . $_REQUEST['search_name'] . "%'";
        }
        if (isset($_REQUEST['search_consultant_name'])) {
            $sql = $sql . " and tc.name like '%" . $_REQUEST['search_consultant_name'] . "%'";
        }
        if (isset($_REQUEST['search_phone'])) {
            $sql = $sql . " and tcs.phone like '%" . $_REQUEST['search_phone'] . "%'";
        }
        if (isset($_REQUEST['search_min_time']) && $_REQUEST['search_min_time'] != null) {
            $sql = $sql . " and tcs.time >= '" . $_REQUEST['search_min_time'] . "'";
        }
        if (isset($_REQUEST['search_max_time']) && $_REQUEST['search_max_time'] != null) {
            $sql = $sql . " and tcs.time <= '" . $_REQUEST['search_max_time'] . "'";
        }
        $result = $wpdb->get_results($sql);
        $data = array();
        foreach ($result as $key => $value) {
            $demand_type_array = array(
                ($value->new_house == 1) ? '新房' : null,
                ($value->secondHand_house == 1) ? '二手房' : null,
                ($value->rent_house == 1) ? '租房' : null
            );
            $demand_type_array = array_filter($demand_type_array, function ($var) {
                return !is_null($var);
            });
            $data[$key] = array(
                'id' => $value->id,
                'name' => $value->name,
                'demand_type' => implode("、", $demand_type_array),
                'customer_remark' => $value->customer_remark,
                'consultant_id' => $value->consultant_id,
                'consultant_name' => $value->consultant_name,
                'status_name' => $value->status_name
            );
        }

        $current_page = $this->get_pagenum();

        $total_items = count($data);
        $total_pages = ceil($total_items / $per_page);

        if ($_REQUEST['paged'] > $total_pages) {
            $current_page = $total_pages;
        }

        $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 function_customerList()
{
    $context = array();
    //
    $context['city'] = SearchDao::searchCity();
    $context['buildProperty'] = SearchDao::searchBuildProperty();
    //
    $context['status'] = SearchDao::searchStatusType(5);
    $context['customer_type'] = SearchDao::searchStatusType(6);

    if (isset($_REQUEST['hasSearch'])) {
        $context['district'] = SearchDao::searchCity($_REQUEST['listCity']);
        $context['plate'] = SearchDao::searchCity($_REQUEST['listCity'], $_REQUEST['listDistrict']);
        $context['dicTotalPrice'] = searchDao::searchTotalPrice($_REQUEST['listCity']);
        $context['dicRentalPrice'] = searchDao::searchRentalPrice($_REQUEST['listCity']);
        $context['dicArea'] = searchDao::searchArea($_REQUEST['listCity']);
        $context['cityId'] = $_REQUEST['listCity'];
        $context['districtId'] = $_REQUEST['listDistrict'];
        $context['plateId'] = $_REQUEST['listPlate'];
        $context['buildPropertyId'] = $_REQUEST['buildProperty'];
        $context['totalPrice'] = $_REQUEST['totalPrice'];
        $context['rentalPrice'] = $_REQUEST['rentalPrice'];
        $context['acreage'] = $_REQUEST['acreage'];
    }

    $context['status_id'] = $_REQUEST['status'];
    $context['demand_type'] = isset($_REQUEST['demand_type']) ? $_REQUEST['demand_type'] : -1;
    $context['customer_type_id'] = isset($_REQUEST['customer_type']) ? $_REQUEST['customer_type'] : -1;
    $context['search_name'] = $_REQUEST['search_name'];
    $context['search_consultant_name'] = $_REQUEST['search_consultant_name'];
    $context['search_phone'] = $_REQUEST['search_phone'];
    $context['search_min_time'] = $_REQUEST['search_min_time'];
    $context['search_max_time'] = $_REQUEST['search_max_time'];

    Timber::render("customerList.html", $context);
}

function addCustomerTable()
{
    $_SERVER['REQUEST_URI'] = remove_query_arg( '_wp_http_referer', $_SERVER['REQUEST_URI'] );
    $customerList = new customerList();
    $customerList->prepare_items();
    $customerList->display();
}

?>
