<?php

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

class Index extends CI_Controller
{
    public function __construct() 
    {
        parent::__construct();
        $this->permission->is_admin(false);
        $this->load->model('Paypal_model');
    }

    public function indexs($date='all',$page=1)
    {
        $data=array();
        $data['current_m']=$date=='all'?date('Ym'):date('Ym',strtotime($date));
        $data['current_d']=$date=='all'?'':date('Ymj',strtotime($date));
        $data['userdata']=$this->session->userdata('admin_chtcdn');
        
        $date=$date=='all'?'all':date('Y-m-d',strtotime($date));
        $list=$this->Paypal_model->get_mail_list2(30,'',$date);

        $pages['total'] = count($list); //数据总条数
        $pages['pageSize'] = 30; //每页展示数量
        $pages['url'] = site_url("apps/paypal/index/index/".$date.'/'); //页码链接
        $pages['current'] = $page; //当前页码
        $data['pageinfo'] = show_page($pages);

        $mail_id_str = 0;
        $list = array_slice($list, $pages['pageSize'] * ($page - 1), $pages['pageSize']);
        foreach ($list as $v) {
            $mail_id_str.=',' . $v->M_SN;
        }
        $data['list']=array();
        !empty($list) && $data['list']=$this->Paypal_model->get_mail_list2(30,$mail_id_str);

        $this->load->view('n-header', $data);
        $this->load->view('index2');
        $this->load->view('n-footer');
    }

    public function details($mail_sn,$tpl=0)
    {
        $data=array();
        $mailinfo=$list=$this->Paypal_model->get_mail_list2(30,$mail_sn);
        $mailinfo=$mailinfo[0];
        $data['mail']=$mailinfo;
        if ($tpl==0) {
            $data['current_m']=date('Ym',strtotime($mailinfo->M_AddTime));
            $data['current_d']=date('Ymj',strtotime($mailinfo->M_AddTime));
            $data['detail_tpl']='1';
            $data['userdata']=$this->session->userdata('admin_chtcdn');
            !empty($mailinfo->pm_orderid) && $data['orderinfo']=$this->Paypal_model->get_order($mailinfo->pm_orderid,true);
            $this->load->view('n-header', $data);
            $this->load->view('index2');
            $this->load->view('n-footer');
        }else{
            $this->load->view('detail2', $data);
        }
    }

    public function index($date='all',$page=1)
    {
        $data=array();
        $data['current_m']=$date=='all'?date('Ym'):date('Ym',strtotime($date));
        $data['current_d']=$date=='all'?'':date('Ymj',strtotime($date));
        $data['userdata']=$this->session->userdata('admin_chtcdn');
        
        $date=$date=='all'?'all':date('Y-m-d',strtotime($date));
        $list=$this->Paypal_model->get_mail_list(30,'',$date);

        $pages['total'] = count($list); //数据总条数
        $pages['pageSize'] = 30; //每页展示数量
        $pages['url'] = site_url("apps/paypal/index/index/".$date.'/'); //页码链接
        $pages['current'] = $page; //当前页码
        $data['pageinfo'] = show_page($pages);

        $mail_id_str = 0;
        $list = array_slice($list, $pages['pageSize'] * ($page - 1), $pages['pageSize']);
        foreach ($list as $v) {
            $mail_id_str.=',' . $v->mail_sn;
        }
        $data['list']=array();
        !empty($list) && $data['list']=$this->Paypal_model->get_mail_list(30,$mail_id_str);

        $this->load->view('n-header', $data);
        $this->load->view('index');
        $this->load->view('n-footer');
    }

    public function search()
    {
        $data=array();
        $data['current_m']=date('Ym');
        $data['current_d']='';
        $data['userdata']=$this->session->userdata('admin_chtcdn');

        $data['list']=array();
        $mail_o_orderno=$this->input->post('search_key');
        $data['search_key']=$mail_o_orderno;
        $data['list']=$this->Paypal_model->get_search_mails($mail_o_orderno);

        $this->load->view('n-header', $data);
        $this->load->view('index');
        $this->load->view('n-footer');
    }

