<?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/>.
 */

require_once MOD_INQMAN_CONTROLLERS_DIR . '/InquiryController.php';

/**
 * 未承認問い合わせ管理画面のコントローラークラス
 *
 * @author 
 * @copyright COPYRIGHT &copy 2008 BULLHEAD,INC. ALL RIGHTS RESERVED.
 * @version 
 * @package 
 * @see InquiryController
 */
class Inqman_UnapprovalController extends Inqman_InquiryController 
{
    /**
     * 承認待ち状態の問い合わせ一覧を表示する。
     * 
     * @access public
     * 
     */
    public function viewlistAction()
    {
        //ページタイトルの設定
        $this->_setupPageTitle('view_list', 'unapproval');
        
        //リクエストパラメータからサービスIDを取得
        $service_id = $this->getRequest()->getParam(Inqman_InquiryForm::SERVICE_ID);
        
        //アクセス権限のチェック
        $this->_checkAcl(ACL_RESOURCE_KEY_UNAPPROVE, ACL_PRIVILEGE_KEY_READ, $service_id);
        
        $service_model = new Inqman_ServiceModel();
        $service = $service_model->getOneService($service_id);
        $this->view->assign('service', $service);
    }
    
    /**
     * 未処理問い合わせ情報をJSON形式で取得する
     * 
     */
    public function jsonAction()
    {
        // 出力にテンプレートを使わないので、NoRender。
        $this->_helper->viewRenderer->setNoRender();
        
        // リクエストのフィルタリング。
        $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'));
        $service_id = $f->filter($this->_request->getParam('service_id'));
        
        $criteria  = $this->_request->getParam('crtr');
        $this->_logger->debug("service_id:{$service_id}, qtype:{$qtype}, query:{$query}, page:{$page}, rp:{$rp}, sortname:{$sortname}, sortorder:{$sortorder}");
        
        $service_model = new Inqman_ServiceModel();
        $inquiry_model = new Inqman_InquiryModel();
        
        if (!empty($service_id)) {
            $service = $service_model->getOneService($service_id);
            $userInfo = $this->_getUserInfo();
        } else {
            $services = $service_model->getEnableServiceOptions($this->_getUserInfo()->id);
            $service_id = array_keys($services);
        }
        
        $order = "{$sortname}_{$sortorder}";
        
        /**
         * 問い合わせ情報取得処理
         */
        $rows  = $inquiry_model->getUnapprovalInquiries($service_id, $order, $page, $rp, $criteria);
        $count = $inquiry_model->getUnapprovalInquiriesTotalCount($service_id, $criteria);
        
        // jsonの作成。
        $json = array(
                'page' => (int) $page,
                'total' => (int) $count,
        );

        foreach ($rows as $row) {
            switch ($row['status']) {
                case Inqman_InquiryModel::STATUS_CODE_UNAPPROVAL:
                    $ctrlName = "unapproval";
                    break;
                default:
                    break;
            }
            
            $tmp = array();
            $tmp[] = $row['id'];
            $tmp[] = $row['service_name'];
            $tmp[] = '<a href="'. $ctrlName . '/view_detail/inquiry_id/' . $row['id'] . '/">' . $this->view->escape($row['subject']) . '</a>';
            $tmp[] = empty($row['received_from']) ? "--" : $this->view->escape($row['received_from']);
            $tmp[] = empty($row['content']) ? "--" : $this->view->escape($row['content']);
            $tmp[] = empty($row['create_datetime']) ? "--" : $row['create_datetime'];
            $tmp[] = empty($row['registrant_name']) ? "--" : $row['registrant_name'];
            $tmp[] = empty($row['accept_datetime']) ? "--" : $row['accept_datetime'];
            $tmp[] = empty($row['accepter_name']) ? "--" : $row['accepter_name'];
            $tmp[] = empty($row['operator_name']) ? "--" : $row['operator_name'];
            $tmp[] = '<div style="width:100%;padding:0;margin:0;background-color:'
                    . $this->_config->view->bgcolor->status->get($row['status'])
                    . ';border:solid 1px #999">' . $this->view->translate("inquiry.status.label."
                    . $row['status']) . '</div>';
            $tmp[] = $this->view->translate("inquiry.priority.label." . $row['priority']);
            $json['rows'][] = array('cell' => $tmp);
        }
        $this->_helper->json->sendJson($json);
    }
    
