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


//JSONを扱うためのパーサ
//require_once(WEBAPP_DIR."/JSON.php");

/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
require_once 'Net/UserAgent/Mobile.php';

/**
 * [[機能説明]]
 *
 * @package     [[package名]]
 * @author      Your Name <mail@example.com>
 * @access      public
 */
class Customer_Itembuy_Cart
{
    var $title;
    var $pagename;
//GETに保存される品名コード・構成コード・在庫コード
    var $itemcd;
    var $structcd;
    var $stockcd;

//挿入するか削除するかのモード
    var $mode;

//宅急便を使う
    var $takkyubin;
    var $takkyubin_chk;
//宅急便料金
    var $takkyubinprc;

//ユーザーが入力して更新した購入数と、それをもとに合計した金額
    var $quantity;
    var $sum_quantity;

    // 送料
    var $total_souryou;
    // 合計金額
    var $totalprice;

    // ダウンロード商品
    var $dlflg;

//SESSIONにItemCd,StructCd,StockCd,$quantityを保存するための配列
    var $item_array;

//SESSION変数とauthモジュールと、CartとPreorderのテーブル操作クラス
    var $session;
    var $auth;
    var $c_cart;
    var $c_preorder;
    var $dlitem;

    var $checkpreorder;
    var $d;

    /**
     * [[機能説明]]
     *
     * @access  public
     */
    function execute()
    {
        $mobile = &Net_UserAgent_Mobile::isMobile();
        $sid = ($mobile) ? "&".SID : "";

        $log =& LogFactory::getLog();
        $log->debug("Customer_Itembuy_Cartが実行されました", "Customer_Itembuy_Cart#execute");

        if($this->auth->getAuthData("membercd")) {

            $sess_item_array = $this->session->getParameter('cart_items');
            foreach ($sess_item_array as $item) {
                $this->c_preorder->insert($this->auth->getAuthData("membercd"), 0, $item[0], $item[1], $item[2], $item[3],"");
            }
            $this->session->removeParameter('cart_items');
            $this->session->removeParameter('takkyubin');


            // 処理中のデータがあるか
            $this->checkpreorder = $this->c_cart->checkPreorder($this->auth->getAuthData("membercd"));
            //--
            if ($this->checkpreorder > 0 && $this->d==1) {
                // 仮受注データをクリア(ログインユーザのデータのみ)
                $this->c_cart->updatePreorder($this->auth->getAuthData("membercd"));
                //--

                $scriptname = htmlspecialchars($_SERVER["SCRIPT_NAME"]
                                               , ENT_QUOTES);
                header('location:'.SSL_URL_ROOT.
                                   $scriptname.
                                   '?action=customer_itembuy_cart'. $sid);
                exit;
            }
            // --


        if(isset($this->mode) && isset($this->itemcd) && isset($this->structcd) && isset($this->stockcd)) {
            //追加
            if($this->mode == 'insert') {
                $quantity = intval($this->quantity);
                $quantity = (empty($quantity)) ? 1 : $quantity;
                $this->c_preorder->insert($this->auth->getAuthData("membercd"), 0, $this->itemcd, $this->structcd, $this->stockcd, $quantity, "");

                $scriptname = htmlspecialchars($_SERVER["SCRIPT_NAME"]
                                               , ENT_QUOTES);
                header('location:'.SSL_URL_ROOT.
                                   $scriptname.
                                   '?action=customer_itembuy_cart'. $sid);
                exit;
            }
            //削除
            else if($this->mode == 'delete') {
                $this->c_preorder->delete($this->auth->getAuthData("membercd"), $this->itemcd, $this->structcd, $this->stockcd);
            }
            $scriptname = htmlspecialchars($_SERVER["SCRIPT_NAME"]
                                           , ENT_QUOTES);
            header('location:'.SSL_URL_ROOT.
                               $scriptname.
                               '?action=customer_itembuy_cart'. $sid);
            exit;

            //更新
        } else {
            if (isset($this->quantity)) {
                $items = $this->c_preorder->selectAll($this->auth->getAuthData("membercd"));
                $i = 0;
                foreach($items as $item) {
                    $data = $this->dlitem->getDownloadItem($item['itemcd'], $item['structcd']);
                    if ($data===FALSE || is_null($data)) {
                      if (is_numeric($this->quantity[$i]) && $this->quantity[$i] > 0) {
                        $this->c_preorder->update($this->auth->getAuthData("membercd"), 0, $item['itemcd'], $item['structcd'], $item['stockcd'], $this->quantity[$i],"");
                      }
                      $i++;
                    } else {
                      $this->c_preorder->update($this->auth->getAuthData("membercd"), 0, $item['itemcd'], $item['structcd'], $item['stockcd'],1,"");
                    }
                }

                $scriptname = htmlspecialchars($_SERVER["SCRIPT_NAME"]
                                               , ENT_QUOTES);
                header('location:'.SSL_URL_ROOT.
                                   $scriptname.
                                   '?action=customer_itembuy_cart'. $sid);
                exit;
            }
        }

            //カートの中身取得
            $items = $this->c_preorder->selectAll($this->auth->getAuthData("membercd"));
            $i = 0;
            foreach($items as $item) {
                $this->item_array[] = array($item['itemcd'], $item['structcd'], $item['stockcd'], $item['count']);
            }

            //カートの中のタイトルと価格取得
            $this->set_parameter();

        //セッションから
        } else {
            $this->item_array = $this->session->getParameter('cart_items');

            //追加
            if ($this->mode == 'insert') {
                $res = true;
                //item_arrayに値が存在しなければ、直接値を入力する
                if(!is_null($this->item_array)) {
                    //要素の存在確認 存在していなければ、配列に挿入する
                    foreach($this->item_array as $item) {
                        if($item[0] == $this->itemcd && $item[1] == $this->structcd && $item[2] == $this->stockcd) {
                            $res = false;
                            break;
                        }
                    }
                }
                if($res) {
                    $quantity = intval($this->quantity);
                    $quantity = (empty($quantity)) ? 1 : $quantity;
                    $this->item_array[] = array($this->itemcd, $this->structcd, $this->stockcd, $quantity);
                    sort($this->item_array);

                    $this->quantity = "";
                }
            // 削除
            } else if ($this->mode == 'delete') {
                if($this->item_array != NULL) {
                    $res = false;
                    $count = 0;
                    //要素の存在確認と、その順番を入手
                    //要素が存在すれば、その順番を元に配列から削除する
                    foreach($this->item_array as $item) {
                        if($item[0] == $this->itemcd && $item[1] == $this->structcd && $item[2] == $this->stockcd) {
                            $res = true;
                            break;
                        }
                        $count += 1;
                    }
                    if($res) {
                        array_splice($this->item_array, $count, 1);
                    }
                }
            }
            for($i=0; $i < count($this->item_array); $i++) {
                if (is_numeric($this->quantity[$i]) && $this->quantity[$i] > 0)
                    $this->item_array[$i][3] = $this->quantity[$i];
            }

            if (isset($this->mode) || isset($this->quantity)) {
                //セッション保存
                $this->session->setParameter('cart_items',$this->item_array);

                $scriptname = htmlspecialchars($_SERVER["SCRIPT_NAME"]
                                               , ENT_QUOTES);
                header('location:'.SSL_URL_ROOT.
                                   $scriptname.
                                   '?action=customer_itembuy_cart'. $sid);
                exit;
            }


            //カートの中のタイトルと価格取得
            $this->set_parameter();
        }

        return ($mobile) ? 'mobile_success' : 'success';
    }