    public function my_paypal()
    {
        $userdata=$this->session->userdata('admin_chtcdn');
        $data['current_m']=date('Ym');
        $data['current_d']='';
        $data['userdata']=$userdata;

        $data['list']=array();
        if($userdata!=false && !empty($userdata['OPI_Email']) && !empty($userdata['OPI_FirstName'])){
            $data['list']=$this->Paypal_model->get_my_order($userdata['OPI_Email'],$userdata['OPI_FirstName']);
        }
        $this->load->view('n-header', $data);
        $this->load->view('index');
        $this->load->view('n-footer');
    }

    public function detail($mail_sn,$tpl=0)
    {
        $data=array();
        $mailinfo=$list=$this->Paypal_model->get_mail_list(30,$mail_sn);
        $mailinfo=$mailinfo[0];
        $data['mail']=$mailinfo;
        if ($tpl==0) {
            $data['current_m']=date('Ym',strtotime($mailinfo->mail_date));
            $data['current_d']=date('Ymj',strtotime($mailinfo->mail_date));
            $data['detail_tpl']='1';
            $data['userdata']=$this->session->userdata('admin_chtcdn');
            $data['orderinfo']=$this->Paypal_model->get_order($mailinfo->mail_o_orderno,true);
            $this->load->view('n-header', $data);
            $this->load->view('index');
            $this->load->view('n-footer');
        }else{
            $mailinfo->mail_body = str_replace("#@#", "'", $mailinfo->mail_body);
            $mailinfo->mail_body=htmlspecialchars_decode($mailinfo->mail_body);
            $this->load->view('detail', $data);
        }
    }

