<?php
/**
 * @copyright ONE/DEPO Project
 * @license   PHP License 3.01 <http://www.php.net/license/3_01.txt>
 */


/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */

/**
 * [[機能説明]]
 *
 * @package     [[package名]]
 * @author      Your Name <mail@example.com>
 * @access      public
 */
class Admin_Ordermanage_Order_Detail_Form
{
  
  var $pagename;
  
  var $order_date_start;
  var $order_date_end;
  var $order_time_start;
  var $order_time_end;
  var $orderno_start;
  var $orderno_end;
  var $ordermember;
  var $mailaddr;
  var $state;
  var $display;

  var $from;
  var $order;
  var $results;
  var $res;
  
  var $odno;
  var $orderno;
  var $orderdate;
  var $lastnm;
  var $firstnm;
  var $sendpostalcd;
  var $pref;
  var $sendaddr1;
  var $sendaddr2;
  var $sendtelno1;
  var $addressee;
  var $deposit_updcnt;
  var $deposit_state;
  var $mail;
  var $depositdiv;
  var $depositdivname;
  var $forwardstate;
  var $stockstate;
  var $takkyubin;
  var $enquiryno;

  var $sendbuyername;
  
  var $itemnm;
  var $price;
  var $count;
  
  var $sumprice;
  
  var $cardcompany = array(1 => "VISA", 
                           2 => "MASTER",
                           3 => "NICOS",
                           4 => "JCB",
                           5 => "アメックス");

  //From 予約一覧画面の為に
  var $untrans;
  var $disp_day;
  var $disp_select;

  var $print;
  var $printdate;

  var $ml;
  var $l_mail;

  var $nomember_name;

  var $note;

  // ダウンロード用
  var $dlitem;
  var $dl_check;
  var $dlorder;

  // コンビニ決済情報
  var $cvsinfo;

  // ルミーズ決済情報
  var $remiseinfo;

  var $c_systeminfo;

    /**
     * [[機能説明]]
     *
     * @access  public
     */
    function execute()
    {
      
        $log =& LogFactory::getLog();
        $log->debug("Admin_Ordermanage_Order_Detail_Formが実行されました", "Ordermanage_Order_Detail_Form#execute");
        
        $this->results   = $this->order->Orderdetailview();

       foreach($this->results as $key => $value){
            $type[]=$this->results[$key]["typediv"];
            $fwtype[]=$this->results[$key]["forwardstate"];
            $price[] = $this->results[$key]["price"];
       }
       
      foreach($type as $key => $value){
             if(($value == 1 || $value==2 || $value==3 || $value==10 || $value==11) &&
                ($fwtype[$key]!=8 && $fwtype[$key]!=9)){
             $salesprice[] = $price[$key];
             }
             else{
             $otherprice[] = $price[$key];
             }
       }
       
        $this->sumprice = array_sum($salesprice);

        $dl = $this->dlitem->getDownloadItem($this->results[0]["itemcd"], $this->results[0]["structcd"]);
        $this->dl_check = (!empty($dl)) ? true : false;
        if ($this->dl_check)
        {
            $this->dlorder = $this->dlitem->getDownloadOrder($this->results[0]["orderno"], $this->results[0]["orderrowno"]);
        }

        
        $this->orderno   = $this->results[0]["orderno"];
        $this->orderdate = $this->results[0]["orderdate"];

        $this->nomember_name     = $this->results[0]["sendbuyer"];

        $this->lastnm    = $this->results[0]["lastnm"];
        $this->firstnm   = $this->results[0]["firstnm"];
        $this->sendbuyername   = $this->results[0]["sendbuyer"];
        $this->sendpostalcd = $this->results[0]["sendpostalcd"];
        $this->prefnm       = $this->results[0]["prefnm"];
        $this->sendaddr1    = $this->results[0]["sendaddr1"];
        $this->sendaddr2    = $this->results[0]["sendaddr2"];
        $this->sendtelno1   = $this->results[0]["sendtelno1"];
        $this->addressee    = $this->results[0]["addressee"];
        $this->deposit_updcnt     = $this->results[0]["deposit_updcnt"];
        $this->deposit_state      = $this->results[0]["depositstate"];
        $this->deposit_statename  = $this->results[0]["depostate"];
        $this->mail           = (!empty($this->results[0]["mailaddr"])) ?
                                $this->results[0]["mailaddr"] : $this->results[0]["sendmailaddr"];
        $this->depositdiv     = $this->results[0]["depositdiv"];
        $this->depositdivname = $this->results[0]["depositdivname"];
        $this->forwardstate   = $this->results[0]["forwardstate"];
        foreach ($this->results as $v) {
            if ($this->forwardstate > $v["forwardstate"] && $v["typediv"]==1) {
                $this->forwardstate   = $v["forwardstate"];
            }
        }
        $this->stockstate     = $this->results[0]["stockstate"];
        $this->takkyubin      = $this->results[0]["takkyubin"];
        $this->enquiryno      = $this->results[0]["enquiryno"];
        $this->brief          = "";
        if ($this->depositdiv==1) {
            $this->brief = $this->cardcompany[$this->results[0]["cardcompany"]];
        } elseif ($this->depositdiv==4) {
            $this->brief = $this->results[0]["kouzanumberkey"];
        }

        $this->note = $this->results[0]["note"];

        // コンビニ決済情報
        $str = $this->results[0]["cvsinfo"];
        $this->cvsinfo = $this->getCVS($str);

        // ルミーズ決済情報
        $str = $this->results[0]["remiseinfo"];
        $s = explode("\n", $str);
        $this->remiseinfo = $s[1]; // 一緒に決済した受注番号のみ表示

        
        if($this->untrans=="untrans") $this->pagename = "予約一覧(未発送管理)";
        
        if (isset($this->print)) {
            $year = (int)date("Y")-1988;
            $this->printdate = "平成". $year ."年". 
                               date("m") ."月".
                               date("d") ."日";
            return 'print';
        }

        if ($this->forwardstate==4 && $this->ml==1) {
            $res = $this->sendMail();
            if (!$res) $log->info("send_item mail ", "error");
        }

        if ($this->ml==2) {
            if ($this->dl_check) {
                $res = $this->sendMailOrder('buy_complete_dl');
            } else {
                switch ($this->stockstate) {
                    case 1:
                    $res = $this->sendMailOrder('buy_complete_reserve');
                    break;
                    case 3:
                    $res = $this->sendMailOrder('buy_complete');
                    break;
                }
            }
            if (!$res) $log->info("send_item mail ", "error");
        }

        return 'success';
    }

