<?php
/*
 * This file is part of INQMAN
 *
 * Copyright(c) 2008 BULLHEAD,INC. ALL RIGHTS RESERVED.
 *
 * http://www.bullhead.co.jp/
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation;
 * either version 3 of the License, or (at your option) any later
 * version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * サービス管理画面のコントローラークラス
 *
 * @author 
 * @copyright COPYRIGHT &copy 2008 BULLHEAD,INC. ALL RIGHTS RESERVED.
 * @version 
 * @package 
 * @see AbstractController
 */
class Inqman_ServiceController extends AbstractController
{
    /**
     * インデックス画面
     * 
     * @access public
     */
    public function indexAction()
    {
        $this->_forward('view_list');
    }
    
	/**
	 * サービス情報一覧を表示する
	 * 
	 * @access public
	 */
	public function viewlistAction()
	{
        //アクセス権限のチェック
        $this->_checkAcl(ACL_RESOURCE_KEY_SERVICE, ACL_PRIVILEGE_KEY_READ, ACL_GLOBAL_SERVICE_ID);
        
        //ページタイトルの設定
        $this->_setupPageTitle('view_list', 'service');
	}
	
	/**
	 * サービス情報をJSON形式で返す
	 * 
	 * @access public
	 */
	public function jsonAction()
	{
        try{
           $this->_checkAcl(ACL_RESOURCE_KEY_SERVICE, ACL_PRIVILEGE_KEY_READ, ACL_GLOBAL_SERVICE_ID);
        } catch (Exception $e) {
            return null;
        }
	    
        // リクエストのフィルタリング。
        $f = new Zend_Filter_StripTags();
        $qtype     = $f->filter($this->_request->getParam('qtype'));
        $query     = $f->filter($this->_request->getParam('query'));
        $page      = $f->filter($this->_request->getParam('page',1));
        $rp        = $f->filter($this->_request->getParam('rp',10));
        $sortname  = $f->filter($this->_request->getParam('sortname', 'id'));
        $sortorder = $f->filter($this->_request->getParam('sortorder', 'desc'));
        
        $criteria = $this->getRequest()->getParam('crtr');
        $criteria['enable'] = 1;
	    
	    $this->_helper->viewRenderer->setNoRender();
	    $service_model = new Inqman_ServiceModel();
	    
	    $count  = $service_model->getTotalSize($criteria);
	    $order = "{$sortname} {$sortorder}";
	           
        $rows = $service_model->findService($order, $page, $rp, $criteria);
	    
        $json = array(
                'page' => (int) $page,
                'total' => (int) $count,
        );
	    
	    foreach ($rows as $row) {
	        $tmp = array();
	        $tmp[] = $row['id'];
	        $tmp[] = $this->view->escape($row['name']);
	        $tmp[] = $this->view->escape($row['code']);
	        $tmp[] = $this->view->escape($row['inquiry_mailaddress']);
	        $tmp[] = $this->view->escape($row['comment_mailaddress']);
	        //$tmp[] = $row['enable'] == 0 ? $this->_translate->translate('common.label.enable.0')
	        //                             : $this->_translate->translate('common.label.enable.1');
	        $tmp[] = empty($row['create_datetime']) ? "----" : $this->view->escape($row['create_datetime']);
	        $tmp[] = empty($row['update_datetime']) ? "----" : $this->view->escape($row['update_datetime']);
	        $tmp[] = "<a href=\"service/setup_receive/service_id/{$row['id']}/\">{$this->view->translate('service.operation.setup_receive')}</a>"
	               . "&nbsp;/&nbsp;<a href=\"./service/modify_input/service_id/{$row['id']}/\">{$this->view->translate('common.operation.modify')}</a>"
	               . "&nbsp;/&nbsp;<a href=\"./service/delete_confirm/service_id/{$row['id']}/\">{$this->view->translate('common.operation.delete')}</a>";
	        $json['rows'][] = array('cell' => $tmp);
	    }
	    $this->_helper->json->sendJson($json);
	}