    //下载远程服务器邮件
    public function load_mail($redirect=0)
    {
        //邮箱配置
        $this->lang->load('config');
        $paymail=$this->lang->line('paymail');
        $host       = $paymail['host'];
        $port       = $paymail['port'];
        $user       = pack("H*",$paymail['user']);
        $password   = pack("H*",$paymail['password']);
        $checkmail  = $paymail['mail'];
        //连接邮箱服务器
        if(!($sock = fsockopen(gethostbyname($host),$port,$errno,$errstr))){
            exit($errno.': '.$errstr);
        }
        stream_set_blocking($sock,true);
        
        $command = "USER ".$user."\r\n";
        fwrite($sock,$command);
        fgets($sock);
        
        $command = "PASS ".$password."\r\n";
        fwrite($sock,$command);
        fgets($sock);

        $command = "stat\r\n";
        fwrite($sock,$command);
        fgets($sock);

        $command = "LIST\r\n";
        fwrite($sock,$command);

        //获取邮件序号ID s
        $all_mails = array();
        while(true)
        {
            $msg = fgets($sock);       
            if(!preg_match('/^\+OK/' , $msg) && !preg_match('/^\./' , $msg))
            {
                $msg = preg_replace('/\ .*\r\n/' , '' , $msg);
                array_push($all_mails,$msg);
            }
            if(preg_match('/^\./',$msg)){
                break;
            }
        }

        //按时间先后重新排序邮件
        $insert_cols='';
        $array_mails  = array();
        krsort($all_mails);
        $i=0;
        $breakflag=false;
        //提取每一封邮件内容
        foreach($all_mails as $item)
        {
            $mail_content = '';
            $mail_body='';
            fwrite($sock, "RETR $item\r\n");
            while(true)
            {
                $msg = fgets($sock);
                $mail_content .= $msg;
                if(preg_match('/^\./', $msg))
                {
                    //从邮件内容提取改邮件的传输编码$encoding，及显示用的编码$charset
                    $encoding=explode('Content-Transfer-Encoding:', $mail_content);
                    if (!isset($encoding[1])) {
                        break;
                    }
                    $encoding[1]=str_replace(array("\t","\n","\r"), ' ', $encoding[1]);
                    $encoding=explode(' ', trim($encoding[1]));
                    $encoding=strtoupper(trim($encoding[0]));

                    $charset=explode('charset=', $mail_content);
                    $charset[1]=str_replace(array("\t","\n","\r"), ' ', $charset[1]);
                    $charset=explode(' ', trim($charset[1]));
                    $charset=trim($charset[0]);

                    //提取邮件mailbody，对邮件内容进行解码,然后统一用utf8编码输出
                    $mail_header=$mail_content;
                    switch ($encoding) {
                    case '7BIT' :
                    case '8BIT' : 
                        $mail_content = mb_convert_encoding($mail_content, 'utf-8', $encoding);
                        $mail_body =$mail_content;
                        $mail_header=$mail_content;
                        break;
                    case 'BASE64' :
                        //base64解码对要解码的字符串有严格要求，必须先把多余部分去掉
                        $mail_content=str_replace('----NextPart_048F8BC8A2197DE2036A--', '', $mail_content);
                        $mail_body=end(explode('charset='.$charset, $mail_content));
                        $mail_body =base64_decode($mail_body);
                        $mail_body = mb_convert_encoding($mail_body, 'utf-8', $charset);
                        $mail_content = mb_convert_encoding($mail_content, 'utf-8', $charset);
                        $mail_header=$mail_content;
                        break;
                    case 'QUOTED-PRINTABLE' :
                        $mail_arr=explode('<html>', $mail_content);
                        $mail_body=end($mail_arr);
                        $mail_header=$mail_arr[0];
                        $mail_arr_temp=explode('</html>', $mail_body);
                        $mail_body=$mail_arr_temp[0];
                        $mail_body=str_replace(array('=A0','=92','=A9','=96'), array(' ',"'",' ','-'), $mail_body);
                        $mail_body= '<html>'.$mail_body.'</html>';
                        $mail_body=quoted_printable_decode($mail_body);
                        $mail_body = mb_convert_encoding($mail_body, 'utf-8', $charset);
                        $mail_content = mb_convert_encoding($mail_content, 'utf-8', $charset);
                        break;
                    }
                    //提取邮件各属性
                    $structures=iconv_mime_decode_headers($mail_header, 0, "UTF-8");
                    $From=array();
                    isset($structures['From'])?$From=explode('via PayPal', $structures['From']):'';
                    $array_mails[$item]->mail_sendstate=0;
                    $array_mails[$item]->message_id = isset($structures['Message-Id'])?$structures['Message-Id']:'';
                    $array_mails[$item]->from = $structures['Reply-To'];
                    $array_mails[$item]->from_name = isset($From[0])?$From[0]:'';
                    $array_mails[$item]->to = 'pays@chinahighlights.com';
                    $array_mails[$item]->to_name = 'Guilin China International Travel Service Co., Ltd';//$structures['To'];
                    $array_mails[$item]->date = isset($structures['Date'])?date('Y-m-d H:i:s',strtotime($structures['Date'])):'';
                    $subject = isset($structures['Subject'])?$structures['Subject']:'';
                    $array_mails[$item]->from_name=str_replace("'", '#@#', $array_mails[$item]->from_name);
                    $array_mails[$item]->subject = str_replace("'", '#@#', $subject);
                    $array_mails[$item]->mail_body = str_replace("'", '#@#', htmlspecialchars($mail_body));
                    
                    //提取金额 
                    $money_flag='$';
                    $money_type='USD';
                    $money=0;
                    $match_result=preg_match('/You received a payment of(.*?)from/i', $mail_body,$price);
                    if ($match_result==1) {
                        $price=trim($price[1]);
                        $price=explode(' ', $price);
                        $money=trim($price[0]);
                        for($j=0;$j<strlen($money);$j++){
                            if(is_numeric($money[$j]) && $j!=0){
                                $money_flag=substr($money,0,$j);
                                $money=substr($money,$j);
                                break;
                            }
                        }
                        $money_type=trim($price[1]);
                    }
                    $array_mails[$item]->money_flag=$money_flag;
                    $array_mails[$item]->money_type=$money_type;
                    $array_mails[$item]->money=str_replace(',', '', $money);

                    //判断邮件是否已经down过
                    if (empty($array_mails[$item]->date)) 
                    {
                        //日期判断不了的用邮件标识ID来判断
                        $is_loaded=$this->Paypal_model->get_list_by_msgid($array_mails[$item]->message_id);
                        if (!empty($is_loaded)) {
                            unset($array_mails[$item]);
                            break;
                        }else{
                            $array_mails[$item]->date =date('Y-m-d H:i:s');
                        }
                    }
                    else
                    {
                        //时间比数据库中最新邮件的时间晚的才算是新邮件
                        $newest_mail_date=$this->Paypal_model->get_newest_mail_date();
                        if (strtotime($array_mails[$item]->date)<=strtotime($newest_mail_date)) {
                            $breakflag=true;
                            unset($array_mails[$item]);
                            break;
                        }
                    }

                    //提取paypal交易号
                    preg_match('/cmd=_view-a-trans(.*)id=(.*?)\"\>/i', $mail_body,$transid);
                    $TransactionID=end($transid);
                    $array_mails[$item]->TransactionID=$TransactionID;
                    $orderinfo2=explode('<strong>Note from', $mail_body);

                    //提取订单号（有Description类型的邮件）
                    $array_mails[$item]->orderid='';
                    if (empty($array_mails[$item]->TransactionID)) {
                        unset($array_mails[$item]);
                        break;//没有交易号的不处理
                    }
                    if (preg_match('/Description(.*?)<\/table>/i', $mail_body,$orderinfo)) {
                        preg_match('/align=\"left\">(.*?)<\/td>/i', $orderinfo[0],$orderinfo);
                        $orderinfo=explode('--', $orderinfo[1]);
                        $orderinfo=$orderinfo[0];
                        if (strpos($orderinfo, 'Tracking Code:')!==false) {
                            $orderinfo=explode('Tracking Code:', $orderinfo);
                            $orderinfo=explode('Travel Advisor', $orderinfo[1]);
                            $orderinfo=$orderinfo[0];
                        }
                        $orderinfo=explode(',', $orderinfo);
                        $array_mails[$item]->orderid=trim($orderinfo[0]);
                    }
                    //提取订单号(Note from类型邮件)
                    elseif (isset($orderinfo2[1])) {
                        $orderinfo=explode('</p>', $orderinfo2[1]);
                        $orderinfo=trim($orderinfo[0]);
                        $orderinfo=explode(':', $orderinfo);
                        $array_mails[$item]->orderid=trim($orderinfo[1]);
                    }

                    //对订单号进行过滤
                    $temp_orderid=$array_mails[$item]->orderid;
                    $temp_orderid=explode('-', $temp_orderid);
                    if (isset($temp_orderid[1])) {
                        $array_mails[$item]->orderid=trim($temp_orderid[1]);
                    }
                    $array_tempid=explode(' ', $array_mails[$item]->orderid);
                    $array_mails[$item]->orderid=$array_tempid[0];
                    $array_mails[$item]->orderid=str_replace(array('<span>','</span>','<br/>'), '', $array_mails[$item]->orderid);
                    
                    if (empty($array_mails[$item]->orderid)) {
                        //unset($array_mails[$item]);
                        break;
                    }

                    //查找外联信息
                    $advisor_info=$this->Paypal_model->get_order($array_mails[$item]->orderid);
                    $array_mails[$item]->OPI_Email=isset($advisor_info->OPI_Email)?$advisor_info->OPI_Email:'';
                    $array_mails[$item]->OPI_FirstName=isset($advisor_info->OPI_FirstName)?$advisor_info->OPI_FirstName:isset($advisor_info->OPI_Name)?$advisor_info->OPI_Name:'';                    
                    
                    //有订单号，但是匹配不到外联（带收款进来的新订单）
                    if (empty($array_mails[$item]->OPI_Email) && empty($array_mails[$item]->OPI_FirstName)) {
                        $array_mails[$item]->mail_sendstate=2;
                    }
                    //匹配到了外联，但是外联没有邮箱
                    elseif (empty($array_mails[$item]->OPI_Email) && !empty($array_mails[$item]->OPI_FirstName)) {
                        $array_mails[$item]->mail_sendstate=3;
                    }

                    break;
                }

            }
            if ($breakflag) {
                break;
            }
            if (isset($array_mails[$item])) {
                $insert_cols.="(0,'".$array_mails[$item]->orderid."',$item,'".$array_mails[$item]->message_id."','".$array_mails[$item]->from."','".$array_mails[$item]->OPI_Email."','',N'".$array_mails[$item]->from_name."',N'".$array_mails[$item]->OPI_FirstName."',N'".$array_mails[$item]->subject."',N'".$array_mails[$item]->mail_body."',0,'".$array_mails[$item]->date."',0,0,'PAYPALSENT','',".$array_mails[$item]->mail_sendstate.",'".$array_mails[$item]->TransactionID."'),";
                //更新收款记录（只针对新的收款）
                $money_list=$this->Paypal_model->get_money_list($array_mails[$item]->orderid,$array_mails[$item]->money,mb_strtoupper($array_mails[$item]->money_type));
                if (!empty($money_list) && empty($money_list[0]->GAI_CusEmail) && empty($money_list[0]->GAI_Memo)) {
                    //$this->Paypal_model->update_account_info($array_mails[$item]->from,'交易号:'$array_mails[$item]->TransactionID,$money_list[0]->GAI_SN);
                }
            }
        }

        //保存邮件
        $insert_cols=trim($insert_cols,',');
        if (!empty($insert_cols)) {
            $result=$this->Paypal_model->save_mail($insert_cols);
            echo '更新成功!';
        }else{
            echo '已经是最新!';
        }

        $command = "QUIT\r\n";
        fwrite($sock,$command);
        if ($redirect==1) {
            redirect(site_url('apps/paypal'));
        }
    }

