<?php
/* SVN FILE: $Id: search.php 495 2008-05-24 11:46:17Z bb_yujiro $ */
/**
 * Model_View Controller
 *
 * PHP versions 5
 *
 *      Hitsuji : Social Network Service <http://rakuto.net/rktSNS/>
 *      Copyright (c) 2007 Yujiro Takahashi
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @filesource
 * @package         Hitsuji
 * @copyright       Copyright (c) 2007 Yujiro Takahashi
 * @link            http://rakuto.net/
 * @author          Yujiro Takahashi <yujiro@rakuto.net>
 * @version         $Revision: 495 $
 * @modifiedby      $LastChangedBy: bb_yujiro $
 * @lastmodified    $Date: 2008-05-24 20:46:17 +0900 (土, 24 5 2008) $
 * @license         http://opensource.org/licenses/mit-license.php The MIT License
 */

/**
 * Controllerクラス
 *
 * @category        Hitsuji : controller
 * @package         Hitsuji
 * @copyright       Copyright (c) 2007 Yujiro Takahashi
 * @link            http://rakuto.net/rktSNS/
 * @author          Yujiro Takahashi <yujiro@rakuto.net>
 * @version         $Revision: 495 $
 * @modifiedby      $LastChangedBy: bb_yujiro $
 * @lastmodified    $Date: 2008-05-24 20:46:17 +0900 (土, 24 5 2008) $
 * @license         http://opensource.org/licenses/mit-license.php The MIT License
 */
class Controller extends Public_Controller 
{
    /**
     * ページ
     * @var integer
     */
    protected $page = 0;

    /**
     * カテゴリID
     * @var integer
     */
    protected $ref_category = null;

    /**
     * キーワード
     * @var string
     */
    protected $keyword = null;

    /**
     * カテゴリコード
     * @var string
     */
    private $_code = null;

    /**
     * カテゴリ
     * @var array
     */
    private $_categories = null;

    /**
     * 変数の初期化
     *
     * @abstract
     * @access protected
     * @return void
     */
    protected function initValue()
    {
        $this->objvew->setTemplate('sidebar_tpl', 'common/menu/review.tpl');
        $this->page = empty($this->page)? 1:$this->page;
    }

    /**
     * 実行処理
     *
     * @access public
     * @return void
     **/
    protected function action()
    {
        $this->objvew->addJavas('js/rating.js');
        $this->_setCategory();
        
        if (empty($this->_categories[$this->ref_category])){
            $this->_code = 'Books';
            $service     = 'amazon';
        } else {
            $this->_code = $this->_categories[$this->ref_category]['code'];
            $service     = $this->_categories[$this->ref_category]['service'];
        }
        $methods = array(
            'amazon'=> '_setAmazon',
            'gnavi'=>  '_setGnavi',
        );
        $method = empty($methods[$service])? '_setAmazon':$methods[$service];
        call_user_func(array(&$this, $method));

        if ($this->account['status'] == STATUS_GUEST){
            $command = '';
        } else {
            $command = '<a id="anc%s" href="javascript:myRating%s.sendRating(\''.
                       HTTP_ACTION.'private/post/rating/0/json/\', \'anc%s\', \''._('Sent Rating').'\', \''._('Bad').'\');">'.
                       _('Send Rating').' </a>';
        }
        $this->objvew->assign('command', $command);
    }

    /**
     * 入力条件の設定
     *
     * @access protected
     * @return void
     **/
    protected function setCondition()
    {
        $this->conditions = array (
            'page'=> array(
                'type'=>     'number',
                'option'=>   array(),
                'required'=> false,
            ),
            'keyword'=> array(
                'type'=>     'string',
                'option'=>   array(),
                'required'=> false,
            ),
            'ref_category'=> array(
                'type'=>     'number',
                'option'=>   array(),
                'required'=> false,
            ),
        );
    }

    /**
     * カテゴリの設定
     *
     * @access private
     * @return void
     **/
    private function _setCategory()
    {
        $list = RKT_DB::getList('rev_category', null, '*', 'sort');

        $categories = array();
        foreach ($list as $row){
            $categories[$row['id']] = $row['label'];
            $this->_categories[$row['id']] = $row;
        }
        $this->objvew->assign('rev_categories', $categories);
    }

    /**
     * 評価の取得
     *
     * @access private
     * @param string item_code
     * @return void
     **/
    private function _getRating($item_code)
    {
        $condition = array(
            'item_code'=>   $item_code,
        );
        $review = RKT_DB::getRow('rev_review', $condition);

        $condition = array(
            'item_code'=>   $item_code,
            'ref_account'=> $this->account['id'],
        );
        $rating = RKT_DB::getRow('rev_rating', $condition);
        
        return array(
            'posts'=>  empty($review['posts'])?  0:$review['posts'],
            'point'=> empty($rating['point'])? 0:$rating['point'],
        );
    }

