<?php
require_once(PLUGIN_DIR . 'Dao/ContractDao.php');
require_once(PLUGIN_DIR . 'Dao/SearchDao.php');
require_once(PLUGIN_DIR . 'Dao/HouseDao.php');
require_once(PLUGIN_DIR . 'Dao/CommissionDao.php');

class Contract {
    public static function init_view(){
        global $wpdb;
        $type = $_POST["type"];
        $context = array();
        $context['siteUrl'] = get_site_url();
        $context['adminUrl'] = admin_url();
        $context['city'] = SearchDao::searchCity();
        $context['managers'] = get_users( 'role=jl' );
        $context['status'] = SearchDao::searchStatusType(4);
        $context['buildProperty'] = SearchDao::searchBuildProperty();
        $context['room'] = SearchDao::searchRoom();

        $htEdit = current_user_can('htEdit');
        if($type==1){
            if($htEdit){
                $wpdb->query("START TRANSACTION");
                $prefix = "<h4>新增";
                if(isset($_REQUEST["id"])) {
                    $prefix = "<h4>修改";
                }
                $result = Contract::doSqlAction();
                if(!is_numeric($result)){
                    $wpdb->query("ROLLBACK");
                    $context["error"] = $result;
                    echo $result;
                    echo $prefix."合同失败</h4>";
                }else{
                    $wpdb->query("COMMIT");
                    echo $prefix."合同成功</h4>";
                }
                echo "<h4>3秒后自动跳转至合同列表</h4>
                <script>
                    setTimeout(function(){
                        window.location.href='" . admin_url('admin.php?page=contractList') . "';
                    },3000);
                </script>";
            }else{
                echo "<h4>没有权限提交合同</h4>";
            }
            exit;
        }else if(isset($_GET['edit'])){
            $id = $_REQUEST["id"];
            $context['result'] = ContractDao::searchContract($id);
            $context["consultant"] = CommissionDao::search_commission_consultant($id);
            $context["commission"] = CommissionDao::search_tospur_commission($id);
			$context["img"] = ContractDao::searchContractImg($id);
            $commissionIds = array();
            foreach($context["commission"] as $item){
                $commissionIds[] = $item->id;
            }
            $context["commissionLog"] = CommissionDao::search_commission_log(implode(",",$commissionIds));
        }
        $context['htEdit'] = $htEdit;
        Timber::render("contract.html",$context);
    }


    private static function formatCommissionParams($params,$contractId,$type){
        $commissionParams = array(
            "accounts" => $params["accounts"],
            "type" => $_REQUEST["businessType"],
            "contractId" => $contractId,
            "consultantId" => $params["consultantId"],
            "ioType" => $type,
            "mtime" => $params["mtime"]
        );
        return $commissionParams;
    }