    //用于定时发送邮件
    public function send_mail()
    {
        $mail_info=$this->Paypal_model->get_sended_list(1,0);
        if (empty($mail_info)) {
            echo '暂时没有需要发送的邮件!';
            return true;
        }
        $mail_info=$mail_info[0];

        $from_email=$mail_info->mail_from;

        $tolist_array=array();
        $to_list=explode(';', $mail_info->mail_to);
        foreach ($to_list as $touser) {
            $tolist_array[]=trim($touser);
        }
        $cc_list_array=array();
        $cc_list=explode(';', $mail_info->mail_cc);
        foreach ($cc_list as $cc_user) {
            $cc_list_array[]=trim($cc_user);
        }

        $subject=str_replace("#@#", "'", $mail_info->mail_subject);
        $mail_info->mail_body = str_replace("#@#", "'", $mail_info->mail_body);
        $mailbody=htmlspecialchars_decode($mail_info->mail_body);

        //$sent_result=$this->Paypal_model->sendmail($from_email,$tolist_array,$cc_list_array,$subject,$mailbody);
        $this->Paypal_model->set_sent($mail_info->mail_sn);
        $this->set_owner();
        //var_dump($sent_result);
    }

    public function set_owner()
    {
        //新订单，无外联,每次更新最新的10条
        $mail_info2=$this->Paypal_model->get_sended_list(10,2);
        if (!empty($mail_info2)) {
            foreach ($mail_info2 as $key => $mail_info) {
                $advisor_info=$this->Paypal_model->get_order($mail_info->mail_o_orderno);
                $OPI_Email=isset($advisor_info->OPI_Email)?$advisor_info->OPI_Email:'';
                $OPI_FirstName=isset($advisor_info->OPI_FirstName)?$advisor_info->OPI_FirstName:isset($advisor_info->OPI_Name)?$advisor_info->OPI_Name:'';                    
                //设置外联邮箱，并把邮件设置为未发送
                if (!empty($OPI_Email)) {
                    $this->Paypal_model->update_mail($mail_info->mail_sn,$OPI_Email,$OPI_FirstName,0);
                }
            }
        }
        
        //外联无邮箱,每次更新最新的10条
        $mail_info3=$this->Paypal_model->get_sended_list(10,3);
        if (!empty($mail_info3)) {
            foreach ($mail_info3 as $key => $mail_info) {
                $advisor_info=$this->Paypal_model->get_order($mail_info->mail_o_orderno);
                $OPI_Email=isset($advisor_info->OPI_Email)?$advisor_info->OPI_Email:'';
                $OPI_FirstName=isset($advisor_info->OPI_FirstName)?$advisor_info->OPI_FirstName:isset($advisor_info->OPI_Name)?$advisor_info->OPI_Name:'';                    
                //设置外联邮箱，并把邮件设置为未发送
                if (!empty($OPI_Email)) {
                    $this->Paypal_model->update_mail($mail_info->mail_sn,$OPI_Email,$OPI_FirstName,0);
                }
            }
        }
        echo 'ok';
    }


