<?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();

        if($type==1){
            $wpdb->query("START TRANSACTION");
            $prefix = "新增";
            if(isset($_REQUEST["id"])) {
                $prefix = "修改";
            }
            $result = Contract::doSqlAction();
            if(!is_numeric($result)){
                $wpdb->query("ROLLBACK");
                $context["error"] = $result;
                echo $result;
                echo $prefix."合同失败";
            }else{
                $wpdb->query("COMMIT");
                echo $prefix."合同成功";
            }
            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);
            $commissionIds = array();
            foreach($context["commission"] as $item){
                $commissionIds[] = $item->id;
            }
            $context["commissionLog"] = CommissionDao::search_commission_log(implode(",",$commissionIds));
        }
        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(){
        $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"])){
            $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;
                $result = CustomerDao::updateCustomerStatue($_REQUEST['customerNumber'],1);
                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'];
        }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( $_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;
    }
} 