    /**
     * アマゾンWebサービス
     *
     * @access private
     * @return void
     **/
    private function _setAmazon()
    {
        include LIB_DIR.'PEAR/Services/AmazonECS4.php';
        $this->keyword = empty($this->keyword)? ' ':$this->keyword;

        $amazon = new Services_AmazonECS4(AMAZON_TOKEN, AMAZON_ASSOCIATEID);
        $options = array(
            'ResponseGroup'=> 'Medium',
            'Sort'=>'salesrank',
            'Keywords'=> $this->keyword,
            'ItemPage'=> $this->page
        );
        $result = $amazon->ItemSearch($this->_code, $options);
        if (PEAR::isError($result)) {
            return false;
        }

        $allowable_tags = '<br><b><a><ul><li>';
        $list = array();
        foreach ($result['Item'] as $row){
            $comment  = empty($row['ItemAttributes']['Author'][0])? '':$row['ItemAttributes']['Author'][0].'<br />';
            $comment .= empty($row['ItemAttributes']['Artist'])? '':$row['ItemAttributes']['Artist'].'<br />';
            $comment .= empty($row['ItemAttributes']['Manufacturer'])? '':$row['ItemAttributes']['Manufacturer'].'<br />';
            $comment .= empty($row['OfferSummary']['LowestNewPrice']['FormattedPrice'])? '':$row['OfferSummary']['LowestNewPrice']['FormattedPrice'].'<br />';

            $comment .= empty($row['EditorialReviews']['EditorialReview'][0]['Source'])? '':'<br />'.$row['EditorialReviews']['EditorialReview'][0]['Source'].'<br />';
            $comment .= empty($row['EditorialReviews']['EditorialReview'][0]['Content'])? '':strip_tags($row['EditorialReviews']['EditorialReview'][0]['Content'], $allowable_tags).'<br />';
            
            $rating = $this->_getRating($row['ASIN']);

            $list[] = array(
                'item_code'=> $row['ASIN'],
                'view_url'=>  $row['DetailPageURL'],
                'small_img'=> empty($row['SmallImage']['URL'])? BASE_URL.NOPHOTO_SMALL:$row['SmallImage']['URL'],
                'large_img'=> empty($row['MediumImage']['URL'])? BASE_URL.NOPHOTO_LARGE:$row['MediumImage']['URL'],
                'title'=>     $row['ItemAttributes']['Title'],
                'comment'=>   $comment,
                'posts'=>      $rating['posts'],
                'point'=>     $rating['point'],
            );
            
        }
        $this->objvew->assign('result', $list);
        $pager = array(
            'page'=>      $this->page,
            'prev'=>      $this->page - 1,
            'next'=>      $this->page + 1,
            'max_page'=>  $result['TotalPages'],
            'param'=>     array()
        );
        $this->objvew->assign('pager', $pager);
        $this->objvew->assign('service',   'amazon');
        $this->objvew->assign('atService', 'Amazon');

        $this->objvew->assign('class_name',  'horizontal');
        $this->objvew->assign('left_width',  166);
        $this->objvew->assign('right_width', 344);
    }

    /**
     * ぐるなびWebサービス
     *
     * @access private
     * @return void
     **/
    private function _setGnavi()
    {
        include LIB_DIR.'PEAR/Services/Gnavi.php';

        $gnavi = new Services_Gnavi(GNAVI_ACCESS_KEY);

        // Restaurant Search
        $options = array(
            'category_l'=>  $this->_code,
            'offset_page'=> $this->page,
            'hit_per_page'=>LIMIT_REVIEW
        );
        
        if (!empty($this->keyword)){
            $options['name'] = $this->keyword;
        }

        $gnavi->searchRestaurant($options);
        $result = $gnavi->getResult();
        if (PEAR::isError($result)) {
            return false;
        }

        if ($result['total_hit_count'] == 1){
            $result['rest'] = array($result['rest']);
        }
        $list = array();
        if (is_array($result['rest'])){
            foreach ($result['rest'] as $row){
                $rating = $this->_getRating($row['id']);
                $list[] = array(
                    'item_code'=> $row['id'],
                    'view_url'=>  $row['url'],
                    'small_img'=> BASE_URL.'review'.ACTION_STYLE.'/gnavi/'.$row['id'].'.jpg',
                    'large_img'=> BASE_URL.'review'.ACTION_STYLE.'/gnavi/'.$row['id'].'.jpg',
                    'title'=>     $row['name'],
                    'comment'=>   $row['pr']['pr_long'],
                    'posts'=>      $rating['posts'],
                    'point'=>     $rating['point'],
                );
            
            }
        } // if (!empty($result['rest']))
        $this->objvew->assign('result', $list);
        $max_page = 0;
        if (!empty($result['total_hit_count'])){
            $max_page = intval(($result['total_hit_count'] / LIMIT_REVIEW) + 0.9999);
        }

        $pager = array(
            'page'=>      $this->page,
            'prev'=>      $this->page - 1,
            'next'=>      $this->page + 1,
            'max_page'=>  $max_page,
            'param'=>     array()
        );
        $this->objvew->assign('pager', $pager);
        $this->objvew->assign('service',   'gnavi');
        $this->objvew->assign('atService', 'ぐるなび');

        $this->objvew->assign('class_name',  '');
        $this->objvew->assign('left_width',  510);
        $this->objvew->assign('right_width', 510);
    }

} // class Controller
?>