    //从paypal接口获取交易记录列表
    public function get_paypal() 
    {
        //查询条件  最后一次更新的时间
        $last_paypal_msg=$this->Paypal_model->last_paypal_msg();
        $last_date=empty($last_paypal_msg)?date('Y-m-d').' 00:00:00':$last_paypal_msg[0]->pm_payment_date;
        $last_date=str_replace(' ', 'T', $last_date).'Z';
        $param['request'] = array(
            'TRANSACTIONCLASS'=>'ALL',
            'startdate'     => $last_date
        );


        //访问接口，并对返回的数据转换格式
        $sandbox = '0';
        $base = $this->base($sandbox);
        $transactions = $this->get_transactions($base,$param);
        $transactions=urldecode($transactions);
        $result_count=substr_count($transactions,'L_TIMESTAMP'); //交易记录条数
        $list=array();
        $temparray=explode('&', $transactions);
        foreach ($temparray as $key => $value) {
            $temp_arr=explode('=', $value);
            if (!isset($temp_arr[1])) {
                $keys=array_keys($list);
                $last_key=array_pop($keys);
                $list[$last_key].='&'.$temp_arr[0];
            }else{
                $list[$temp_arr[0]]=$temp_arr[1];
            }
        }

        //保存信息
        for ($i=0; $i < $result_count; $i++) 
        {
            //已经更新了的记录就不再保存,并停止处理剩下的数据
            $has_exit=$this->Paypal_model->get_paypal_msg($list['L_TRANSACTIONID'.$i]);
            if (!empty($has_exit)) {
                die('更新了'.$i.'/'.$result_count.'条记录');
            }
            //只保存已经支付完成，且交易类型是付款和退款的交易记录,因为其他类型的交易记录获取不到交易详情
            if ($list['L_STATUS'.$i]!='Completed' || !in_array($list['L_TYPE'.$i],array('Payment','Refund'))) {
                continue;
            }
            //保存交易信息
            $pm_transaction_id=$list['L_TRANSACTIONID'.$i];//交易号
            $pm_orderid='';                            //订单号
            $pm_item_name='';                          //交易备注说明
            $pm_money=$list['L_AMT'.$i];               //交易金额
            $pm_currency=$list['L_CURRENCYCODE'.$i];   //交易币种
            $pm_payer=$list['L_NAME'.$i];              //客人名字
            $pm_payer_email='';                        //客人邮箱
            $pm_payer_status='';                       //是否paypal已认证的客人
            $pm_memo='';                               //交易详情json数据集
            $pm_pay_type=$list['L_TYPE'.$i];           //交易类型
            $pm_payment_date=$list['L_TIMESTAMP'.$i];  //交易时间
            $pm_payment_date=str_replace(array('T','Z'), array(' ',''), $pm_payment_date);
            $insert_res=$this->Paypal_model->save_paypal_msg($pm_transaction_id,$pm_orderid,$pm_item_name,$pm_money,$pm_currency,$pm_payer,$pm_payer_email,$pm_payer_status,$pm_memo,$pm_payment_date,$pm_pay_type);
        }

        echo ('更新了'.($result_count).'条记录');

    }