	/**
     * サービス登録の入力画面を表示する
     * 
     * @access public
     */
    public function createinputAction()
    {        
        //ページタイトルの設定
        $this->_setupPageTitle('create_input', 'service');
        
        //アクセス権限のチェック
        $this->_checkAcl(ACL_RESOURCE_KEY_SERVICE, ACL_PRIVILEGE_KEY_CREATE, ACL_GLOBAL_SERVICE_ID);
        
        //確認画面から戻ってきた場合に、入力フィールドに値を入れる
        if (!empty($_POST)) {
            $form_input = $_POST;
        } else {
            $form_input = array(
                'service_id'          => "",
                'name'	     		  => "",
                'code'				  => "",
                'inquiry_mailaddress' => "",
            	'comment_mailaddress' => "",
            );
        }
        $this->view->assign(VIEW_KEY_FORM_INPUT, $form_input);
        
        $this->_assignCreateActionValue();
        $this->_helper->viewRenderer->setRender('input');
    }
    
    /**
     * サービス登録の入力情報確認画面を表示する
     * 
     * @access public
     */
    public function createconfirmAction()
    {        
        //ページタイトルの設定
        $this->_setupPageTitle('create_confirm', 'service');
        
        //アクセス権限のチェック
        $this->_checkAcl(ACL_RESOURCE_KEY_SERVICE, ACL_PRIVILEGE_KEY_CREATE, ACL_GLOBAL_SERVICE_ID);
        
        $form  = new Inqman_ServiceForm();
        $error_messages = array();
        
        //フォーム入力値の検証
        if(!$form->isValid($_POST)) {
            $error_messages = $form->getMessages();
        }
        
        //ユニークフィールドの重複チェック
        $error_messages = array_merge($error_messages, (array) $this->_checkDuplicate($form));
        
        //エラーがあった場合はメッセージをセットして、入力画面を再表示
        if (empty($error_messages))
        {
            $this->view->assign(VIEW_KEY_FORM_INPUT, $form->getValues());
            $this->_helper->viewRenderer->setRender('confirm');
        } else {
            $this->view->assign(VIEW_KEY_ERROR_MESSAGES, $error_messages);
            $this->view->assign(VIEW_KEY_FORM_INPUT, $form->getUnfilteredValues());
            $this->_helper->viewRenderer->setRender('input');  
        }
        
        $this->_assignCreateActionValue();
    }
	
	/**
	 * サービス登録を実行する
	 * 
	 * @access public
	 */
	public function createcommitAction()
	{        
        //ページタイトルの設定
        $this->_setupPageTitle('create_commit', 'service');
        
        //アクセス権限のチェック
        $this->_checkAcl(ACL_RESOURCE_KEY_SERVICE, ACL_PRIVILEGE_KEY_CREATE, ACL_GLOBAL_SERVICE_ID);
	    
        $form  = new Inqman_ServiceForm();
        $model = new Inqman_ServiceModel();
        $error_messages = array();
        
        //フォーム入力値の検証
        if(!$form->isValid($_POST)) {
            $error_messages = $form->getMessages();
        }
        
        //ユニークフィールドの重複チェック
        $error_messages = array_merge($error_messages, (array) $this->_checkDuplicate($form));
        
        if (empty($error_messages))
        {
            $values = array(
            		'name'                => $form->getValue(Inqman_ServiceForm::NAME),
                    'code'				  => $form->getValue(Inqman_ServiceForm::CODE),
                    'inquiry_mailaddress' => $form->getValue(Inqman_ServiceForm::INQ_MAIL),
                    'comment_mailaddress' => $form->getValue(Inqman_ServiceForm::CMT_MAIL),
                    'enable'              => 1,
                    'deleted'             => 0,
            );
            $model->createService($values);
            $this->_helper->viewRenderer->setRender('commit'); 
        }
        //エラーがあった場合はメッセージをセットして、入力画面を再表示
        else {
            $this->view->assign(VIEW_KEY_ERROR_MESSAGES, $error_messages);
            $this->view->assign(VIEW_KEY_FORM_INPUT, $form->getUnfilteredValues());
            $this->_helper->viewRenderer->setRender('input');  
        }
        
        $this->_assignCreateActionValue();
	}