    /**
     * 承認待ち状態の問い合わせ詳細情報を表示する。
     * 
     * @access public
     */
    public function viewdetailAction()
    {
        //ページタイトルの設定
        $this->_setupPageTitle('view_detail', 'unapproval');
        
        //リクエストパラメータから問い合わせIDを取得する
        $inquiry_id = $this->getRequest()->getParam(REQUEST_KEY_INQUIRY_ID);
        
        //問い合わせ詳細情報を取得
        $inquiry_model = new Inqman_InquiryModel();
        $data = $inquiry_model->getOneInquiry($inquiry_id);
        
        $this->view->assign(VIEW_KEY_FORM_INPUT, $data);
        
        //問い合わせ情報からサービスIDを取得
        $service_id = $data[Inqman_InquiryModel::SERVICE_ID];
        
        //アクセス権限のチェック
        $this->_checkAcl(ACL_RESOURCE_KEY_UNAPPROVE, ACL_PRIVILEGE_KEY_READ, $service_id);
        
        //サービス情報を取得
        $service_model = new  Inqman_ServiceModel();
        $service = $service_model->getOneService($service_id);
        $this->view->assign('service', $service);
        
        //ラベル表示用の配列を取得
        $status_options   = $inquiry_model->getStatusOptions();
        $priority_options = $inquiry_model->getPriorityOptions();
        $this->view->assign('status_options', $status_options);
        $this->view->assign('priority_options', $priority_options);
        
        $this->_assignAclFlag($service_id, $inquiry_id);
        $this->_assignPermission($service_id, $data);
    }
    
    /**
     * 承認（却下）確認画面を表示する。
     * 
     * @access public
     */
    public function approveconfirmAction()
    {
        //ページタイトルの設定
        $this->_setupPageTitle('approve_confirm', 'unapproval');
        
        //リクエストパラメータから問い合わせIDを取得
        $inquiry_id = $this->getRequest()->getParam(REQUEST_KEY_INQUIRY_ID);        
        
        //問い合わせ詳細情報を取得
        $inquiry_model = new Inqman_InquiryModel();
        $data = $inquiry_model->getOneInquiry($inquiry_id);
        
        //問い合わせ情報からサービスIDを取得
        $service_id = $data[Inqman_InquiryModel::SERVICE_ID];
        $service_model = new Inqman_ServiceModel();
        $service = $service_model->getOneService($service_id);
        $this->view->assign('service', $service);
        
        //アクセス権限のチェック
        $this->_checkAcl(ACL_RESOURCE_KEY_INQUIRY, ACL_PRIVILEGE_KEY_APPROVE, $service_id);
        
        //承認か却下かを判別してそれぞれの処理を実行する
        $operation = $this->getRequest()->getParam('operation');
        if ($operation == 'approve') {
            $this->_performApproveConfirm($data);
        } else if ($operation == 'reject') {
            $this->_performRejectConfirm($data);
        }
        
        $status_options = $inquiry_model->getStatusOptions();
        $priority_options = $inquiry_model->getPriorityOptions();
        
        $this->view->assign('status_options', $status_options);
        $this->view->assign('priority_options', $priority_options);
        
        $this->_assignAclFlag($service_id, $inquiry_id);
        $this->_assignPermission($service_id, $data);
    }

    /**
     * 承認（却下）処理を実行する。
     * 
     * @access public
     * 
     */
    public function approvecommitAction()
    {
        //ページタイトルの設定
        $this->_setupPageTitle('approve_commit', 'unapproval');
        
        //リクエストパラメータから問い合わせIDを取得
        $inquiry_id = $this->getRequest()->getParam(REQUEST_KEY_INQUIRY_ID);        
        
        //問い合わせ詳細情報を取得
        $inquiry_model = new Inqman_InquiryModel();
        $data = $inquiry_model->getOneInquiry($inquiry_id);
        
        //問い合わせ情報からサービスIDを取得
        $service_id = $data[Inqman_InquiryModel::SERVICE_ID];
        
        //アクセス権限のチェック
        $this->_checkAcl(ACL_RESOURCE_KEY_INQUIRY, ACL_PRIVILEGE_KEY_APPROVE, $service_id);
        
        $form = new Inqman_InquiryForm();
        if ($form->isValid($_POST)) {
            //承認か却下かを判別してそれぞれの処理を実行する
            $operation = $this->getRequest()->getParam('operation');
            $values = $form->getValues();
            $values[Inqman_InquiryModel::ID] = $data[Inqman_InquiryModel::ID];
            if ($operation == 'approve') {
                $this->_performApproveCommit($values);
                $event_action_id = 8;
            } else if ($operation == 'reject') {
                $this->_performRejectCommit($values);
                $event_action_id = 6;
            }
            $this->view->assign('operation', $operation);
            
            $criteria = array('service_id'=>$service_id, 'inquiry_id'=>$inquiry_id);
            $inquiry_model->sendMail($event_action_id, $criteria);
        } else {
            //不正入力があった場合は、確認画面のアクションを経て入力画面に戻す
            $this->approveconfirmAction();
        }
        
        $this->view->assign('service_id', $service_id);
    }
    
