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

/**
 * 商品検索
 *
 * @package     itemview
 * @author      netnee T.Ototgawa <tomokauzu.otogawa@netnee.jp>
 * @access      public
 */
class Onedepo_Logic_Itemview {

    var $item;
    var $tcast;
    var $genre;
    var $maker;
    var $label;
    var $series;
    var $image;
    var $name;
    var $struct;
    var $access;
    var $stock;
    var $tag;

    var $jancode;
    var $hinban;
    var $itemtitle;
    var $release_date_start;
    var $release_date_end;
    var $publish_date_start;
    var $publish_date_end;
    var $maker_capital;
    var $maker_name;
    var $media;
    var $cast;
    var $situation;
    var $photo_situation;
    var $publish_situation;

    var $genre_select;

    var $sort;
    var $cd;
    var $structcd;

    var $data;

    var $from;

    var $overcount;


    function getSearchResults($to,$genre_select,$resultmax=0,$export=false)
    {
        $where = array();
        $params = array();

        $log =& LogFactory::getLog();
        $log->debug("debug", "Onedepo_Logic_Itemview#getSearchResults");


        // AND検索の為に半角空白で分割
        $this->itemtitle = mb_convert_kana($this->itemtitle, "s", "UTF-8");
        $title = explode(" ", $this->itemtitle);
        $this->cast = mb_convert_kana($this->cast, "s", "UTF-8");
        $cast = explode(" ", $this->cast);

        // WHERE句で「=」を使うもの
        $eq = array("jancd"         => $this->jancode,
                    "basic.makercd" => $this->maker_name,
                    "mediacd"       => $this->media);
        $this->makeEqualParams($eq, $where, $params);
        //--

        // LIKEを使うもの
        $s = mb_convert_kana($this->hinban, "as", "UTF-8");
        $rep = array("‐","ー","―","－");
        $s = strtoupper(str_replace($rep, "-", $s));
        $like = array("makeritemcd" => $s,
                      "itemnm"      => $title);
        $this->makeLikeParams($like, $where, $params);
        //--

        // 日付
        $date = array("salestartdate" => array($this->release_date_start, $this->release_date_end),
                      "releasedate"   => array($this->publish_date_start, $this->publish_date_end));
        foreach ($date as $key => $val) {
            if (!empty($val)) {

                if (!empty($val[0])) {
                    $where[] = $key .">= ?";
                    $params[] = str_replace("/", "-", $val[0]);
                }
                if (!empty($val[1])) {
                    $where[] = $key ."<= ?";
                    $params[] = str_replace("/", "-", $val[1]);
                }

            }
        }

        if ($this->situation=="none") {
            $where[] = "web.updcnt IS NULL";
        }
        if ($this->situation=="none_sd") { // 発売日未設定
            $where[] = "salestartdate IS NULL";
        }
        if ($this->publish_situation=="none") {
            $where[] .= "(releasedate > ? OR releasedate IS NULL)";
            $params[] = date('Y-m-d');
        }
        if ($this->publish_situation=="is") {
            $where[] .= "releasedate <= ?";
            $params[] = date('Y-m-d');
        }


        $w = $p = array();
        // キャスト
        $cast_where = array();
        $cast_params = array();
        $cast = array("castnm" => $cast);
        $this->makeLikeParams($cast, $cast_where, $cast_params);
        //--

        if (!empty($cast_where)) {
            $qy = "(SELECT itemcd FROM t_cast_item castitem, t_cast tcast WHERE tcast.castdiv=1 AND tcast.delflg = FALSE AND castitem.delflg = FALSE AND tcast.castcd = castitem.castcd";

            foreach ($cast_where as $val) {
                $qy .= " AND $val";
            }
            $qy .= " GROUP BY itemcd)";
            $w[] = $qy;
            //$where[] = " basic.itemcd IN ". $qy;
            foreach ($cast_params as $val) {
                $p[] = $val;
            }
        }

        // ジャンル
        if (!empty($genre_select)) {
            //$where[] = " basic.itemcd IN (SELECT itemcd FROM t_genre_item WHERE genrecd in (!) GROUP BY itemcd) ";
            $w[] = "(SELECT itemcd FROM t_genre_item WHERE genrecd in (!) GROUP BY itemcd)";
            $p[] = implode(",", $genre_select);
        }

        if ($this->photo_situation=="is") { // 画像有
            //$where[] .= " basic.itemcd in (SELECT generalcd FROM t_image WHERE typediv = 1 AND delflg=FALSE GROUP BY generalcd)";
            $w[] = "(SELECT generalcd FROM t_image WHERE typediv = 1 AND delflg=FALSE GROUP BY generalcd)";
        }
        if (!empty($w)) {
            $where[] = " basic.itemcd IN (". implode(" INTERSECT ALL ", $w) .")";
            foreach ($p as $v) $params[] = $v;
        }
        if ($this->photo_situation=="none") { // 画像無
            $where[] .= " basic.itemcd not in (SELECT generalcd FROM t_image WHERE typediv = 1 AND delflg=FALSE GROUP BY generalcd)";
        }


        if ($this->photo_situation=="movie_is") { // 動画有
            $where[] .= " (basic.itemcd, struct.structcd) in
                           (SELECT generalcd, generalsubcd FROM t_image WHERE typediv = 4 AND delflg=FALSE GROUP BY generalcd,generalsubcd)";
        }
        if ($this->photo_situation=="movie_none") { // 動画無
            $where[] .= " (basic.itemcd, struct.structcd) not in
                           (SELECT generalcd, generalsubcd FROM t_image WHERE typediv = 4 AND delflg=FALSE GROUP BY generalcd,generalsubcd)";
        }


        if ($this->situation=="stk") { // 在庫有
            $where[] = " (basic.itemcd, struct.structcd) in
                    (SELECT t_s.itemcd, t_s.structcd
                       FROM t_ex_stock_detail t_s
                      left join
                       (select * from t_order_detail t_o
                         left join t_forward_detail t_f
                         on t_f.orderno=t_o.orderno
                         and t_f.orderrowno=t_o.orderrowno
                        where t_f.forwardstate is null
                        or not (t_f.forwardstate is not null
                        and (t_f.forwardstate=9
                        or (t_f.forwardstate=8 and t_f.returndate is not null)))
                       ) t_o
                      on t_o.itemcd = t_s.itemcd
                      AND t_o.structcd = t_s.structcd
                      and t_s.stockcd = t_o.stockcd
                     WHERE t_o.itemcd IS NULL
                     AND   t_s.stockstate = 3
                     AND   t_s.exhibitcount > 0
                     AND   t_s.sellercd IS NULL
                     AND   t_s.delflg = false
                    GROUP BY t_s.itemcd, t_s.structcd)";
        }
        if ($this->situation=="nostk") { // 在庫無
            $where[] = " (basic.itemcd, struct.structcd) not in
                    (SELECT t_s.itemcd, t_s.structcd
                       FROM t_ex_stock_detail t_s
                      left join
                       (select * from t_order_detail t_o
                         left join t_forward_detail t_f
                         on t_f.orderno=t_o.orderno
                         and t_f.orderrowno=t_o.orderrowno
                        where t_f.forwardstate is null
                        or not (t_f.forwardstate is not null
                        and (t_f.forwardstate=9
                        or (t_f.forwardstate=8 and t_f.returndate is not null)))
                       ) t_o
                      on t_o.itemcd = t_s.itemcd
                      AND t_o.structcd = t_s.structcd
                      and t_s.stockcd = t_o.stockcd
                     WHERE t_o.itemcd IS NULL
                     AND   t_s.stockstate = 3
                     AND   t_s.exhibitcount > 0
                     AND   t_s.sellercd IS NULL
                     AND   t_s.delflg = false
                    GROUP BY t_s.itemcd, t_s.structcd)";
        }


        if ($this->sort == "title")         $sortkey = "basic.itemnm, struct.variationnm";
        else if ($this->sort == "release")  $sortkey = "struct.salestartdate desc";
        else                                $sortkey = "struct.makeritemcd";


        if (!is_numeric($this->from)) {
        $this->from = 1;
        }
        $from = ($this->from-1)*$to;

        $c = $this->item->getSearchResultsCount($where, $params);
        if ($resultmax>0 && $c > $resultmax) {
            $this->overcount=$c;
            return false;
        }

        if (!$export) { // 商品検索
            $this->data = $this->item->getSearchResults($where,
                                                        $params,
                                                        $sortkey,
                                                        $to,
                                                        $from);
        } else {        // データ出力
            $this->data = $this->item->getSearchResultsExport($where,
                                                              $params,
                                                              $sortkey,
                                                              $to,
                                                              $from);
        }
        return $this->data;
    }
    function getImagecount($itemcd) {
        return $this->item->getImagecount($itemcd);
    }
    function getStockcount($itemcd, $structcd) {
        return $this->item->getStockcount($itemcd, $structcd);
    }
    function getStockcount2($itemcd, $structcd) {
        return $this->item->getStockcount2($itemcd, $structcd);
    }
   function getStockStyle($itemcd, $structcd) {
        return $this->item->getStockStyle($itemcd, $structcd);
    }

