<?php
require_once(PLUGIN_DIR . 'Dao/SearchDao.php');
class House {
    public static function init_view(){
        wp_enqueue_script('jquery-ui');
        wp_enqueue_script('bootstrapjs');
        wp_enqueue_style('jquery-ui_css');
        wp_enqueue_style('bootstrapcss');

        if(isset($_GET["updated"])){
            echo "updated success";
        }else{
            global $wpdb;
            $context = array();
            $context["city"] = SearchDao::searchCity();
            $context["buildProperty"] = SearchDao::searchBuildProperty();
            $context["room"] = SearchDao::searchRoom();
            $context["photoType"] = SearchDao::searchPhotoType();
            House::data_insert();
            Timber::render("newhouse.html",$context);
        }
    }

    public static function data_insert(){
        global $wpdb;
        date_default_timezone_set("Etc/GMT-8");;
        //图片信息
        $uploadedfile = $_FILES['files'];
        //房源与类型以及面积信息
        $data = $_POST["data"];
        //获取新房信息，存入tospur_house表
        $insert_tospur_house_array = array(
            'name' => $_POST['name'],
            'average_price' => $_POST['average_price'],
            'latest_news' => $_POST['event'],
            'address' => $_POST['address'],
            'traffic' => $_POST['traffic'],
            'periphery' => $_POST['periphery'],
            'developer' => $_POST['developers'],
            'check_in_time' => $_POST['check_in_time'],
            'building_type' => $_POST['building_type'],
            'property_age' => $_POST['property_age'],
            'decoration' => $_POST['decoration'],
            'covered_area' => $_POST['acreage'],
            'volume_rate' => $_POST['volume_rate'],
            'greening_rate' => $_POST['greening_rate'],
            'households' => $_POST['households'],
            'parking_spaces' => $_POST['parking_spaces'],
            'property_management' => $_POST['property_management'],
            'overview' => $_POST['overview'],
            'city_id' => $_POST['baseCity'],
            'district_id' => $_POST['baseAreaId'],
            'plate_id' => $_POST["basePlateId"],
            "room_id" => $_POST["baseRoom"],
            "property_money" => $_POST["property_money"],
            'creattime' => date("Y-m-d H:i:s"),
            'user_id' => get_current_user_id()
        );
        $res = $wpdb->get_results('SELECT * FROM tospur_house WHERE name="' . $_POST['name'] . '" and address="' . $_POST['address'] . '"', OBJECT);
        if (!$res) {
            $houseRes = $wpdb->insert('tospur_house', $insert_tospur_house_array);
            if (!$houseRes) {
                return 500;
            }
            $houseid = $wpdb->insert_id;
        }
        //主力房源的图片与房子信息关联插入数据库
        foreach($uploadedfile["name"] as $key=> $value) {
            $uploadParam = array(
                "name" => $uploadedfile["name"][$key],
                "type" => $uploadedfile["type"][$key],
                "tmp_name" => $uploadedfile["tmp_name"][$key],
                "error" => $uploadedfile["error"][$key],
                "size" => $uploadedfile["size"][$key]
            );
            //因为file提交过来有一个空的数组，所以这里判断在filename不为空的情况下，再做后续操作
            if ($uploadParam["name"] != "") {
                //上传图片
                if (!function_exists('wp_handle_upload')) {
                    require_once(ABSPATH . 'wp-admin/includes/file.php');
                }
                $overrides = array('test_form' => false);
                $movefile = wp_handle_upload($uploadParam, $overrides);
                $str = preg_replace('#^https?://#', '', $movefile["url"]);
                $length = strpos($str, "/",strpos($str, "/")+1);
                $url = substr($str,$length);
                if ($movefile && !isset($movefile['error'])) {
                    //上传成功后将图片信息存入tospur_image表
                    $insert_image_array = array(
                        'name' => $uploadParam["name"],
                        'path' => $url,
                        'creattime' => date("Y-m-d H:i:s"),
                        'alt' => "",
                        'image_type' =>$data[$key]["type"]
                    );
                    //插入图片表
                    $imgRes = $wpdb->insert('tospur_image', $insert_image_array);
                    if (!$imgRes) {
                        return 501;
                    }
                    //获取插入图片的id
                    $imgid = $wpdb->insert_id;
                    //房源类型、面积与图片关联表
                    if($data[$key]["type"] == "0"){
                        $houseTypeArea = array(
                            'house_id' => $houseid,
                            "buildproperty_id" => $data["$key"]["buildProperty"],
                            "house_area" => $data["$key"]["housearea"],
                            "image_id" => $imgid
                        );
                        $houseTypeAreaRes = $wpdb->insert('a_district_area', $houseTypeArea);
                        if (!$houseTypeAreaRes) {
                            return 502;
                        }
                    }
                    //将房源id与图片id储存到关联表中
                    $house_img_array = array(
                        'house_id' => $houseid,
                        'image_id' => $imgid,
                    );
                    $houseImgRes = $wpdb->insert('a_house_image', $house_img_array);
                    if (!$houseImgRes) {
                        return 503;
                    }
                } else {
                    return $movefile['error'];
                }
            }
        }
    }
} 