    /** Local Methods **/
    
    /**
     * 承認確認の前処理を実行する。
     * 
     * @access protected
     * 
     */
    protected function _performApproveConfirm($data)
    {
        
        //起票者名/IDに、現ログインユーザ名/IDをセット
        $userInfo = $this->_getUserInfo();
        $data['approver_id']   = $userInfo->id;
        $data['approver_name'] = $userInfo->name;
        
        //入力値検証
        $form = new Inqman_ApproveForm();
        if(!$form->isValid($_POST)) {
            //エラーメッセージをVIEWにセット
            $this->view->assign(VIEW_KEY_ERROR_MESSAGES, $form->getMessages());
            
            //subject,priority,content,memoは入力値をセット
            $data['subject']       = $this->getRequest()->getParam('subject');
            $data['received_from'] = $this->getRequest()->getParam('received_from');
            $data['priority']      = $this->getRequest()->getParam('priority');
            $data['content']       = $this->getRequest()->getParam('content');
            
            $this->_helper->viewRenderer->setRender('view_detail');
        } else {
            $data['subject']       = $form->getValue('subject');
            $data['received_from'] = $form->getValue('received_from');
            $data['priority']      = $form->getValue('priority');
            $data['content']       = $form->getValue('content');
        }
        
        $data['operation'] = 'approve';
        
        $this->view->assign(VIEW_KEY_FORM_INPUT, $data);
    }
    
    /**
     * 却下確認の前処理を実行する。
     */
    protected function _performRejectConfirm($data)
    {
        
        //起票者名/IDに、現ログインユーザ名/IDをセット
        $userInfo = $this->_getUserInfo();
        $data['approver_id']   = $userInfo->id;
        $data['approver_name'] = $userInfo->name;
        
        //入力値検証
        $form = new Inqman_ApproveForm();
        if(!$form->isValid($_POST)) {
            //エラーメッセージをVIEWにセット
            $this->view->assign(VIEW_KEY_ERROR_MESSAGES, $form->getMessages());
            
            //subject,priority,content,memoは入力値をセット
            $data['subject']       = $this->getRequest()->getParam('subject');
            $data['received_from'] = $this->getRequest()->getParam('received_from');
            $data['priority']      = $this->getRequest()->getParam('priority');
            $data['content']       = $this->getRequest()->getParam('content');
            $data['memo']          = $this->getRequest()->getParam('memo');
            
            $this->_helper->viewRenderer->setRender('view_detail');
        } else {
            $data['subject']       = $form->getValue('subject');
            $data['received_from'] = $form->getValue('received_from');
            $data['priority']      = $form->getValue('priority');
            $data['content']       = $form->getValue('content');
            $data['memo']          = $form->getValue('memo');
        }
        
        $data['operation'] = 'reject';
        
        $this->view->assign(VIEW_KEY_FORM_INPUT, $data);
    }
    
    /**
     * 承認処理を実行する
     * 
     * @access protected
     * 
     */
    protected function _performApproveCommit($values)
    {
        $inquiry = array();
        
        //処理実行中のユーザを承認者に設定
        $userInfo = $this->_getUserInfo();
        $inquiry['approver_id'] = $userInfo->id;
        $inquiry['subject']     = $values['subject'];
        $inquiry['content']     = $values['content'];
        $inquiry['priority']    = $values['priority'];
        
        //承認処理
        $inquiry_id = $values['id'];
        
        $inquiry_model = new Inqman_InquiryModel();
        $inquiry_model->approveInquiry($inquiry_id, $inquiry);
    }
    
    /**
     * 却下処理を実行する
     * 
     * @access protected
     * 
     */
    protected function _performRejectCommit($values)
    {
        //却下処理
        $inquiry_id = $values['id'];
        
        $inquiry_model = new Inqman_InquiryModel();
        $inquiry_model->rejectInquiry($inquiry_id, $values);
    }
    
    /**
     * 編集権限、承認（却下）権限のチェック
     */
    public function _assignPermission($service_id, $data)
    {
        $acl_model = new Inqman_AclModel();
        $authorities = array_keys($this->_getUserInfo()->roles);
        $edit_flag = false;
        $approve_flag = false;
        if($acl_model->checkAcl(ACL_RESOURCE_KEY_INQUIRY, ACL_PRIVILEGE_KEY_APPROVE, $service_id, $authorities)) {
            $edit_flag = true;
            $approve_flag = true;
        } else if ($data['accepter_id'] == $this->_getUserInfo()->id) {
            $edit_flag = true;
        }
        $this->view->assign('edit_flag', $edit_flag);
        $this->view->assign('approve_flag', $approve_flag);
    }
    
}