    function getSum_quantity()
    {
        return $this->sum_quantity;
    }

    function output_cart()
    {
        return $this->item_array;
    }

    function set_parameter()
    {
        if($this->item_array != NULL)
        {
            $souryou = array();
            for($i=0; $i<count($this->item_array); $i++)
            {
//品名コード・構成コード・在庫コードを元にテーブルから商品名と価格を入手　Item_arrayに挿入
                $params = $this->c_cart->selectOne($this->item_array[$i][0], $this->item_array[$i][1], $this->item_array[$i][2]);
                if($params) {
                    $data = $this->dlitem->getDownloadItem($this->item_array[$i][0], $this->item_array[$i][1]);
                    if ($data===FALSE || is_null($data)) {
                        $this->item_array[$i][4] = $params['itemnm'] ." ". $params["variationnm"];
                        $this->item_array[$i][5] = intval($this->item_array[$i][3]) * intval($params['sellingprice']);
                        $this->item_array[$i][6] = $params['sellingprice'];
                        $this->item_array[$i][7] = $params['souryouprc'];
                        $this->item_array[$i][8] = $params['sellernm'];
                        $this->item_array[$i][9] = $params['itemexp'];
                    } elseif ($data["fileexistence"]==="t") {
                        $this->item_array[$i][4] = $params['itemnm'] ." ". $params["variationnm"];
                        $this->item_array[$i][5] = intval($this->item_array[$i][3]) * intval($params['sellingprice']);
                        $this->item_array[$i][6] = $params['sellingprice'];
                        $this->item_array[$i][7] = $params['souryouprc'];
                        $this->item_array[$i][8] = $params['sellernm'];
                        $this->item_array[$i][9] = $params['itemexp'];

                        $this->item_array[$i][10] = $data;
                        $this->dlflg = true;
                    }

                    // 小計
                    $this->sum_quantity += intval($this->item_array[$i][5]);
                    // 送料計
                    //$this->total_souryou += intval($this->item_array[$i][3]) * intval($params['souryouprc']);
                    if (empty($params["sellernm"]) && $params["reserveflg"]==0) { // 在庫
                        //$souryou["normal"] = SITE_SOURYOU;
                        $souryou["normal"] = 0;
                    } else if (empty($params["sellernm"]) && $params["reserveflg"]==1) { // 予約
                        //$souryou["reserve"] += SITE_SOURYOU;
                        $souryou["reserve"] += 0;
                    } else { // 出品
                        $souryou[$params["sellercd"]] = 0;
                    }
                }
            }
            $this->total_souryou = array_sum($souryou);
            // 合計
            $this->totalprice = intval($this->sum_quantity) + intval($this->total_souryou);
        }
    }
    function getBakurl() {
        $permit_action = array("general_portal", 
                               "general_itemview_itemlist",
                               "general_itemview_rsvitemlist",
                               "general_itemview_itemlist_itemsearch_list",
                               "itemdetail");

        $referer = $_SERVER["HTTP_REFERER"];

        if (!empty($this->backurl)) $referer = $this->backurl;//urldecode($this->backurl);
        if (empty($referer)) return;

        $this->backurl = "";
        $qs = "";
        $scriptname = htmlspecialchars($_SERVER["SCRIPT_NAME"], ENT_QUOTES);
        $dirname = dirname($_SERVER['SCRIPT_NAME']);
        $dirname = htmlspecialchars($dirname, ENT_QUOTES);
        $dirname = ($dirname=="/") ? "" : $dirname;

        $ptn = "@^(?:".SSL_URL_ROOT.$scriptname."|".
                       SSL_URL_ROOT.$dirname."/|".
                       URL_ROOT.$scriptname."|".
                       URL_ROOT.$dirname."/".
                  ")(\?[^\?]+)@i";
        $f = preg_match($ptn, $referer, $url);

        foreach ($permit_action as $val) {
            if (preg_match("/".$val."/i",$url[1],$match)) {
                $referer = urlencode($referer);
                $this->backurl = urldecode($referer);
                break;
            }
        }
        if ($f) return $this->backurl;

        // mod_rewrite用
        $ptn = "@^(?:".SSL_URL_ROOT.$scriptname."|".
                       SSL_URL_ROOT.$dirname."/|".
                       URL_ROOT.$scriptname."|".
                       URL_ROOT.$dirname."/".
                  ")(item_[0-9]+.html)@i";
        $f = preg_match($ptn, $referer, $url);

        if ($f) {
            $referer = urlencode($referer);
            $this->backurl = urldecode($referer);
        } else {
            $this->backurl = URL_ROOT.$scriptname;
        }

        return $this->backurl;
    }
}
?>