    //根据交易号获取交易详细信息
    public function get_transactions_detail() 
    {
        //从数据库提取一条还没有更新交易详情的记录获取交易号
        $pay_data=$this->Paypal_model->get_paypal_msg();
        if (empty($pay_data)) {
            die('暂无更新');
        }
        $pay_data=$pay_data[0];
        $transactionsID=$pay_data->pm_transaction_id;

        //接口信息拼接
        $sandbox = '0';
        $base = $this->base($sandbox);
        $post  = "METHOD=GetTransactionDetails&VERSION=100.0&TRANSACTIONID=$transactionsID";
        $detail = $this->call($base,$post);

        //格式化接口返回数据
        $detail=urldecode($detail);
        $detail_list=array();
        $temparray=explode('&', $detail);
        foreach ($temparray as $key => $value) {
            $temp_arr=explode('=', $value);
            $detail_list[$temp_arr[0]]=$temp_arr[1];
        }

        //请求数据状态是成功且支付状态是完成的，更新交易记录信息
        if ($detail_list['ACK']=='Success' && $detail_list['PAYMENTSTATUS']=='Completed') 
        {
            $pm_sn=$pay_data->pm_sn;
            $pm_orderid=(isset($detail_list['INVNUM']) && !empty($detail_list['INVNUM']))?$detail_list['INVNUM']:isset($detail_list['CUSTOM'])?$detail_list['CUSTOM']:isset($detail_list['L_NAME0'])?$detail_list['L_NAME0']:'';
            $pm_item_name=$pm_orderid;
            $orderinfo=$pm_orderid;
            if (strpos($orderinfo, 'Tracking Code:')!==false) {
                $orderinfo=explode('Tracking Code:', $orderinfo);
                $orderinfo=explode('Travel Advisor', $orderinfo[1]);
                $orderinfo=trim($orderinfo[0]);
            }
            //订单号过滤
            $orderinfo=explode('--', $orderinfo);
            $orderinfo=$orderinfo[0];
            $orderinfo=explode(',', $orderinfo);
            $orderid=trim($orderinfo[0]);
            $temp_orderid=explode('-', $orderid);
            if (isset($temp_orderid[1])) {
                $orderid=trim($temp_orderid[1]);
            }
            $tempid=explode(' ', $orderid);
            $pm_orderid=$tempid[0];//订单号

            $pm_payer_email=$detail_list['EMAIL'];         //客人邮箱
            $pm_payer_status=$detail_list['PAYERSTATUS'];  //客人认证状态
            $pm_memo=json_encode($detail_list);            //序列化数据
            $this->Paypal_model->update_paypal_msg($pm_sn,$pm_orderid,$pm_item_name,$pm_payer_email,$pm_payer_status,$pm_memo);
        
            //查找外联信息
            $M_State=0;
            if (!empty($pm_orderid)) {
                $pm_invoice=$pm_orderid;
                $advisor_info=$this->Paypal_model->get_order($pm_orderid);
                $OPI_Email=isset($advisor_info->OPI_Email)?$advisor_info->OPI_Email:'';
                $OPI_FirstName=isset($advisor_info->OPI_FirstName)?$advisor_info->OPI_FirstName:isset($advisor_info->OPI_Name)?$advisor_info->OPI_Name:'';                    
                
                //有订单号，但是匹配不到外联（带收款进来的新订单）
                if (empty($OPI_Email) && empty($OPI_FirstName)) {
                    $M_State=2;
                }
                //匹配到了外联，但是外联没有邮箱
                elseif (empty($OPI_Email) && !empty($OPI_FirstName)) {
                    $M_State=3;
                }

            }
            //没有订单号，转发给陆燕
            else{
                $OPI_Email='lussie@chinahighlights.net';
                $OPI_FirstName='Lussie';
            }

            //给外联发送通知邮件
            $fromName=$pay_data->pm_payer;
            $fromEmail=$detail_list['EMAIL'];
            $toName=$OPI_FirstName;
            $toEmail=$OPI_Email;
            $subject='来自'.$detail_list['EMAIL'].'的收款';

            $data['mailinfo']=$pay_data;
            $data['mailinfo']->INSURANCEOPTIONSELECTED=isset($detail_list['INSURANCEOPTIONSELECTED'])?$detail_list['INSURANCEOPTIONSELECTED']:'';
            $data['mailinfo']->SUBJECT=isset($detail_list['SUBJECT'])?$detail_list['SUBJECT']:'';
            $data['mailinfo']->NOTE=isset($detail_list['NOTE'])?$detail_list['NOTE']:'';
            $data['mailinfo']->pm_payer_email=$detail_list['EMAIL'];
            $data['mailinfo']->pm_item_name=$pm_item_name;

            $body=$this->load->view('mail_tpl',$data,true);
            $M_RelatedInfo=$pm_sn;
            $M_AddTime=$pay_data->pm_payment_date;
            $this->Paypal_model->save_automail($fromName, $fromEmail, $toName, $toEmail, $subject, $body,$M_RelatedInfo,$M_State,$M_AddTime);
        }

        echo $transactionsID.'更新成功';
    }

