<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Order_model extends CI_Model {

    public function __construct()
    {
        parent::__construct();
        $this->ht = $this->load->database('HT', TRUE);
    }

    public function get_order_contact($coli_sn, $order_type='227002')
    {
        $sql = "SELECT GUT_FirstName+' '+GUT_LastName fullname
                    ,GUT_Email email
                    ,case ISNULL(GUT_MoveTel,'') when '' then GUT_TEL else GUT_MoveTel end phone
                    ,g.GUT_POST nation
                from BIZ_GUEST g
                INNER JOIN BIZ_ConfirmLineInfo coli on coli.COLI_GUT_SN=g.GUT_SN
                WHERE COLI_SN=?";
        if ($order_type !== '227002' && $order_type !== null) {
            $sql = "SELECT top 1
                        case isnull(CUL_IsLinkMan,0) when 1 then MEI_Phone else '' end as phone
                        ,(select COI_CountryCode from COuntryInfo
                            where COI_SN=MEI_Country
                        ) as nation
                        ,MEI_MailList email
                        ,(isnull(MEI_LastName,'') +' '+ isnull(MEI_FirstName,'')) as fullname
                    from CustomerList cul
                    inner join MemberInfo mei on MEI_SN=CUL_CUI_SN
                    where 1=1
                        and cul.DeleteFlag=0 and mei.DeleteFlag=0
                        and CUL_COLI_SN = ?
                    order by cul.CUL_IsLinkMan desc ";
        }
        $contact_row = $this->ht->query($sql, array($coli_sn))->row_array();
        if ( ! empty($contact_row)) {
            $contact_row['phone_no'] = $contact_row['phone'];
            if (false !== strripos($contact_row['phone'], ":")) {
                $contact_row['phone_no'] = substr($contact_row['phone_no'], strripos($contact_row['phone_no'], ":")+1);
            }
            $contact_row['phone_no'] = $this->real_phone_number($contact_row['phone_no'],$contact_row['nation']);
        }
        return $contact_row;
    }

    public function real_phone_number($phone, $nation_code)
    {
        $nation_str = "+" . $nation_code;
        $cut_nation = str_replace($nation_str, "", $phone);
        return mb_ereg_replace('[\D]', '', $cut_nation);
    }

    public function orders($wu_id)
    {
        $sql = "SELECT orders.*
                ,PAG.PAG2_Name tourName,pag.PAG2_Attraction tourAttraction
                ,CONVERT(date, COLD_StartDate) startDate
                --test:先设置一个字段.todo:是否完成电子反馈表
                ,case when COLD_StartDate>'2019-06-01' then 0 else 1 end evaluationDone
                ,isnull((select top 1 'Paid  ' from Tourmanager.dbo.BIZ_GroupAccountInfo a where a.DeleteFlag=0 and GAI_COLI_SN=orders.coli),'Unpaid')
                as ispaid
                from (
                    select
                    COLI_GroupCode groupCode,COLI_GRI_SN groupId,COLI_ID orderId, COLI_SN coli
                    ,(select top 1 COLD_SN from BIZ_ConfirmLineDetail where deleteflag=0 and cold_coli_sn=coli_sn order by cold_startdate
                    ) as COLD_SN0
                    ,COLI_IsSuccess isSuccess
                    ,COLI_ApplyDate orderDate
                    from BIZ_ConfirmLineInfo coli
                    where 1=1
                    and exists(
                        select 1 from InfoManager.dbo.wx_customer where WC_WU_id=? and WC_COLI_SN=coli.COLI_SN
                    )
                ) as orders
                inner join BIZ_ConfirmLineDetail cold on cold.COLD_SN=orders.COLD_SN0
                inner join BIZ_PackageInfo2 pag  on pag.PAG2_PAG_SN=cold.COLD_ServiceSN and pag.PAG2_LGC=1
                order by
                    --evaluationDone asc,
                    -- startDate asc
                    orders.orderDate desc
        ";
        return $this->ht->query($sql, array($wu_id))->result_array();
    }

    public function get_pag_tour_info($external_id)
    {
        $sql = "SELECT top 1 p.*
                    ,(select top 1 SYC_SN from V_System_Code where SYC2_CodeDiscribe=sc.SYC2_CodeDiscribe and SYC_Type=32 and DeleteFlag=0 and LGC_LGC=2 ) as sourcetype32
                from BIZ_PackageInfo p
                left join V_System_Code sc on SYC_SN = PAG_sourceType and SYC_Type=132 AND LGC_LGC=2
                where isnull(p.DeleteFlag,0)=0
                and charindex(?,p.PAG_WebBR)>0";
        return $this->ht->query($sql, array(",$external_id,"))->row_array();
    }

    public function biz_make_order_number() {
        include('c:/database_conn.php');
        $connection = array(
            'UID' => $db['HT']['username'],
            'PWD' => $db['HT']['password'],
            'Database' => 'tourmanager',
            'ConnectionPooling' => 1,
            'CharacterSet' => 'utf-8',
            'ReturnDatesAsStrings' => 1
        );
        $conn = sqlsrv_connect($db['HT']['hostname'], $connection);
        $stmt = sqlsrv_query($conn, "DECLARE @COLI_ID varchar(40); EXEC dbo.SP_GetBIZOrderNo @COLI_ID OUT; select @COLI_ID coli_id;");
        if ($stmt === false) {
            echo "Error in executing statement 3.\n";
            die(print_r(sqlsrv_errors(), true));
        } else {
            //存储过程中每一个select都会产生一个结果集，取某个结果集就需要从第一个移动到需要的那个结果集
            //如果结果集为空就移到下一个

            while (sqlsrv_has_rows($stmt) !== TRUE) {
                sqlsrv_next_result($stmt);
            }

            $result_object = array();
            while ($row = sqlsrv_fetch_object($stmt)) {
                $result_object[] = $row;
            }

            sqlsrv_free_stmt($stmt);
            sqlsrv_close($conn);

            return $result_object[0];
        }
    }

    public function order_save($coli_arr=array())
    {
        $this->ht->insert('BIZ_ConfirmLineInfo', $coli_arr);
        return $this->ht->insert_id();
    }

    public function book_detail_save($cold_arr=array())
    {
        $this->ht->insert('BIZ_ConfirmLineDetail', $cold_arr);
        return $this->ht->insert_id();
    }

    public function guest_save($guest=array())
    {
        $this->ht->insert('BIZ_guest', $guest);
        return $this->ht->insert_id();
        // return $this->ht->query('SELECT top 1 GUT_SN from BIZ_GUEST where GUT_Email=? order by GUT_SN desc', array($guest['GUT_Email']))->row()->GUT_SN;
    }

    public function book_people_save($book_people=array())
    {
        $this->ht->insert('BIZ_BookPeople', $book_people);
        return $this->ht->insert_id();
        // return $this->ht->query('SELECT top 1 BPE_SN from BIZ_BookPeople where BPE_Passport=? order by BPE_SN desc', array($book_people['BPE_Passport']))->row()->BPE_SN;
    }

    public function biz_bookpeople_List_save($arr=array())
    {
        $this->ht->insert('BIZ_BookPeopleList', $arr);
        return $this->ht->insert_id();
    }

    public function pag_order_save($poi_arr=array())
    {
        $this->ht->insert('BIZ_PackageOrderInfo', $poi_arr);
        return $this->ht->insert_id();
    }

    public function order_info_to_pay($coli_sn, $pending=null)
    {
        $column = ""; $calc = "";
        if ($pending===null) {
            $column = " COLI_Price price, ";
            $calc  = " (select Tourmanager.dbo.ConvertToRMB(coli.COLI_Currency, coli.COLI_Price)) as cny_price ";
        } else {
            $column = " $pending as 'price', ";
            $calc  = " (select Tourmanager.dbo.ConvertToRMB(coli.COLI_Currency, $pending)) as cny_price ";
        }
        $sql = "SELECT
        u.WU_userOpenId openid,COLI_ID,
        $column
        $calc
        from InfoManager.dbo.wx_customer
        inner join InfoManager.dbo.wx_user u on WU_id=WC_WU_id
        inner join Tourmanager.dbo.BIZ_ConfirmLineInfo coli on COLI_SN=WC_COLI_SN
        where WC_COLI_SN=? ";
        return $this->ht->query($sql, array($coli_sn))->row_array();
    }

    public function order_detail($coli_sn, $coli_id = null)
    {
        $ret = array();
        bcscale(2);
        /**
         * booking tour detail
         */
        // 支付结果使用ID, 不再获取SN
        $id_sql = ($coli_sn===0&&$coli_id!==null) ? "COLI_ID='$coli_id'" : "COLI_SN=$coli_sn";
        $sql = "SELECT
            c.COLI_SN coli,c.COLI_ID orderId,c.COLI_State orderStep,c.COLI_OPI_ID opi,
            convert(date,COLD_StartDate) startDate,
            isnull((select top 1 1 from Tourmanager.dbo.BIZ_GroupAccountInfo a where a.DeleteFlag=0 and GAI_COLI_SN=c.COLI_SN),0)
                as ispaid,
            convert(decimal(11,2),c.COLI_Price) totalPrice,c.COLI_Currency currency,
            c.COLI_GroupCode groupCode,p.PAG2_PAG_SN as tourId
            ,convert(varchar(10),d.COLD_personNum) + ' Adults; ' +
                case when d.COLD_childNum>0 then convert(varchar(10), d.COLD_childNum)+' Children; '
                else '' end
            as personNum
            ,(select top 1 g.GUT_FirstName from BIZ_Guest g where GUT_SN=COLI_GUT_SN) as leader
            ,po.POI_hotel as hotelName
            ,po.POI_hotelAddress as hotelAddress
            ,po.POI_hotelPhone as hotelTel
            ,p.PAG2_Attraction as attraction,PAG2_Title as schedule,p.PAG2_Name as tourName
            ,isnull(ps.PAGS_describ, '') as subTourInfo
            from Tourmanager.dbo.BIZ_ConfirmLineInfo c
            inner join Tourmanager.dbo.BIZ_ConfirmLineDetail d on c.COLI_SN=d.COLD_COLI_SN
                and d.DeleteFlag=0
            left join biz_packageOrderinfo po on po.POI_COLD_SN=d.COLD_SN
            left join Tourmanager.dbo.BIZ_PackageInfo2 p on p.PAG2_PAG_SN=d.COLD_ServiceSN and p.PAG2_LGC=1
            left join Tourmanager.dbo.BIZ_PackageInfoSub ps on ps.PAGS_SN=d.COLD_ServiceSN2 and ps.PAGS_LGC=1
            where  $id_sql
            order by d.COLD_StartDate asc";
        $ret['orderTour'] = $this->ht->query($sql)->result_array();
        $sqlb = "SELECT
            a.GAI_SQJE paidValue,a.GAI_SQJECurrency paidCurrency
            ,case when a.gai_sqje>0 then 'pay' else 'refund' end as fundAction
            from Tourmanager.dbo.BIZ_GroupAccountInfo a
            where a.GAI_COLI_SN=?
            and a.DeleteFlag=0
            order by a.GAI_SQDate asc";
        $ret['paymentList'] = $this->ht->query($sqlb, array($coli_sn))->result_array();
        $sqlp = "SELECT
            CONVERT(decimal(10,2),isnull(sum(paid.paidQuote),0)) as paidQuote
            from (
                select
                isnull(a.GAI_SQJE,0) paidValue,isnull(a.GAI_SQJECurrency,'USD') paidCurrency
                ,Tourmanager.dbo.ConvertCurrencyToCurrency(1, isnull(a.GAI_SQJECurrency,'USD'), 'USD', isnull(a.GAI_SQJE,0)) as paidQuote
                ,case when a.gai_sqje>0 then 'pay' else 'refund' end as fundAction
                from Tourmanager.dbo.BIZ_GroupAccountInfo a
                where a.GAI_COLI_SN=?
                and a.DeleteFlag=0
            ) paid";
        $ret['paidQuote'] = $this->ht->query($sqlp, array($coli_sn))->row()->paidQuote;
        $ret['paidQuote'] = number_format($ret['paidQuote'], 2, '.', '');
        $ret['pendingBalance'] = bcsub($ret['orderTour'][0]['totalPrice'], $ret['paidQuote']);
        // $ret['pendingBalance'] = bcsub(1, 0); // test: $ret['paidQuote']
        $ret['pendingBalance'] = $ret['pendingBalance']>0 ? $ret['pendingBalance'] : 0;
        if (null !== $ret['orderTour'][0]['opi']) {
            $operator_sql = "SELECT opi.OPI_SN id,opi.OPI_Name chineseName,opi.OPI_FirstName englishName2,OPI_MoveTelephone tel,OPI_Email email,opi2.OPI2_Name englishName
                from OperatorInfo opi
                left join OperatorInfo2 opi2 on opi2.OPI2_OPI_SN=OPI_SN and opi2.OPI2_LGC=1
                where OPI_SN=" . $ret['orderTour'][0]['opi'] . " AND OPI_SN<>435";
            $ret['operator'] = $this->ht->query($operator_sql)->row();
        }
        return $ret;
    }
    /*
     * 发送邮件
     */
    function SendMail($fromName, $fromEmail, $toName, $toEmail, $subject, $body) {
        $sql = "INSERT INTO tourmanager.dbo.Email_AutomaticSend \n"
                . "  ( \n"
                . " M_ReplyToName, M_ReplyToEmail, M_ToName, M_ToEmail, M_Title, M_Body, M_Web,  \n"
                . " M_FromName, M_State,M_AddTime \n"
                . "  ) \n"
                . "VALUES \n"
                . "  (  \n"
                . " ?, ?, ?, ?, ?, N?, ?, ?, 0, GETDATE() \n"
                . "  ) ";
        $query = $this->ht->query($sql,
            array(substr($fromName, 0, 127), $fromEmail, substr($toName, 0, 127), $toEmail, $subject, $body, 'wechat-notify', 'Auto mail')
            );
        return $query;
    }

}

/* End of file Order_model.php */
