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

class Send_operation extends CI_Controller {

    public function __construct(){
        parent::__construct();
        mb_regex_encoding("UTF-8");
        bcscale(4);
        $this->load->helper('array');
        $this->load->model('Send_operation_model', 'send_model');
        $this->send_url = 'https://www.mycht.cn/webht.php/apps/messagecenter/index/send_message/';
        header('Access-Control-Allow-Origin:*');
        header('Access-Control-Allow-Methods:POST, GET');
        header('Access-Control-Max-Age:0');
        header('Access-Control-Allow-Headers:x-requested-with, Content-Type');
        header('Access-Control-Allow-Credentials:true');
    }

    public function index()
    {
        $this->sms_log();
        return;
    }

    public function sms_log()
    {
        $this->permission->is_admin(true);
        $date = $this->input->get_post("date");
        $date = $date ? $date : date('Y-m-d', strtotime("+1 day"));
        $ready_order["date"] = $date;
        $COLI_ID = $this->input->get_post("order_id");
        $ready_order["order_id"] = $COLI_ID;
        $ready_order["list"] = $this->send_model->daytour_order_ready_for_send(trim($COLI_ID), $date, "no_send_state");
        $this->load->view('sms_log', $ready_order);
        return;
    }

    public function order_sms_list($COLI_SN)
    {
        $data['list'] = $this->send_model->order_sms_list($COLI_SN);
        $list_table = $this->load->view('order_sms_list', $data, true);
        $this->output->set_content_type('application/json')->set_output(json_encode($list_table));
        return;
    }

