<?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_List_Export
{
  var $order;
  var $results;
  var $pagename;
  var $title;
  
  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 $cardcompany = array(1 => "VISA", 
                           2 => "MASTER",
                           3 => "NICOS",
                           4 => "JCB",
                           5 => "アメックス");
    var $odno;
    var $created;
    var $sumprice;
    
    /**
     * [[機能説明]]
     *
     * @access  public
     */
    function execute()
    {
        $log =& LogFactory::getLog();
        $log->debug("Admin_Ordermanage_List_Exportが実行されました", "Admin_Ordermanage_List_Export#execute");
        
        $this->results = $this->order->OrderSearchResults(50000);
        unset($this->results["recordcount"]);
        foreach($this->results as $key => $value){
             $odno[] = $this->results[$key]["orderno"];
        }
        
        //詳細情報の取得
        foreach($odno as $key => $v){
            $res[] = $this->order->listprice($v);
        }
        //購入合計金額取得の為に
        foreach ($res as $key => $value) {
            foreach ($res[$key] as $key => $value) {
                if ($value["typediv"]==1 || 
                    $value["typediv"]==2 || 
                    $value["typediv"]==3 || 
                    $value["typediv"]==10 ||
                    $value["typediv"]==11) {
                    $salesprice[$value["orderno"]][] = $value["price"];
                } else {
                    $otherprice[$value["orderno"]][] = $value["price"];
                }
            }
        }

        foreach($salesprice as $key => $value){
            $price[$key] = number_format(array_sum($value));
        }
        $this->sumprice = $price;
        
        
        $path = TEMP_DIR;
        $filename = "export.csv";
        $filepathname = $path.$filename;
        
        $this->createCSV($filepathname);
        $this->created = true;
        $this->exportCSV($filepathname, $filename);
        return 'success';
    }
    
    /**
    * CSVファイル作成
    *
    */
    
    function createCSV($filepathname) {
        $tmp = array();
        
        // 更新前データから更新したデータだけ抜き出す
        foreach ( $this->results as $key => $val){
            //$send = ($val["depositdiv"]==3) ? "代引" : ($val["takkyubin"]==1) ? "宅急便" : "メール便";
            //$depo = ($val["depositdiv"]==1) ? "カード会社：". $this->cardcompany[$val[cardcompany]] : ($val["depositdiv"]==4) ? "支店番号：". $val["shitennumberkey"] ."口座番号：". $val["kouzanumberkey"] : '';
            $send = "";
            $depo = "";
            if($val["depositdiv"]==3) {
                $send = "コレクト";
                //$sendcode = 2;
            } else if($val["takkyubin"]==1) {
                $send = "宅急便";
                //$sendcode = 0;
            } else {
                $send = "メール便";
                //$sendcode = 3;
            }
            
            if($val["depositdiv"]==1) {
                $depo = $this->cardcompany[$val["cardcompany"]];
            } else if ($val["depositdiv"]==4) {
                $depo = $val["kouzanumberkey"];
            }

            $tmp[] = array($val["orderno"],
                           substr($val["orderdate"], 0, 19),
                           (!empty($val["ordermember"])) ? $val["lastnm"]." ".$val["firstnm"] : $val["sendbuyer"], 
                           $this->sumprice[$val["orderno"]],         // 取引金額
                           $val["depostate"]);                        // 入金状態
        }
        
        $this->odrlist =  array_merge(array(array(
                                              '受注番号',
                                              '受注日時',
                                              '購入者',
                                              '取引金額',
                                              '入金状態')), $tmp);

        //$fullpath = DATAEXPORT_DL_DIR . "/order-list.csv";
        // =>CSVファイルのファイル名を変更する時は関連テンプレートのリンクも変更する必要あり
        
        $fp = fopen($filepathname, 'w');
        for ($i = 0; $i < count($this->odrlist); $i++) {
            fputcsv($fp, $this->odrlist[$i]);
        }
        fclose($fp);
        
        // ファイル内容のエンコードを UTF-8 から SJIS へ変換
        //$enc = mb_convert_encoding(file_get_contents($filepathname), "SJIS","UTF-8");
        //file_put_contents($filepathname, $enc);
        return 0;
    }
    
    function exportCSV($filepathname, $filename="export.csv")
    {
        $len = filesize($filepathname);
        header("Cache-Control: public");
        header("Pragma: public");
        header ("Content-Disposition: inline ; filename=$filename");
        header ("Content-type: text/octet-stream");
        header ("Content-Length: ". $len);
        $handle = fopen ($filepathname, "r");
        while (!feof ($handle)) {
            $buffer = fgets($handle, 4096);
            $buffer = mb_convert_encoding($buffer, "SJIS","UTF-8");
            echo $buffer;
        }
        fclose ($handle);

        return TRUE;
    }

}
?>