    function getNewitemList($sort, $to, $from, $q="", $parameters=array(), $tag="", $q_select="", $maxcount=1000)
    {
        $log =& LogFactory::getLog();
        $func_name = "Onedepo_Logic_Itemview#getNewitemList";
        $log->debug("Onedepo_Logic_Itemviewが実行されました", $func_name);

        $where = array();
        $params = array();
        $itemcd = array();
        $join = $g_join = $c_join = $m_join = $dc_w = "";

        $i = 0;

        // 詳細検索用
        // タイトル
        if ( strlen($parameters['itemnm'])>0 ) {
            $where[$i][] = 'basic.itemnm LIKE ? ';
            $params[] = "%". $parameters['itemnm'] ."%";
            $i++;
        }
        // 商品説明
        if ( strlen($parameters['itemexp'])>0 ) {
            $where[$i][] = 'basic.itemexp LIKE ? ';
            $params[] = "%". $parameters['itemexp'] ."%";
            $i++;
        }
        // メーカー品番
        if ( strlen($parameters['makeritemcd'])>0 ) {
            // 全角半角大文字小文字を"全角大文字"で統一
            $s = mb_convert_kana($parameters["makeritemcd"], "as", "UTF-8");
            $rep = array("‐","ー","―","－");
            $s = strtoupper(str_replace($rep, "-", $s));

            $w  = 'basic.itemcd IN ';
            $w .= ' (SELECT DISTINCT itemcd FROM t_item_struct WHERE ';
            $w .= 'makeritemcd LIKE ?) ';
            $where[$i][] = $w;
            $params[] = '%'. $s .'%';
            $i++;
        }
        // JANコード
        if ( !empty($parameters['jancd']) ) {
            $where[$i][] .= 'basic.itemcd IN (SELECT DISTINCT itemcd FROM t_item_struct WHERE jancd=?) ';
            $params[] = $parameters['jancd'];
            $i++;
        }
        // 詳細検索用ここまで


        // 選択されたタグ
        if ($tag != "") {
            $c = $this->tag->getItemcdForTagnm($tag);
            $c = implode(",", $c);
            $where[$i][] = "basic.itemcd in (!)";
            $params[] = $c;
            $i++;
        } else if ($q != "") {
            // AND検索の為に半角空白で分割
            $q = mb_convert_kana($q, "s", "UTF-8");
            $q_arr = explode(" ", trim($q));
            //--

            $union = array();
            if ($q_select == "all" || $q_select == "tag") {
                // タグ
                $tag = array("tagnm" => $q_arr);
                //$this->makeLikeParams($tag, $tag_where, $tag_params);
                $this->makeLikeParams($tag, $tag_where, $params);
                //--

                if (!empty($tag_where)) {
                   $u = "(SELECT t.itemcd 
                           FROM t_tag t, t_member_basic_attr m 
                           WHERE t.delflg=FALSE
                           AND t.usercd = m.membercd
                           AND m.memberstate = 1 ";
                    foreach ($tag_where as $val) {
                        $u .= " AND $val";
                    }
                    $u .= ")";
                    $union[] = $u;
                }
            }
            if (!empty($union)) {
                $qry .= " basic.itemcd IN ( ". implode(" UNION ALL ", $union) .")";
                if ($q_select=="all") $qry.=" OR ";
            }

            if ($q_select == "all" || $q_select == "jan") {
                // JANコード
                $jan = array("jancd" => $q_arr);
                $this->makeEqualParams($jan, $jan_where, $jan_params);
                //--

                if (!empty($jan_where)) {
                    $cd = array();
                    $cd = $this->item->getItemcdForJancd($jan_where, $jan_params);
                    if (!empty($cd)) $itemcd[] = $cd;
                }
            }
            if (!empty($itemcd)) {
                $merge = $itemcd[0]; // 基準
                if (count($itemcd) > 1) { // ヒットしたコードのみ
                    foreach ($itemcd as $val) {
                        $merge = array_merge($merge, $val);
                    }
                }
                $merge = array_unique($merge);
                $merge = implode(",", $merge);

                if (!empty($merge)) {
                    $qry .= "basic.itemcd in (!) ";
                    if ($q_select == "all") $qry .="OR ";
                    $params[] = $merge;
                }
            }
            $itemcd = array();

            // LIKEを使うもの
/*
            $like = array("itemnmkana"  => $q_arr,
                          "subtitle"    => $q_arr,
                          "iteminfo"    => $q_arr,
                          "comment"     => $q_arr);
*/
            $like = array();
            switch ($q_select) {
            case "all":
                $like["itemnm"]   = $q_arr;
                //$like["iteminfo"]   = $q_arr;
                //$like["maker.makernm"]  = $q_arr;
            break;
            case "title":
                $like["itemnm"]   = $q_arr;
            break;
	    /*
            case "iteminfo":
                $like["iteminfo"]   = $q_arr;
            break;
            case "maker":
                $like["maker.makernm"]  = $q_arr;
            break;
	    */
            }

            $j = 0;
            foreach ($like as $key => $val) {
                if ($j++ > 0) $qry .= " OR ";

                if(!empty($val)) {
                    if (is_array($val)) {
                        foreach ($val as $k => $v) {
                            if (!empty($v)) {
                                if ($k > 0) $qry .= " AND ";
                                $qry .= $key ." LIKE ?";
                                $params[] = '%'. $v .'%';
                            }
                        }
                    } else {
                        $qry .=  $key ." LIKE ?";
                        $params[] = '%'. $val .'%';
                    }
                }
            }
            if (!empty($qry)) {
                $where[$i][] = "(".$qry.")";
                $i++;
            } else { // ヒットした商品が無し
                $where[$i][] = "(basic.itemcd IS NULL)";
                $i++;
            }
        }

        /**
         * 絞り込み
         *
         */
        if (!empty($parameters)) {

          // メーカー
          if (!empty($parameters["maker"])) {
              $where[$i][] = " basic.makercd = ?";
              $params[] = $parameters["maker"];
          }
          //--

          // ジャンル
          if (!empty($parameters["genre"])) {
              // 単一選択
              if (is_numeric($parameters["genre"][0])) {
                  $g = $this->genre->selectGenreRelationship();
                  $tree = array();
                  $this->genre->makeTree($g, "", $tree, false);
                  $this->getGenreUnderGenre($tree, $parameters["genre"][0], $ret, false);

                  $imp = implode(",", $ret);
                  $g_join .= " INNER JOIN (SELECT itemcd FROM t_genre_item WHERE genrecd IN (".$imp.") GROUP BY itemcd ) gi ON gi.itemcd=basic.itemcd ";
              }
          }
          //--

          // 種別
          $qy1 = $qy2 = $qy3 = $qy4 = "";

          if ($parameters["etc"]["saledate"]=="after") {        // 発売後
              $where[$i][] = "min_salestartdate <= CURRENT_DATE";
          } elseif ($parameters["etc"]["saledate"]=="before") { // 発売前
              $where[$i][] = "min_salestartdate > CURRENT_DATE";
          }
          if (is_array($w1)) {
              $qy1 = " (SELECT itemcd FROM t_item_struct WHERE ". implode(" AND ",$w1) ." AND delflg = FALSE GROUP BY itemcd)";
          }
          //--

          if ($parameters["etc"]["type"]=="new") {        // 新品
              $where[$i][] = " basic.newlowprice >= 0";
              $dc_w = " AND basic.newlowprice >= 0";
          } elseif ($parameters["etc"]["type"]=="used") { // 中古
              $where[$i][] = " basic.oldlowprice > 0";
              $dc_w = " AND basic.oldlowprice > 0";
          }
          //--

          if ($parameters["etc"]["stock"]=="stk") {          // 在庫有
              if ($parameters["etc"]["type"]=="new") {        // 新品
                  $where[$i][] = " basic.newlowprice >= 0";
              } elseif ($parameters["etc"]["type"]=="used") { // 中古
                  $where[$i][] = " basic.oldlowprice > 0";
              } else {
                  $where[$i][] = " basic.lowprice >= 0";
                  $dc_w = " AND basic.lowprice >= 0";
              }
	    //$qy3 = " (select itemcd from v_item_basic_term where stockstate=3 group by itemcd having sum(exhibitcount)>0)";
          } elseif ($parameters["etc"]["stock"]== "nstk") {  // 在庫無
              if ($parameters["etc"]["type"]=="new") {        // 新品
                  $where[$i][] = " basic.newlowprice IS NULL";
              } elseif ($parameters["etc"]["type"]=="used") { // 中古
                  $where[$i][] = " basic.oldlowprice IS NULL";
              } else {
                  $where[$i][] = " basic.lowprice IS NULL";
              }
	    //$qy3 = " (select itemcd from v_item_basic_term group by itemcd having sum(exhibitcount)<=0)";
          } elseif ($parameters["etc"]["stock"]=="rsv") {    // 予約中
              $qy3 = " (SELECT itemcd FROM v_stock_list WHERE reserveflg=1 GROUP BY itemcd)";
          }
          //--

          $re = array();
          if (!empty($qy1)) $re[] = $qy1;
          if (!empty($qy2)) $re[] = $qy2;
          if (!empty($qy3)) $re[] = $qy3;
          if (!empty($re)) {
              $r = implode(" intersect ", $re);
              $where[$i][] = " basic.itemcd in (". $r .")";
          }
          $log->debug("where ".$r, "v_item_basic_list");
        }
        /**
         */

        if (!empty($itemcd)) {
            $intersect = $itemcd[0]; // 基準
            if (count($itemcd) > 1) { // 重複するコードのみ
                foreach ($itemcd as $val) {
                    $intersect = array_intersect($intersect, $val);
                }
            }

            $intersect = implode(",", $intersect);

            if (!empty($intersect)) {
                $where[$i][] = "basic.itemcd in (!)";
                $params[] = $intersect;
            } else {
                return array();
            }
            $i++;
        }


        $sortkey = "basic.stock_upddate desc";
        if ($sort=="-udate") {
            $sortkey = "basic.stock_upddate desc";
        } else if ($sort=="udate") {
            $sortkey = "basic.stock_upddate";
        } else if ($sort=="-title") {
            $sortkey = "basic.itemnm desc";
        } else if ($sort=="title") {
            $sortkey = "basic.itemnm";
        } else if ($sort=="-saledate") {
            $sortkey = "basic.min_salestartdate desc";
        } else if ($sort=="saledate") {
            $sortkey = "basic.min_salestartdate";
        } else if ($sort=="-price") {
            if ($parameters["etc"]["type"]=="new") {        // 新品
                $sortkey = "basic.newlowprice desc";
            } else if ($parameters["etc"]["type"]=="used") {// 中古
                $sortkey = "basic.oldlowprice desc";
            } else {                                        // 全て
                $sortkey = "basic.lowprice desc";
            }
        } else if ($sort=="price") {
            if ($parameters["etc"]["type"]=="new") {        // 新品
                $sortkey = "basic.newlowprice";
            } else if ($parameters["etc"]["type"]=="used") {// 中古
                $sortkey = "basic.oldlowprice";
            } else {                                        // 全て
                $sortkey = "basic.lowprice";
            }
        } 


        /*
        // 新着商品
        if (    (empty($parameters["cast"]))        // それぞれの条件がない時
            AND (empty($parameters["maker"]))
            //AND (empty($parameters["genre"]))
            AND (empty($parameters["label"]))
            AND (empty($parameters["series"]))
            AND (empty($parameters["itemcd"]))
            AND ($q == "")
           ) {
            $tc = $this->item->getTotalDataCount();
            if (!($parameters["etc"]["type"]=="new" && $tc["alltitlenum_new"] < $maxcount)) {
                $c = $this->item->getDataCount($maxcount, $g_join.$m_join, $dc_w);
                if ($c>0) {
                    $where[$i][] = " basic.stock_upddate > CURRENT_DATE-!";
                    $params[] = $c;
                    $i++;
                }
            }
        }
        */
        //--

        $this->data = $this->item->getNewitemList($to,
                                                  $from,
                                                  $where,
                                                  $params,
                                                  $sortkey,
                                                  $join,
                                                  $g_join.$c_join);

        return $this->data;
    }