    function sendMail()
    {
        $results   = $this->order->OrderdetailviewMail($this->orderno);
        
        foreach($results as $key => $value){
            if ($results[$key]["typediv"] == 3) $takkyubin = true;
            $type[]=$results[$key]["typediv"];
            $price[] = $results[$key]["price"];
        }
       
        foreach($type as $key => $value){
            if($value >= 1 and $value <= 3 || $value==10 || $value==11)
                $salesprice[] = $price[$key];
            else
                $otherprice[] = $price[$key];
        }
       
        $sumprice = array_sum($salesprice);
        
        $orderno   = $results[0]["orderno"];
        $orderdate = $results[0]["orderdate"];
        $lastnm    = $results[0]["lastnm"];
        $firstnm   = $results[0]["firstnm"];
        $sendbuyername   = $results[0]["sendbuyer"];
        $sendpostalcd = $results[0]["sendpostalcd"];
        $prefnm       = $results[0]["prefnm"];
        $sendaddr1    = $results[0]["sendaddr1"];
        $sendaddr2    = $results[0]["sendaddr2"];
        $sendtelno1   = $results[0]["sendtelno1"];
        $addressee    = $results[0]["addressee"];
        $deposit_statename  = $results[0]["depostate"];
        $mail           = (!empty($results[0]["mailaddr"])) ?
                           $results[0]["mailaddr"] : $results[0]["sendmailaddr"];
        $depositdiv = $results[0]["depositdiv"];
        $depositdivname = $results[0]["depositdivname"];
        $enquiryno = $results[0]["enquiryno"];
    
        $from        = MAIL_FROM;

        $params = array("username"        => (empty($results[0]["ordermember"])) ? $sendbuyername : $lastnm." ".$firstnm,
                        "takkyubin"       => $takkyubin,
                        "orderdate"       => $orderdate,
                        "orderno"         => $orderno,
                        "depositdiv"      => $depositdiv,
                        "depositdivname"  => $depositdivname,
                        "post"            => $sendpostalcd,
                        "address"         => $prefnm . $sendaddr1,
                        "address2"        => $sendaddr2,
                        "tel"             => $sendtelno1,
                        "addressee"       => $addressee,
                        "enquiryno"       => $enquiryno
                       );
        $params["totalprice"] = $sumprice;

        foreach ($results as $key => $val) {
            $itemlist = array();
            if ($val["typediv"]<>1) {
                if ($val["typediv"] == 2 or 
                    $val["typediv"] == 3 or
                    $val["typediv"] == 10 or
                    $val["typediv"] == 11) {
                    $itemlist["itemnm"] = $val["orderdetailtypename"];
                    $itemlist["price"]  = $val["price"];
                }
            } else {
                $itemlist["itemnm"] = $val["itemnm"] ." ". $val["variationnm"];
                $itemlist["count"]  = $val["count"];
                $itemlist["price"]  = $val["price"];
            }
            $params["itemlist"][] = $itemlist;
        }
        return $this->l_mail->sendFromTemplate("send_item", $mail, $from, $params);
    }