    //设置授权 
    public function base($sandbox) {

        if($sandbox=='1') { 
            $base = array(
                'url'       => 'https://api-3t.sandbox.paypal.com/nvp',
                'username'  => 'pays_api1.chinahighlights.com',
                'password'  => 'HWJ7BFSZBZUETZ4K',
                'signature' => 'AxfjDmuPaaxMccY-8ZHIWGDHQKxOAyYzBPToLDzU-cgnldnh6eZGKJMn'
                );
        }

        if($sandbox=='0') { 
            $base = array(
                'url'       => 'https://api-3t.paypal.com/nvp',
                'username'  => 'pays_api1.chinahighlights.com',
                'password'  => 'HWJ7BFSZBZUETZ4K',
                'signature' => 'AxfjDmuPaaxMccY-8ZHIWGDHQKxOAyYzBPToLDzU-cgnldnh6eZGKJMn'
                );
        }       

        return $base; 
    }

    //获取交易历史记录列表
    public function get_transactions($base,$param) {
        $post  = 'METHOD=TransactionSearch&';
        $post .= 'VERSION=100.0';

        foreach ($param['request'] as $key => $value) {
                $post .= '&' . strtoupper($key) . '=' . $value;
        }

        $transactions = $this->call($base,$post);
        return $transactions;
    }    

    //请求接口
    public function call($base,$post) {
        $post .= '&PWD='.$base['password'];
        $post .= '&USER='.$base['username'];
        $post .= '&SIGNATURE='.$base['signature'];

        $ch = curl_init($base['url']);
        curl_setopt($ch, CURLOPT_PORT, 443);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
        curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);    
        $response = curl_exec($ch);

        if(empty($response)) { return 'No response received.'; }
        else {
            return $response;
        }
        curl_close($ch);
    }


}