    function getNewListPortal($to, $from, $parameters=array(),$maxcount=50)
    {
        $log =& LogFactory::getLog();
        $func_name = "Onedepo_Logic_Itemview#getNewListPortal";

        $where = array();
        $params = array();
        $itemcd = array();

        $i = 0;

        /**
         * 絞り込み
         *
         */
        if (!empty($parameters)) {

          if ($parameters["etc"]["saledate"]=="after") {        // 発売後
              $where[$i][] = "min_salestartdate <= CURRENT_DATE";
          } elseif ($parameters["etc"]["saledate"]=="before") { // 発売前
              $where[$i][] = "min_salestartdate > CURRENT_DATE";
          }
          //--

          if ($parameters["etc"]["type"]=="new") {        // 新品
              $where[$i][] = " basic.newlowprice >= 0";
          } elseif ($parameters["etc"]["type"]=="used") { // 中古
              $where[$i][] = " basic.oldlowprice > 0";
          }
          //--

          if ($parameters["etc"]["stock"]=="stk") {          // 在庫有
              if ($parameters["etc"]["type"]=="new") {        // 新品
                  $where[$i][] = " basic.newlowprice >= 0";
              } elseif ($parameters["etc"]["type"]=="used") { // 中古
                  $where[$i][] = " basic.oldlowprice > 0";
              } else {
                  $where[$i][] = " basic.lowprice >= 0";
              }
          } elseif ($parameters["etc"]["stock"]== "nstk") {  // 在庫無
              if ($parameters["etc"]["type"]=="new") {        // 新品
                  $where[$i][] = " basic.newlowprice IS NULL";
              } elseif ($parameters["etc"]["type"]=="used") { // 中古
                  $where[$i][] = " basic.oldlowprice IS NULL";
              } else {
                  $where[$i][] = " basic.lowprice IS NULL";
              }
          } elseif ($parameters["etc"]["stock"]=="rsv") {    // 予約中
              $qy3 = " (SELECT itemcd FROM v_stock_list WHERE reserveflg=1 GROUP BY itemcd)";
          }
          //--

          if (!empty($parameters["etc"]["salestartdate_start"]) &&
              !empty($parameters["etc"]["salestartdate_end"])) {
              $where[$i][] = "min_salestartdate >= CURRENT_DATE-!";
              $where[$i][] = "min_salestartdate <= CURRENT_DATE+!";
              $params[] = $parameters["etc"]["salestartdate_start"];
              $params[] = $parameters["etc"]["salestartdate_end"];
          }


          $re = array();
          if (!empty($qy3)) $re[] = $qy3;
          if (!empty($re)) {
              $r = implode(" intersect ", $re);
              $where[$i][] = " basic.itemcd in (". $r .")";
          }
        }
        /**
         */

        $sortkey = "COALESCE(basic.stock_upddate, '1900-01-01') desc, 
                    basic.itemnm";

        $this->data = $this->item->getNewListPortal($to,
                                                    $from,
                                                    $where,
                                                    $params,
                                                    $sortkey,
                                                    "",
                                                    "");

        return $this->data;
    }