    function sendMailOrder($template)
    {
        $results   = $this->order->OrderdetailviewMail($this->orderno);

        foreach($results as $key => $value){
            if ($results[$key]["typediv"] == 3) $takkyubin = true;
            if ($results[$key]["typediv"] == 10) {
                $daibiki_cost = $results[$key]["price"];
            }
            $type[]=$results[$key]["typediv"];
            $price[] = $results[$key]["price"];
        }

        foreach($type as $key => $value){
            if($value >= 1 and $value <= 3 || $value==10 || $value==11)
                $salesprice[] = $price[$key];
            else
                $otherprice[] = $price[$key];
        }

        $sumprice = array_sum($salesprice);

        $orderno   = $results[0]["orderno"];
        $orderdate = substr($results[0]["orderdate"], 0, 10);
        $lastnm    = $results[0]["lastnm"];
        $firstnm   = $results[0]["firstnm"];
        $sendbuyername   = $results[0]["sendbuyer"];
        $sendpostalcd = $results[0]["sendpostalcd"];
        $prefnm       = $results[0]["prefnm"];
        $sendaddr1    = $results[0]["sendaddr1"];
        $sendaddr2    = $results[0]["sendaddr2"];
        $sendtelno1   = $results[0]["sendtelno1"];
        $addressee    = $results[0]["addressee"];
        $mail           = (!empty($results[0]["mailaddr"])) ?
                           $results[0]["mailaddr"] : $results[0]["sendmailaddr"];
        $usernote     = $results[0]["note"];

        // ダウンロード販売以外
        if (!$this->dl_check) {

        $sellercd = $results[0]["sellercd"];
        if (!empty($sellercd)) {
            $seller = $this -> c_member -> select_one($sellercd);
            if( empty($seller["nicknm"]) ) {
                $nicknm = $seller["lastnm"] ." ". $seller["firstnm"];
            } else {
                $nicknm = $seller["nicknm"];
            }
            $mailaddr = $seller['mailaddr'];
        }

        }
        switch ($results[0]["depositdiv"]) {
        case 1:
        $payment[0] = $results[0]["depositdiv"];
        $payment[1] = $results[0]["cardcompany"];
        $payment[2] = $results[0]["cardnumber"];
        $payment[3] = $results[0]["cardname"];
        $exp = explode('/', $results[0]["cardexp"]);
        $payment[4] = $exp[0];
        $payment[5] = $exp[1];
        switch ($payment[1]) {
            case 1:
            $this->cardmessage = "カード会社：VISA\n";
            break;
            case 2:
            $this->cardmessage = "カード会社：MASTER\n";
            break;
            case 3:
            $this->cardmessage = "カード会社：NICOS\n";
            break;
            case 4:
            $this->cardmessage = "カード会社：JCB\n";
            break;
            case 5:
            $this->cardmessage = "カード会社：アメックス\n";
            break;
        }
        $this->cardmessage .= "下４桁：".$payment[2]."\n";
        $this->cardmessage .= "お支払額：".$sumprice."円";
        break;
        case 2: // コンビニ決済
        $payment[0] = 4;
        parse_str($results[0]["cvsinfo"], $cvsinfo);
        $this->cvsmessage  = "支払いコンビニ店名：";
        switch($cvsinfo["cvs_shop"]) {
            case "01":
            $this->cvsmessage .= "セブンイレブン\n";
            $this->cvsmessage .= "受付番号：".$cvsinfo["receipt_no"] ."\n";

            $note  = "払込票を印刷、もしくは払込票番号を紙などに控えて全国のセブンイレブンにてお支払ください。\n";
            $note .= "払込票番号を紙などでお持ちの場合は、お客様から店員に提示の際に「インターネット代金の支払い」とお伝え下さい。\n";
            $note .= "詳しくは以下のページにてご確認ください。\n";
            $note .= "http://pr.sej.co.jp/in/system.html \n";
            break;

            case "02":
            $this->cvsmessage .= "ローソン・セイコーマート\n";
            $this->cvsmessage .= "受付番号：".$cvsinfo["receipt_no"] ."\n";
            $this->cvsmessage .= "電話番号：".$cvsinfo["cvs_tel"] ."\n";
            $note = "受付番号を紙などに控えて全国のローソンまたはセイコーマートにてお支払ください。\n";
            break;

            case "03":
            $this->cvsmessage .= "ファミリーマート\n";
            $company_code = substr($cvsinfo["receipt_no"], 0, 5);
            $order_no = substr($cvsinfo["receipt_no"], 6, 12);
            $this->cvsmessage .= "受付番号：".$cvsinfo["receipt_no"] ."\n";
            $this->cvsmessage .= "企業コード：".$company_code ."\n";
            $this->cvsmessage .= "注文番号：".$order_no ."\n";
            $note = "企業コード、注文番号を紙などに控えて全国のファミリーマートにてお支払ください。\n";
            break;

            case "04":
            $this->cvsmessage .= "サークルKサンクス・デイリーヤマザキ・ヤマザキデイリーストアー・タイムリー・ミニストップ\n";
            $this->cvsmessage .= "受付番号：".$cvsinfo["receipt_no"] ."\n";
            $mobile_url = preg_replace("/https:\/\/.+?\/JLPcon/",
                                       "https://w2.kessai.info/JLM/JLMcon",
                                       urldecode($cvsinfo["haraikomi_url"]));
            $note  = "統合決済画面を印刷、もしくはオンライン決済番号を紙などに控えて全国のサークルK、サンクス、\n";
            $note .= "デイリーヤマザキ、ヤマザキデイリーストアー、タイムリー、ミニストップ にてお支払ください。\n";
            $note .= "オンライン決済番号のみを紙などでお持ちの場合は、お客様から店員に提示の際に「オンライン決済」である旨お伝え下さい。\n";
            break;
        }
        $this->cvsmessage .= "支払い金額：". $cvsinfo["amount"] ." 円　\n";
        $this->cvsmessage .= "支払い期限：". $cvsinfo["pay_limit"]."\n";

        if (!empty($cvsinfo["haraikomi_url"])) {
            $this->cvsmessage .= "払込票URL：". urldecode($cvsinfo["haraikomi_url"]) ."\n";
        }
        if (!empty($mobile_url)) {
            $this->cvsmessage .= "払込票URL(携帯用)：". $mobile_url ."\n";
        }
        $this->cvsmessage .= "\n". $note;

        $payment["message"] = "【お支払い】\n".$this->cvsmessage;
        break;
        case 3:
        $payment[0] = 2;
        $this->daibikimessage  = "運送会社　：ヤマト運輸\n";
        $this->daibikimessage .= "お支払い　：現金（代金引換払いでは、クレジットはお取扱いしておりません）\n";
        $this->daibikimessage .= "代引手数料：".$daibiki_cost."円\n";
        $this->daibikimessage .= "お支払い額：".$sumprice."円";
        $payment["message"] = "【お支払い】\n". $this->daibikimessage;
        break;
        case 4:
        $payment[0] = 3;
        $payment["shiten"] = $results[0]["shitennumberkey"];
        $payment["kouza"] = $results[0]["kouzanumberkey"];
        $sysinfo = $this->c_systeminfo->selectAll();
        $payment["bank_name"] = $sysinfo[0]["bankname"];
        $payment["shiten_name"] = $sysinfo[0]["shitenname"];
        $payment["kouza_div"] = ($sysinfo[0]["kouzadiv"] == 1) ? "口座" : "当座";
        $payment["kouza_name"] = $sysinfo[0]["kouzaname"];

        $this->bankmessage  = "銀行名：". $sysinfo[0]["bankname"] ."\n";
        //$this->bankmessage .= "銀行コード：0036\n";
        $this->bankmessage .= "支店名：". $sysinfo[0]["shitenname"] ."\n";
        //$this->bankmessage .= "支店番号：". $results[0]["shitennumberkey"] ."\n";
        $this->bankmessage .= "口座種類：". ($sysinfo[0]["kouzadiv"] == 1) ? "口座" : "当座" ."\n";
        $this->bankmessage .= "口座番号：". $results[0]["kouzanumberkey"]  ."\n";
        $this->bankmessage .= "口座名義：". $sysinfo[0]["kouzaname"] ."\n";
        $this->bankmessage .= "お支払額：".$sumprice."円\n";
        $this->bankmessage .= "※振込み手数料はお客様でご負担下さい。";
        $payment["message"] = "【お支払い】".$this->bankmessage;
        break;
        case 5:
        $payment[0] = 5;
        $this->yuubinmessage = "";
        //$params["payment"]["message"] = "【お支払い】\n". $this->yuubinmessage;
        break;
        }
   
        $from        = MAIL_FROM;

        $params = array("username"        => (empty($results[0]["ordermember"])) ? $sendbuyername : $lastnm." ".$firstnm,
                        "takkyubin"       => $takkyubin,
                        "orderdate"       => $orderdate,
                        "orderid"         => $orderno,
                        "payment"         => $payment,
                        "post"            => $sendpostalcd,
                        "address"         => $prefnm . $sendaddr1,
                        "address2"        => $sendaddr2,
                        "tel"             => $sendtelno1,
                        "addressee"       => $addressee,
                        "nicknm"          => $nicknm,
                        "mailaddr"        => $mailaddr,
                        "usernote"        => $usernote
                       );
        $params["totalprice"] = $sumprice;

        foreach ($results as $key => $val) {
            $itemlist = array();
            if ($val["typediv"]<>1) {
                if ($val["typediv"] == 2 && $val["price"]>0)
                    $souryou = $val["price"];
                if ($val["typediv"] == 3 && $val["price"]>0)
                    $takkyubin = $val["price"];
                if ($val["typediv"] == 10 && $val["price"]>0)
                    $daibiki = $val["price"];
                if ($val["typediv"] == 11 && $val["price"]>0)
                    $yuubin = $val["price"];
            } else {
                $itemlist["itemnm"] = $val["itemnm"] ." ". $val["variationnm"];
                $itemlist["count"]  = $val["count"];
                $itemlist["price"]  = $val["price"];
            }
            if (!empty($itemlist)) $params["order"][] = $itemlist;
        }
        $params["souryou"] = $souryou;
        $params["takkyubin"] = $takkyubin;
        $params["daibiki"] = $daibiki;
        $params["yuubin"] = $yuubin;

        if ($this->dl_check) {
            $fid_key = $this->dlorder["orderno"] ."_". $this->dlorder["orderrowno"] ."_". $this->dlorder["membercd"];
            $params["download_url"] = $this->dlitem->getDownloadURL(sha1($fid_key), $this->dlorder["orderno"], $this->dlorder["orderrowno"]);
            $params["dlperiodend"] = $this->dlorder["dlperiodend"];
        }

        return $this->l_mail->sendFromTemplate($template, $mail, $from, $params);
    }