    /*!
     * 通过短信发送导游信息给预定了Day Tour的客人
     * * 每天9:00, 16:00 尝试发送
     * * 第二次发送之后仍然发送失败或没有调度信息, 反馈到Alex邮箱
     * * 这里只是Day Tour 订单, 不含单接送, 因此每个订单仅发送一次
     * @date   2018-09-25
     */
    /*!
     * 模板内容
     * 2018-10-22
     * 【桂林海纳国旅】Hi {1}, your guide on {2} is {3}, （local）mobile is {4}. He/she'll call you at the hotel, or leave a message tonight. You can find more info by inputting booking No. {5} at https://www.trippest.com/track-your-trip. Wish you a wonderful day with Trippest!
     */
    public function daytour($COLI_ID="")
    {
        $now_h = date("H");
        $time_flag = "";
        if ($now_h < 9 || $now_h > 19) {
            echo "Break time.";
            return false;
        } else if ($now_h >= 9 && $now_h < 16) {
            $time_flag = "try1";
        } else {
            $time_flag = "try2";
        }
        $date = date('Y-m-d', strtotime("+1 day"));
        if (trim($COLI_ID) !== "") {
            $date = null;
            $time_flag = "handle";
        }
        $ready_order = $this->send_model->daytour_order_ready_for_send(trim($COLI_ID), $date, $time_flag);
        if (empty($ready_order)) {
            echo "Empty. ";
            return false;
        }
        $order = $ready_order[0];
        if (strtotime($order->COLD_StartDate) < strtotime(date('Y-m-d')) ) {
            echo "已过期";
            return;
        }
        $has_send = false;
        $send_history = $this->send_model->order_sms_list($order->COLI_SN);
        if ( ! empty($send_history)) {
            $has_send = true;
            $new_number = mb_ereg_replace('[\D]', '', $order->GUT_POST) . real_phone_number($order->GUT_TEL, mb_ereg_replace('[\D]', '', $order->GUT_POST));
            $last_send = end($send_history);
            $last_send_number = $last_send->TPSL_nationCode . $last_send->TPSL_mobile;
            $last_send_cb = json_decode($last_send->TPSL_callbackJson);
            if ($last_send_cb->result == 1016 && $new_number == $last_send_number) {
                // 更新时间, 以免一直重复在这个订单
                $update_cb_db['TPSL_logTime'] = date("Y-m-d H:i:s");
                $update_where = " TPSL_SN=" . $last_send->TPSL_SN;
                $ht_id = $this->send_model->update_trippest_sms_log($update_where, $update_cb_db);
                echo "手机号错误且未变更";
                return;
            }
        }
        $last_update = "";
        $guide_name = "";
        if ($order->gcod != null) {
            $split_gcod = explode("@", $order->gcod);
            $guide_name = $split_gcod[0];
            $guide_tel = $split_gcod[1];
            $last_update = $split_gcod[2] . " " . $split_gcod[3];
        } else {
            $guide_name = strstr($order->eva, "@", true);
            $guide_tel = substr(strstr($order->eva, "@"), 1);
        }
        $guide_name = mb_ereg_replace('[^a-zA-Z]', '', $guide_name);
        $send_body = array(
            "one"          => trim($order->guest_name)
            ,"two"         => substr($order->COLD_StartDate, 0, 10)
            ,"three"       => $guide_name
            ,"four"        => "+86 " . $guide_tel
            ,"five"        => $order->COLI_ID
            ,"phone"       => real_phone_number($order->GUT_TEL, mb_ereg_replace('[\D]', '', $order->GUT_POST))
            ,"nation_code" => mb_ereg_replace('[\D]', '', $order->GUT_POST)
        );
        $cb_db = array(
            "TPSL_COLI_SN"     => $order->COLI_SN
            ,"TPSL_nationCode" => $send_body['nation_code']
            ,"TPSL_mobile"     => $send_body['phone']
            ,"TPSL_msgType"    => 'guide'
            ,"TPSL_sendState"  => 0
        );
        $ht_id = $this->send_model->insert_trippest_sms_log($cb_db);
        $error_msg = "";
        $send_time = date("Y-m-d H:i:s");
        if ($guide_name != null) {
            $send_cb = $this->excute_curl($this->send_url, $send_body);
            $send_cb_obj = json_decode($send_cb);
            $update_cb_db["TPSL_sendTime"]    = $send_time;
            $update_cb_db["TPSL_sendContent"] = json_encode($send_body);
            $update_cb_db['TPSL_sendState'] = $send_cb_obj->result===0 ? 1 : 0;
            $update_cb_db['TPSL_callbackJson'] = $send_cb;
            $update_cb_db['TPSL_callbackTime'] = date("Y-m-d H:i:s");
            $update_where = " TPSL_SN=" . $ht_id;
            $ht_id = $this->send_model->update_trippest_sms_log($update_where, $update_cb_db);
            $send_cb_obj->errmsg!=="OK" ? $error_msg=$send_cb_obj->errmsg : null;
        }
        // if ($time_flag === "try1") {
        //     return;
        // }
        if ($has_send == false) {
            if ($guide_name == null || $error_msg !== "") {
                // 没有调度或发送失败
                // to Alex
                $operator_mailbody = "<p> Dear Alex: </p>" .
                    "<p>导游信息发送客人失败：<br /></p>" .
                    "<p>订单号:" . $order->COLI_ID ."</p>" .
                    "<p>发团时间:" . substr($order->COLD_StartDate, 0, 10) ."</p>" .
                    "<p>导游信息:" . $guide_name . "(" . $guide_tel . ")" ."</p>" .
                    "<p>导游更新时间:" . $last_update ."</p>" .
                    "<p>发送时间:" . $send_time ."</p>";
                if ($error_msg !== "") {
                    $operator_mailbody .= "<p>发送失败信息:" . $error_msg . "</p>";
                }
                $operator_mailbody .= "<p><a href='https://www.trippest.com/track-your-trip/'>Tracking Link</a>.</p>";
                $operator_mailbody .= "<p> 此邮件由系统自动发送, 请勿回复.</p>";
                $this->send_model->SendMail(
                    "chinahighlights",
                    "webform@chinahighlights.net",
                    "YSL",
                    "alex@chinahighlights.net", // ysl email alex@chinahighlights.net
                    '#SMS send fail#  ' . $order->COLI_ID,
                    $operator_mailbody);
            }
        }
        echo "已发送";
        return;
    }

    protected function excute_curl($url, $postBody) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FAILONERROR, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            "Accept: application/json"
        ));

        if (empty($postBody)) {
            return false;
        }
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postBody);

        $reponse = curl_exec($ch);
        // $eval_resp = json_decode($reponse);

        if (curl_errno($ch)) {
            log_message('error', "curl error : ".curl_error($ch) . "; curl postBodyString: ".json_encode($postBody));
        } else {
            $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            if (200 !== $httpStatusCode) {
                log_message('error', "curl response Status Code: ".$httpStatusCode."; curl postBodyString: ".json_encode($postBody));
            }
        }
        curl_close($ch);
        return $reponse;
    }

}

/* End of file send_operation.php */
/* Location: ./webht/third_party/trippestOrderSync/controllers/send_operation.php */