    function getNewitemList4exhibit($sort, $to, $from, $q="", $parameters=array())
    {
        $log =& LogFactory::getLog();
        $func_name = "Onedepo_Logic_Itemview#getNewitemList4exhibit";
        $log->debug("Onedepo_Logic_Itemviewが実行されました", $func_name);

        $where = array();
        $params = array();
        $itemcd = array();

        $log =& LogFactory::getLog();
        $log->debug("debug", $func_name);

        $i = 0;

        // 条件選択
        if ($q != "") {
            // AND検索の為に半角空白で分割
            $q = mb_convert_kana($q, "s", "UTF-8");
            $q_arr = explode(" ", $q);
            //--

            $itemcd = array();

            // LIKEを使う
            $like = array();
            $like["basic.itemnm"]   = $q_arr;

            $j = 0;
            foreach ($like as $key => $val) {
                if ($j++ > 0) $qry .= " OR ";

                if(!empty($val)) {
                    if (is_array($val)) {
                        foreach ($val as $k => $v) {
                            if (!empty($v)) {
                                if ($k > 0) $qry .= " AND ";
                                $qry .= $key ." LIKE ?";
                                $params[] = '%'. $v .'%';
                            }
                        }
                    } else {
                        $qry .=  $key ." LIKE ?";
                        $params[] = '%'. $val .'%';
                    }
                }
            }
            if (!empty($qry)) {
                $where[$i][] = "(".$qry.")";
                $i++;
            } else { // ヒットした商品が無し
                $where[$i][] = "(basic.itemcd IS NULL)";
                $i++;
            }
        }

        /**
         * 絞り込み
         **/
        if (!empty($parameters)) {

            // メーカー品番
            if (!empty($parameters["makeritemcd"])) {
                $where[$i][] = " struct.makeritemcd = ?";
                $s = mb_convert_kana($parameters["makeritemcd"], "as", "UTF-8");
                $rep = array("‐","ー","―","－");
                $s = strtoupper(str_replace($rep, "-", $s));
                $params[] = $s;
            }
            //--

            // JANコード
            if (!empty($parameters["jancd"])) {
                $where[$i][] = " struct.jancd = ?";
                $params[] = $parameters["jancd"];
            }
            //--

            if (!empty($qy1)) $where[$i][] = $qy1;
        }

        $sortkey = "basic.itemnm";

        $this->data = $this->item->getNewitemList4Exhibit($to,
                                                          $from,
                                                          $where,
                                                          $params,
                                                          $sortkey);

        return $this->data;
    }