    private static function doSqlAction(){
        date_default_timezone_set("Etc/GMT-8");
        $params = array(
            'signedDate' =>$_REQUEST['signedDate'],
            'status' =>$_REQUEST['status'],
            'area' =>$_REQUEST['area'],
            'permitNumber' =>$_REQUEST['permitNumber'],
            'managerId' =>$_REQUEST['managerId'],
            'paymentMethod' =>$_REQUEST['paymentMethod'],
            'codicil' =>$_REQUEST['codicil'],
            'oName' =>$_REQUEST['oName'],
            'oID' =>$_REQUEST['oID'],
            'oBroker' =>$_REQUEST['oBroker'],
            'oAddress' =>$_REQUEST['oAddress'],
            'oMoney' =>$_REQUEST['oMoney'],
            'oPayBack' =>$_REQUEST['oPayBack'],
            'cName' =>$_REQUEST['cName'],
            'cID' =>$_REQUEST['cID'],
            'cBroker' =>$_REQUEST['cBroker'],
            'cAddress' =>$_REQUEST['cAddress'],
            'cMoney' =>$_REQUEST['cMoney'],
            'cPayBack' =>$_REQUEST['cPayBack']
        );
        $commissionType = array();
        if(isset($_REQUEST["id"])){
			global $wpdb;
            $result = ContractDao::update($_REQUEST["id"],$params);
            if(!is_numeric($result)){
                return $result;
            }
            $status = 0;

            if($params['status'] == 4) {//作废
                $status = 0;
            }else if($params['status'] == 3){//成交
                $status = 2;
                $params['dealTime'] = date("Y-m-d H:i:s");
                $result = CustomerDao::updateCustomerStatue($_REQUEST['customerNumber'],1);
                if(!is_numeric($result)){
                    return $result;
                }
            }
            $result = ContractDao::update($_REQUEST["id"],$params);
            if(!is_numeric($result)){
                return $result;
            }
            $result = HouseDao::updateStatus($status,$_REQUEST['id']);
            if(!is_numeric($result)){
                return $result;
            }
            $commissionType['buy'] = $_REQUEST['commissionId_buy'];
            $commissionType['sell'] = $_REQUEST['commissionId_sell'];

			$exists_photo_ids = array();
            foreach($_REQUEST['exists_photo'] as $id => $item){
                $exists_photo_ids[] = $id;
            }
            $old_exists_photo_ids = explode(",",$_POST['exists_photo_ids']);
            $delete_photo_ids = array();
            foreach(array_diff($old_exists_photo_ids,$exists_photo_ids) as $key => $id){
                $delete_photo_ids[] = $id;
            }
            $delete_photo_ids = implode(",",$delete_photo_ids);
            if($delete_photo_ids){
                $path = ContractDao::searchImgPath($delete_photo_ids);
                DBManager::query("delete from ".Config::A_CONTRACT_IMAGE_TABLE." where contract_id = {$_REQUEST["id"]} and image_id in ({$delete_photo_ids});");
                DBManager::query("delete from ".Config::TOSPUR_IMAGE_TABLE." where id in ({$delete_photo_ids});");
                foreach($path as $value){
                    $url =  substr_replace(__DIR__,$value->path,strpos(__DIR__,"wp",0)-1);
                    unlink($url);
                }
            }
            ContractDao::insert_contract_image($_REQUEST["id"]);
        }else{
            $params['business'] = $_REQUEST['businessId'];
            $params['houseNumber'] = $_REQUEST['houseNumber'];
            $params['price'] = $_REQUEST['price'];
            $params['houseId'] = $_REQUEST['houseId'];
            $params['customerNumber'] = $_REQUEST['customerNumber'];
            $params['oPhone'] = $_REQUEST['oPhone'];
            $params['oCommission'] = $_REQUEST['oCommission'];
            $params['cPhone'] = $_REQUEST['cPhone'];
            $params['cCommission'] = $_REQUEST['cCommission'];
            $params['consultantId'] = get_current_user_id();

            $result = ContractDao::insert($params);
            if(!is_numeric($result)){
                return $result;
            }
            $pre = "CJCS";
            if($_REQUEST['type'] > 1){
                $pre = "CJCZ";
            }
            $contractNumber = $pre.str_pad($result,6,'0',STR_PAD_LEFT);
            $contractId = $result;
            $result = ContractDao::setContractId($result,$contractNumber);
            if(!is_numeric($result)){
                return $result;
            }
            //二手房、租房创建合同时修改房源的状态
            if(intval($_REQUEST['businessId']) >=1 ){
                $result = HouseDao::updateStatus(-1,$params['houseId']);
                if(!is_numeric($result)){
                    return $result;
                }
            }
            $buyCommissionParams = Contract::formatCommissionParams($_REQUEST['buy'],$contractId,0);
            $result = CommissionDao::insert_touspur_commission($buyCommissionParams);
            if(!is_numeric($result)){
                return $result;
            }
            $commissionType['buy'] = $result;

            $sellCommissionParams = Contract::formatCommissionParams($_REQUEST['sell'],$contractId,1);
            $result = CommissionDao::insert_touspur_commission($sellCommissionParams);
            if(!is_numeric($result)){
                return $result;
            }
            $commissionType['sell'] = $result;
			if( isset($_FILES['files'])){
                ContractDao::insert_contract_image($contractId);
            }
        }
        if(isset( $_POST["log"])) {
            foreach ($_POST["log"] as $key => $value) {
                $commissionId = $commissionType[$key];
                foreach($value as $item){
                    $logParams = array(
                        "commissionId" => $commissionId,
                        "time" => $item["time"],
                        "paid" => $item["paid"]
                    );
                    $result =  CommissionDao::insert_commission_log($logParams);
                    if(!is_numeric($result)){
                        return $result;
                    }
                }
            };
        }
        return $result;
    }
} 