	/**
	 * サービス設定変更の入力画面を表示する
	 * 
	 * @access public
	 */
	public function modifyinputAction()
	{
        //ページタイトルの設定
        $this->_setupPageTitle('modify_input', 'service');
        
	    //リクエストパラメータから変更対象のユーザIDを取得
	    $service_id = $this->getRequest()->getParam('service_id');
	    
        //アクセス権限のチェック
        $this->_checkAcl(ACL_RESOURCE_KEY_SERVICE, ACL_PRIVILEGE_KEY_UPDATE, ACL_GLOBAL_SERVICE_ID);
        
        $service_model = new Inqman_ServiceModel();
        $service = $service_model->getOneService($service_id);
        
        //確認画面から戻ってきた場合に、入力フィールドに値を入れる
        if (!empty($_POST)) {
            $form_input = $_POST;
        } else {
            $form_input = array(
                'service_id'          => $service['id'],
                'name'                => $service['name'],
                'code'                => $service['code'],
                'inquiry_mailaddress' => $service['inquiry_mailaddress'],
                'comment_mailaddress' => $service['comment_mailaddress'],
            );
        }
        $this->view->assign(VIEW_KEY_FORM_INPUT, $form_input);
        
        $this->_assignModifyActionValue();
        $this->_helper->viewRenderer->setRender('input');
	}
	
	/**
	 * サービス設定変更の入力情報確認画面を表示する
	 * 
	 * @access public
	 */
	public function modifyconfirmAction()
	{
        //ページタイトルの設定
        $this->_setupPageTitle('modify_confirm', 'service');
        
        //アクセス権限のチェック
        $this->_checkAcl(ACL_RESOURCE_KEY_SERVICE, ACL_PRIVILEGE_KEY_CREATE, ACL_GLOBAL_SERVICE_ID);
        
        $form  = new Inqman_ServiceForm();
        $error_messages = array();
        
        //フォーム入力値の検証
        if(!$form->isValid($_POST)) {
            $error_messages = $form->getMessages();
        }
        
        //ユニークフィールドの重複チェック
        $error_messages = array_merge($error_messages, (array) $this->_checkDuplicate($form, true));
        
        //エラーがあった場合はメッセージをセットして、入力画面を再表示
        if (empty($error_messages))
        {
            $this->view->assign(VIEW_KEY_FORM_INPUT, $form->getValues());
            $this->_helper->viewRenderer->setRender('confirm');
        } else {
            $this->view->assign(VIEW_KEY_ERROR_MESSAGES, $error_messages);
            $this->view->assign(VIEW_KEY_FORM_INPUT, $form->getUnfilteredValues());
            $this->_helper->viewRenderer->setRender('input');  
        }
        
        $this->_assignModifyActionValue();
	}
	
	/**
	 * サービス設定変更を実行する
	 * 
	 * @access public
	 */
	public function modifycommitAction()
	{
        //ページタイトルの設定
        $this->_setupPageTitle('modify_commit', 'service');
        
        //アクセス権限のチェック
        $this->_checkAcl(ACL_RESOURCE_KEY_SERVICE, ACL_PRIVILEGE_KEY_CREATE, ACL_GLOBAL_SERVICE_ID);
	    
        $form  = new Inqman_ServiceForm();
        $model = new Inqman_ServiceModel();
        $error_messages = array();
        
        //フォーム入力値の検証
        if(!$form->isValid($_POST)) {
            $error_messages = $form->getMessages();
        }
        
        //ユニークフィールドの重複チェック
        $error_messages = array_merge($error_messages, (array) $this->_checkDuplicate($form, true));
        
        if (empty($error_messages))
        {
            $service_id = $form->getValue(Inqman_ServiceForm::ID);
            $values = array(
                    'id'                  => $service_id,
            		'name'                => $form->getValue(Inqman_ServiceForm::NAME),
                    'code'				  => $form->getValue(Inqman_ServiceForm::CODE),
                    'inquiry_mailaddress' => $form->getValue(Inqman_ServiceForm::INQ_MAIL),
                    'comment_mailaddress' => $form->getValue(Inqman_ServiceForm::CMT_MAIL),
            );
            $model->updateService($service_id, $values);
            $this->_helper->viewRenderer->setRender('commit'); 
        }
        //エラーがあった場合はメッセージをセットして、入力画面を再表示
        else {
            $this->view->assign(VIEW_KEY_ERROR_MESSAGES, $error_messages);
            $this->view->assign(VIEW_KEY_FORM_INPUT, $form->getUnfilteredValues());
            $this->_helper->viewRenderer->setRender('input');  
        }
        
        $this->_assignModifyActionValue();
	}
	
	/**
	 * 受信設定の入力画面を表示する
	 * 
	 * @access public
	 */
	public function setupreceiveAction()
	{
        //ページタイトルの設定
        $this->_setupPageTitle('setup_receive', 'service');
        
	    //リクエストパラメータから変更対象のサービスIDを取得
	    $service_id = $this->getRequest()->getParam('service_id');
	    
        //アクセス権限のチェック
        $this->_checkAcl(ACL_RESOURCE_KEY_SERVICE, ACL_PRIVILEGE_KEY_UPDATE, ACL_GLOBAL_SERVICE_ID);
        
        $service_model = new Inqman_ServiceModel();
        $service = $service_model->getOneService($service_id);
        $this->view->assign('service', $service);
        
        $service_settings = $service_model->getServiceSettings($service_id);
        
        $this->view->assign('service_settings', $service_settings);
	}
	