    function getOneItem($shopdiv=null)
    {
        $where = "";
        if (!empty($shopdiv)) $where = " AND shopdiv = ". $shopdiv;

        $this->data = $this->item->getOneItem($this->cd, $where);
        return $this->data;
    }

    function getOneItemRow($shopdiv=null)
    {
        $where = "";
        if (!empty($shopdiv)) $where = " AND shopdiv = ". $shopdiv;

        $this->data = $this->item->getOneItemRow($this->cd, $where);
        return $this->data;
    }
    function getOneItemRow2($itemcd)
    {
        $this->data = $this->item->getOneItemRow($itemcd);
        return $this->data;
    }

    function getOneItem4ExhibitRow($itemcd, $structcd)
    {
        $log =& LogFactory::getLog();
        $func_name = "Onedepo_Logic_Itemview#getOneItem4ExhibitRow";
        $log->debug("#itemcd=".$itemcd."#structcd=".$structcd, $func_name);

        $this->data = $this->item->getOneItem4ExhibitRow($itemcd, $structcd);
        return $this->data;
    }

    function getOneItemForUsersite()
    {
        $where = " AND releasedate <= CURRENT_DATE";
        $this->data = $this->item->getOneItem($this->cd, $where);
        return $this->data;
    }

    function getOneStruct()
    {
        $this->data = $this->struct->getOneItem($this->cd, $this->structcd);
        return $this->data;
    }

