<?php

class CustomerDao
{
    public static function insert_customer($params){
        global $wpdb;
        $result =  $wpdb->insert(Config::TOSPUR_CUSTOMER_TABLE, $params);
        $insert_id = $wpdb->insert_id;
        if($result){
            return $insert_id;
        }else{
            return 0;
        }
    }

    public static function searchCustomer($id)
    {
        global $wpdb;
        $sql = "SELECT tcs.* FROM tospur_customer tcs where tcs.id = %d";
        $result = $wpdb->get_row($wpdb->prepare($sql, $id));
        $context = array();
        if($result){
            $context['result'] = $result;
            $consultant_sql = "SELECT * FROM tospur_consultant where id = %d";
            $consultant = $wpdb->get_results($wpdb->prepare($consultant_sql, $result->consultant_id));
            $context['consultant'] = $consultant;
        }
        return $context;
    }

    public static function searchCustomerByNameOrPhone(){
        global $wpdb;
        $search = "%".$_REQUEST['search']."%";
        $sql = "SELECT tcs.id,tcs.name,tcs.phone FROM ".Config::TOSPUR_CUSTOMER_TABLE." tcs where (tcs.name like %s or tcs.phone like %s)";
        switch($_REQUEST["customerDemand"]){
            case "0":
                $sql .= " and tcs.new_house = 1";
                break;
            case "1":
                $sql .= " and tcs.secondHand_house = 1";
                break;
            case "2":
                $sql .= " and tcs.rent_house = 1";
                break;
        }
        $result = $wpdb->get_results($wpdb->prepare($sql, $search,$search));
        wp_send_json($result);
    }

    public static function updateCustomerStatue($id,$status){
        global $wpdb;
        $result = $wpdb->update(Config::TOSPUR_CUSTOMER_TABLE,array(
            'status' => $status,
        ),array(
            'id' => $id
        ));
        if($wpdb->last_error)
            return $wpdb->last_error;
        return $result;
    }
}

?>