<?php

namespace memsg;

require_once(BASE_ROOT_PATH . '/helper/push_sender.php');
require_once(BASE_ROOT_PATH . '/helper/push_helper.php');
require_once(BASE_ROOT_PATH . '/helper/sms_helper.php');

use Log;
use push_helper;
use push_sender;

class message_sender
{
    private $code = '';
    private $member_id = 0;
    private $member_info = array();
    private $mobile = '';
    private $sms_param = '';

    public function set($key,$value){
        $this->$key = $value;
    }

    public function send($param = array())
    {
        $msg_tpl = rkcache('member_msg_tpl', true);
        if (!isset($msg_tpl[$this->code]) || $this->member_id <= 0) {
            return false;
        }

        $tpl_info = $msg_tpl[$this->code];
        $setting_info = Model('member_msg_setting')->getMemberMsgSettingInfo(array('mmt_code' => $this->code,
            'member_id' => $this->member_id),
            'is_receive');

        if (empty($setting_info) || $setting_info['is_receive'])
        {
            // 发送站内信
            if ($tpl_info['mmt_message_switch']) {
                $message = ncReplaceText($tpl_info['mmt_message_content'],$param);
                $this->sendMessage($message);
            }

            $push_success = false;
            if ($tpl_info['mmt_push_switch']) {
                $message = ncReplaceText($tpl_info['mmt_push_content'],$param);
                $info = push_helper::format_msg($this->member_id,$message);
                $sender = new push_sender();
                $push_success = $sender->send($info);
            }

            // 发送短消息
            if ($push_success == false && $tpl_info['mmt_short_switch'])
            {
                $sms_code = $tpl_info['mmt_short_code'];
                $this->getMemberInfo();
                if (!empty($this->mobile)) {
                    $this->member_info['member_mobile'] = $this->mobile;
                }
                $this->sendShort($this->member_info['member_mobile'], $sms_code, empty($this->sms_param) ? null : $this->sms_param);
            }
        }
    }

    private function getMemberInfo() {
        if (empty($this->member_info)) {
            $this->member_info = Model('member')->getMemberInfoByID($this->member_id);
        }
    }

    private function sendMessage($message)
    {
        $model_message = Model('message');
        $insert_arr = array();
        $insert_arr['from_member_id'] = 0;
        $insert_arr['member_id'] = $this->member_id;
        $insert_arr['msg_content'] = $message;
        $insert_arr['message_type'] = 1;

        $model_message->saveMessage($insert_arr);
    }

    private function sendShort($number,$smscode,$param) {
        $sms = new Sms();
        $ret = $sms->send_oper($number,$smscode,$param);

        $ret = json_encode($ret);
        Log::record("sendShort {$ret}",Log::DEBUG);
    }
}