    function getOneItemOneStruct()
    {
        $this->data = $this->struct->getOneItemOneStruct($this->cd, $this->structcd);
        return $this->data;
    }


    /**
     * = を使用するクエリ
     *
     */
    function makeEqualParams($basearr, &$where, &$params)
    {
        foreach ($basearr as $key => $val) {
            if(!empty($val)) {
                if (is_array($val)) {

                    foreach ($val as $v) {
                        $where[] = $key ." = ?";
                        $params[] = $v;
                    }

                } else {
                    $where[] = $key ." = ?";
                    $params[] = $val;
                }
            }
        }
    }

    /**
     * LIKE 部分一致
     *
     */
    function makeLikeParams($basearr, &$where, &$params)
    {
        foreach ($basearr as $key => $val) {
            if(!empty($val)) {
                if (is_array($val)) {

                    foreach ($val as $v) {
                        if (!empty($v)) {
                            $where[] = $key ." LIKE ?";
                            $params[] = '%'. $v .'%';
                        }
                    }

                } else {
                    $where[] = $key ." LIKE ?";
                    $params[] = '%'. $val .'%';
                }
            }
        }
    }

    function getCastnmForItemcd()
    {
        $where = array();
        $params = array();
        $cd = "";

        $log =& LogFactory::getLog();
        $log->debug("debug", "Onedepo_Logic_Itemview#getCastnmForItemcd");

        $itemcd = array();
        foreach ($this->data as $key => $val)
        {
            if (!empty($val["itemcd"]))
                $itemcd[] = $val["itemcd"];
        }
        $cd = implode(",", $itemcd);

        //$log->debug($cd, "Onedepo_Logic_Itemview#getCastnmForItemcd");
        if (empty($cd)) return;

        $list = $this->tcast->getCastnmForItemcd($cd);

        $castnm = array();
        foreach ($list as $key => $val)
        {
            $castnm[$key] = implode(" ", $val);
        }
        return $castnm;
    }

    function getCastListForItemcd()
    {
        $where = array();
        $params = array();
        $cd = "";

        $log =& LogFactory::getLog();
        $log->debug("debug", "Onedepo_Logic_Itemview#getCastListForItemcd");

        $itemcd = array();
        foreach ($this->data as $key => $val)
        {
            if (!empty($val["itemcd"]))
                $itemcd[] = $val["itemcd"];
        }
        $cd = implode(",", $itemcd);

        //$log->debug(print_r($this->data, true), "Onedepo_Logic_Itemview#getCastListForItemcd");
        if (empty($cd)) return;

        $list = $this->tcast->getCastListForItemcd($cd);

        $cast = array();
        foreach ($list as $key => $val)
        {
            $cast[$key] = $val;
        }
        return $cast;
    }

    function getCastForItemcd($itemcd, $shopdiv=null)
    {
        $log =& LogFactory::getLog();
        $log->debug("debug: itemcd=".$itemcd, "Onedepo_Logic_Itemview#getCastForItemcd");

        return $this->tcast->getCastForItemcd($itemcd, $shopdiv);
    }

    function getCastListWomen()
    {
        $where = array();
        $params = array();
        $cd = "";

        $itemcd = array();
        foreach ($this->data as $key => $val)
        {
            if (!empty($val["itemcd"]))
                $itemcd[] = $val["itemcd"];
        }
        $cd = implode(",", $itemcd);

        if (empty($cd)) return;

        $list = $this->tcast->getCastListWomen($cd);

        $cast = array();
        foreach ($list as $key => $val)
        {
            $cast[$key] = $val;
        }
        return $cast;
    }

    function getCastWomen($itemcd)
    {
        $log =& LogFactory::getLog();
        $log->debug("debug", "Onedepo_Logic_Itemview#getCastWomen");

        $list = $this->tcast->getCastWomen($itemcd);
        $cast = array();
        foreach ($list as $key => $val)
        {
            $cast[$key] = $val;
        }
        return $cast;
    }
    function getCastDirec($itemcd)
    {
        $log =& LogFactory::getLog();
        $log->debug("debug", "Onedepo_Logic_Itemview#getCastDirec");

        $list = $this->tcast->getCastDirec($itemcd);
        $cast = array();
        foreach ($list as $key => $val)
        {
            $cast[$key] = $val;
        }
        return $cast;
    }

    function getGenrenmForItemcd()
    {
        $where = array();
        $params = array();
        $cd = "";

        $log =& LogFactory::getLog();
        $log->debug("debug", "Onedepo_Logic_Itemview#getGenrenmForItemcd");

        $itemcd = array();
        foreach ($this->data as $key => $val)
        {
            if (!empty($val["itemcd"]))
                $itemcd[] = $val["itemcd"];
        }
        $cd = implode(",", $itemcd);

        //$log->debug($cd, "Onedepo_Logic_Itemview#getGenrenmForItemcd");
        if (empty($cd)) return;

        $list = $this->genre->getGenrenmForItemcd($cd);

        $genrenm = array();
        foreach ($list as $key => $val)
        {
            $genrenm[$key] = implode(" ", $val);
        }
        return $genrenm;
    }