    function getCVS($str) {
        $info = "";
        if (!empty($str)) {
            parse_str($str, $e);

            foreach ($e as $k => $v) {
                switch ($k) {
                case 'cvs_shop':
                    $info .= "支払いコンビニ店名：";
                    if ($v=="01") {
                        $info .= "セブンイレブン\n";
                    } else if ($v=="02") {
                        $info .= "ローソン・セイコーマート\n";
                    } else if ($v=="03") {
                        $info .= "ファミリーマート\n";
                    } else if ($v=="04") {
                        $info .= "サークルKサンクス・デイリーヤマザキ・ヤマザキデイリーストアー・タイムリー・ミニストップ\n";
                    }
                break;

                case 'cvs_name1':
                    $info .= "姓：". $v ."\n";
                break;

                case 'cvs_name2':
                    $info .= "名：". $v ."\n";
                break;

                case 'cvs_name3':
                    $info .= "姓名(カナ)：". $v ."\n";
                break;

                case 'cvs_tel':
                    $info .= "電話番号：". $v ."\n";
                break;

                case 'amount':
                    $info .= "支払い金額：". $v ."\n";
                break;

                case 'pay_limit':
                    $info .= "支払い期限：". $v ."\n";
                break;

                case 'receipt_no':
                    $info .= "受付番号：". $v ."\n";
                break;

                case 'haraikomi_url':
                    $info .= "払込票URL：". urldecode($v) ."\n";
                break;
                }
            }
        }
        return $info;
    }
}
?>