	/**
	 * 受信設定の変更を実行する
	 * 
	 * @access public
	 */
	public function setupreceivecommitAction()
	{
        
	    //リクエストパラメータから変更対象のサービスIDを取得
	    $service_id = $this->getRequest()->getParam('service_id');
	    
        //アクセス権限のチェック
        $this->_checkAcl(ACL_RESOURCE_KEY_SERVICE, ACL_PRIVILEGE_KEY_UPDATE, ACL_GLOBAL_SERVICE_ID);
        
        //入力された設定情報を取得
        $settings = $this->getRequest()->getParam('settings');
        
        //設定変更を実行
        $service_model = new Inqman_ServiceModel();
        $service_model->updateServiceSettings($service_id, $settings);

	    $this->_helper->viewRenderer->setNoRender();
	    $this->_redirect("/service/setup_receive/service_id/{$service_id}/");
	}
	
	/**
	 * ユーザ情報の削除確認画面を表示する
	 * 
	 * @access public
	 */
	public function deleteconfirmAction()
	{
        //ページタイトルの設定
        $this->_setupPageTitle('delete_confirm', 'service');
        	    
        //アクセス権限のチェック
        $this->_checkAcl(ACL_RESOURCE_KEY_SERVICE, ACL_PRIVILEGE_KEY_DELETE, ACL_GLOBAL_SERVICE_ID);
        
	    //リクエストパラメータから変更対象のサービスIDを取得
	    $service_id = $this->getRequest()->getParam('service_id');
	    
	    //サービス情報を取得
        $service_model = new Inqman_ServiceModel();
        $service = $service_model->getOneService($service_id);
        $this->view->assign('service', $service);
	}
	
	/**
	 * ユーザ情報の削除を実行する
	 * 
	 * @access public
	 */
	public function deletecommitAction()
	{
        //ページタイトルの設定
        $this->_setupPageTitle('delete_commit', 'service');
        
        //アクセス権限のチェック
        $this->_checkAcl(ACL_RESOURCE_KEY_SERVICE, ACL_PRIVILEGE_KEY_DELETE, ACL_GLOBAL_SERVICE_ID);
        
	    //リクエストパラメータから変更対象のサービスIDを取得
	    $service_id = $this->getRequest()->getParam('service_id');
	    
	    //サービス情報を削除
        $service_model = new Inqman_ServiceModel();
        $service_model->deleteService($service_id);
	}
	
	/**
	 * ユニークフィールドの重複チェックを行う
	 * 
	 * @access protected
	 * @param Inqman_ServiceForm $form
	 * @return array 
	 * 
	 */
	protected function _checkDuplicate($form, $is_modify=false)
	{
        $model = new Inqman_ServiceModel();
        $error_messages = null;
	    
        //サービスコードの重複チェック
        $code = $form->getValue(Inqman_ServiceForm::CODE);
        if (!empty($code) && !$model->checkDuplicateCode($code, $is_modify)) {
            $error_messages[Inqman_ServiceForm::CODE] = array($this->view->translate('svccodeIsDuplicated'));
        }
        
        //問い合わせ受付用メールアドレスの重複チェック
        $inquiry_mailaddress = $form->getValue(Inqman_ServiceForm::INQ_MAIL);
        if (!empty($inquiry_mailaddress) && !$model->checkDuplicateInquiryMailaddress($inquiry_mailaddress, $is_modify)) {
            $error_messages[Inqman_ServiceForm::INQ_MAIL] = array($this->view->translate('inqaddrIsDuplicated'));
        }
        
        //コメント受付用メールアドレスの重複チェック
        $comment_mailaddress = $form->getValue(Inqman_ServiceForm::CMT_MAIL);
        if (!empty($comment_mailaddress) && !$model->checkDuplicateCommentMailaddress($comment_mailaddress, $is_modify)) {
            $error_messages[Inqman_ServiceForm::CMT_MAIL] = array($this->view->translate('cmtaddrIsDuplicated'));
        }
        
        return $error_messages;
	}
	
}