    function getGenreForItemcd()
    {
        $where = array();
        $params = array();
        $cd = "";

        $log =& LogFactory::getLog();
        $log->debug("debug", "Onedepo_Logic_Itemview#getGenreForItemcd");

        $itemcd = array();
        foreach ($this->data as $key => $val)
        {
            if (!empty($val["itemcd"]))
                $itemcd[] = $val["itemcd"];
        }
        $cd = implode(",", $itemcd);

        //$log->debug($cd, "Onedepo_Logic_Itemview#getGenrenmForItemcd");
        if (empty($cd)) return;

        $list = $this->genre->getGenreForItemcd($cd);

        $genre = array();
        foreach ($list as $key => $val)
        {
            $genre[$key] = $val;
        }
        return $genre;
    }
    function getGenrecdForItemcd($cd)
    {
        if (empty($cd)) return;
        return $this->genre->getGenrecdForItemcd($cd);
    }
    function getGenreTreeAll () {
        $log =& LogFactory::getLog();
        $log->debug("debug", "Onedepo_Logic_Itemview#getGenreTree");

        $g = $this->genre->selectGenreRelationship();

        $c = "";
        $tree = array();
        $this->genre->makeTree($g, $c, $tree, false);
        return $tree;
    }

    function getGenreTree ($cd="") {
        $log =& LogFactory::getLog();
        $log->debug("debug", "Onedepo_Logic_Itemview#getGenreTree");

        $g = $this->genre->selectGenreRelationship();

        $c = "";
        $tree = array();
        $this->genre->makeTree($g, $c, $tree, false);

        $ret="";
        if (!empty($cd)) {
            foreach ($cd as $c) {
                $this->getGenreEqualGenrecd ($tree, $c, NULL, $ret);
            }
        }

        return $ret;
    }
    function getGenreEqualGenrecd ($genre, $genrecd, $tmp=NULL, &$ret = NULL) {
        foreach ($genre as $key => $val) {
            $c = $val["genrecd"];
            $tmp[] = array("genrecd"=>$val["genrecd"], "genrenm"=>$val["genrenm"]);
            if ($c==$genrecd) {
                $ret[] = $tmp;
                return false;
            }
            // 下の階層をチェック
            $destroy = $this->getGenreEqualGenrecd ($val["child"], $genrecd, $tmp, $ret);
            array_pop($tmp);
        }
    }
    /* 指定したジャンルより下の階層のジャンルを取得 */
    function getGenreUnderGenre ($genre, $genrecd, &$ret = NULL, $f=false) {
        $place = false;
        foreach ($genre as $key => $val) {
            if ($place) $f = false;
            if ($val["genrecd"]==$genrecd) $f = $place = true;
            if ($f) {
                $ret[] = $val["genrecd"];
            }
            // 下の階層をチェック
            $r = $this->getGenreUnderGenre ($val["child"], $genrecd, $ret, $f);
        }
    }

    function getSellingpriceForDetail($cd)
    {
        $list = $this->item->getSellingpriceForItemcd($cd);

        $price = 0;
        foreach ($list as $key => $val) $price = $val[0];
        return $price;
    }
    function getLowprice($cd)
    {
        $list = $this->item->getLowprice($cd);

        $price = 0;
        foreach ($list as $key => $val) $price = $val[0];
        return $price;
    }

    function getMediaForItemcd($media)
    {
        $cd = "";

        $itemcd = array();
        foreach ($this->data as $key => $val) {
            if (!empty($val["itemcd"]))
                $itemcd[] = $val["itemcd"];
        }
        $cd = implode(",", $itemcd);

        if (empty($cd)) return;

        $list = $this->item->getMediaForItemcd($cd, $media);

        $struct = array();
        foreach ($list as $key => $val) $struct[$key] = $val;

        return $struct;
    }
    function getSellingpriceForItemcd($c="")
    {
        $cd = "";
        $condition = "";
        if ($c==1) { // 新品
            $condition = "AND condition=1";
        } elseif ($c==2) { // 中古
            $condition = "AND condition>=2";
        }

        $itemcd = array();
        foreach ($this->data as $key => $val) {
            if (!empty($val["itemcd"]))
                $itemcd[] = $val["itemcd"];
        }
        $cd = implode(",", $itemcd);

        if (empty($cd)) return;

        $list = $this->item->getSellingpriceForItemcd($cd, $condition);

        $stocklist = array();
        foreach ($list as $key => $val) $stocklist[$key] = $val;
        return $stocklist;
    }
    function getCd($c=NULL,$p=NULL)
    {
        return $this->item->getCartCd($c,$p);
    }
    function getCd2($c=NULL,$p=NULL)
    {
        return $this->item->getCartCdWithDateCheck($c,$p);
    }
    function getTotalDataCount() { 
        return $this->item->getTotalDataCount();
    }
    function getExhibitcountForItemcd()
    {
        $cd = "";

        $itemcd = array();
        foreach ($this->data as $key => $val) {
            if (!empty($val["itemcd"]))
                $itemcd[] = $val["itemcd"];
        }
        $cd = implode(",", $itemcd);

        if (empty($cd)) return;

        $list = $this->item->getExhibitcountForItemcd($cd);

        $stocklist = array();
        foreach ($list as $key => $val) $stocklist[$key] = $val;
        return $stocklist;
    }
    function getReserveflgForItemcd()
    {
        $cd = "";

        $itemcd = array();
        foreach ($this->data as $key => $val) {
            if (!empty($val["itemcd"]))
                $itemcd[] = $val["itemcd"];
        }
        $cd = implode(",", $itemcd);

        if (empty($cd)) return;

        $list = $this->item->getReserveflgForItemcd($cd);

        $stocklist = array();
        foreach ($list as $key => $val) $stocklist[$key] = $val;
        return $stocklist;
    }


    function getItemImageForItemcd()
    {
        $where = array();
        $params = array();
        $cd = "";

        $log =& LogFactory::getLog();
        $log->debug("debug", "Onedepo_Logic_Itemview#getImageForItemcd");

        $itemcd = array();
        foreach ($this->data as $key => $val)
        {
            if (!empty($val["itemcd"]))
                $list[$val["itemcd"]] = array("S","M","L");
        }
        //$cd = implode(",", $itemcd);

        //$log->debug($cd, "Onedepo_Logic_Itemview#getImageForItemcd");
        //if (empty($cd)) return;

        //$list = $this->image->getItemImageForItemcd($cd);

        $imagenm = array();
        foreach ($list as $key => $val) {
            foreach ($val as $imgsize) {
                if (is_file(IMAGE_DIR ."/1/". $key . $imgsize . ".jpg"))
                    $imagenm[$key][$imgsize] = "img.php?c=". $key ."&s=". $imgsize ."&d=1";
            }
        }
        return $imagenm;
    }

    function getLastUpdDate($cd)
    {
        return $this->stock->getLastUpdDate($cd);
    }
    function getStockForItemcd($view="")
    {
        switch ($view) {
        case 'new':
        $where = " AND condition = 1";
        break;
        case 'used':
        $where = " AND condition >= 2";
        break;
        default:
        $where = "";
        break;
        }
        $data = $this->stock->getStockSelectForItemcd($this->cd, $where);
        return $data;
    }
    function getStockDetail($itemcd, $structcd, $view)
    {
        switch ($view) {
        case 'onedepo':
        $where = " AND (sellercd = 9999 OR sellercd IS NULL) ";
        break;
        case 'seller':
        $where = " AND (sellercd IS NOT NULL AND sellernm IS NOT NULL AND memberstate=1) ";
        break;
        }
        $data = $this->stock->getStockDetail($itemcd, $structcd, $where);
        return $data;
    }

    function getStructData($itemcd, $structcd)
    {
        $this->data = $this->struct->getOneItem($itemcd, $structcd);
        return $this->data[0];
    }

    function getStockSellData($itemcd, $structcd)
    {
        $d = $this->stock->getStockSellData($itemcd, $structcd);
        return $d;
    }

    // アクセス数インクリメント
    function incrementAccessCount($user)
    {
        $log =& LogFactory::getLog();
        $log->debug("debug", "Onedepo_Logic_Itemview#incrementAccessCount");

        $this->access->AccessIncrement($this->cd, date("Y-m-d"), $user);

        RETURN TRUE;
    }


    /*
    * アイテム・女優のランキングを取得
    *
    */
    function getRankingListData(){
        $log =& LogFactory::getLog();
        $log->debug("debug", "Onedepo_Logic_Itemview#getRankingData");

        $rankdata = array();

        // アイテムランキング
        $rankdata["item"] = $this->item->getItemRanking();
        // 女優ランキング
        $rankdata["actress"] = $this->tcast->getCastRanking(1); // キャスト種別１

        return $rankdata;
    }


    /**
     * 絞り込み用
     **/
    function getSearchCast($castcd)
    {
        if (empty($castcd)) return "";

        $log =& LogFactory::getLog();
        $log->debug("debug", "Onedepo_Logic_Itemview#getSearchCast");

        $cast = $this->tcast->selectKey($castcd);

        return $cast;
    }

    function getSearchMaker($makercd)
    {
        if (empty($makercd)) return "";

        $log =& LogFactory::getLog();
        $log->debug("debug", "Onedepo_Logic_Itemview#getSearchMaker");

        $maker = $this->maker->selectKey($makercd);

        return $maker["makernm"];
    }

    function getSearchLabel($makercd, $labelcd)
    {
        if (empty($makercd) || empty($labelcd)) return array();

        $log =& LogFactory::getLog();
        $log->debug("debug", "Onedepo_Logic_Itemview#getSearchLabel");

        $label = $this->label->getLabelnmList($makercd, $labelcd);

        return $label;
    }

    function getSearchSeries($makercd, $seriescd)
    {
        if (empty($makercd) || empty($seriescd)) return "";

        $log =& LogFactory::getLog();
        $log->debug("debug", "Onedepo_Logic_Itemview#getSearchSeries");

        $series = $this->series->selectKey($makercd, $seriescd);

        return $series["seriesnm"];
    }

    function getSearchGenre($genrecd)
    {
        if (empty($genrecd)) return array();

        $log =& LogFactory::getLog();
        $log->debug("debug", "Onedepo_Logic_Itemview#getSearchGenre");

        $genre = $this->genre->getGenrenmList($genrecd);

        return $genre;
    }

    function getGenreImage($genrecd="", $size="L")
    {
        if (empty($genrecd)) return ;
        $log =& LogFactory::getLog();
        $log->debug("debug", "Onedepo_Logic_Itemview#getGenreImage");

        $imageurl = "";
        if (is_file(IMAGE_DIR ."/6/". $genrecd . $size . ".jpg"))
            $imageurl = "img.php?c=". $genrecd ."&s=". $size ."&d=6";
        return $imageurl;
    }

    /**
     * 指定したサイズの画像が登録されているジャンルのみ取得
     **/
    function getGenreHasImage($size="S")
    {
        $genrelist = $this->genre->selectAll();

        $r = array();
        foreach ($genrelist as $k => $v) {
            if (is_file(IMAGE_DIR ."/6/". $v["genrecd"] . $size . ".jpg")) {
                $imageurl = "img.php?c=". $v["genrecd"] ."&s=". $size ."&d=6";

                $r[] = array("genrecd"=>$v["genrecd"],
                             "genrenm"=>$v["genrenm"],
                             "genreimg"=>$imageurl);
            }
        }
        return $r;
    }
}
?>