<?php
/**
 * Implementation of blog administration controller for comments
 *
 * @package koubel homepage
 * @author Miroslav Kubelik (koubel@volny.cz)
 * @copyright Copyright (c) 2007-2009 Miroslav Kubelik
 * @license http://opensource.org/licenses/gpl-license.php GNU GPL
 */

/**
 * Serves administration actions for blog comments
 *
 * @package koubel homepage
 * @author Miroslav Kubelik (koubel@volny.cz)
 * @copyright Copyright (c) 2007-2009 Miroslav Kubelik
 * @license http://opensource.org/licenses/gpl-license.php GNU GPL
 */
class Blog_Admin_CommentController extends Zend_Controller_Action
{
    /** count of comments in a list */
    const COMMENTS_PER_PAGE = 15;

    /**
     * Views the table with the comment list, a pagination is supported.
     */
    public function indexAction()
    {
        $comment = new Comment();

        $this->view->comments = $comment->getAll(
            $this->_helper->Paginator->getPageNumber(),
            self::COMMENTS_PER_PAGE
        );
        $this->view->paginator = $comment->getPaginator();

        if ($this->_helper->flashMessenger->hasMessages()) {
            $this->view->messages = $this->_helper->flashMessenger->getMessages();
        }
    }

    /**
     * Views a dialog for an edit comment page with a form.
     * It is used as target for the forward or redirect from the another actions, hence
     * it can set a form data from an old request, which will not serve in another actions.
     */
    public function editAction()
    {
        $comment = new Comment();

        //in POST are old data, it occures when current submitted data are invalid, so
        //we print old data in form, user can corrects these.
        if (isset($_POST["commentId"])) {
            $data=$this->getRequest()->getPost();
            $this->view->formData=$data;
            $this->view->formData["id"]=$data["commentId"];
            $comment->findById( $data["commentId"] );
        } else {
            //no old data, gets data from database
            $comment->findById( $this->_getParam("itemId") );
            $this->view->formData=$comment->getDaoRow(false)->toArray();

            //special format for a datetime
            $date=new Zend_Date($comment->getPosted(),Zend_Date::ISO_8601,"en_US");
            $this->view->formData["posted"]=$date->toString('dd-MM-yyyy HH:mm:ss');
        }//end isset($_POST["commentId"]

        $relatedArticle = $comment->getArticle();
        $this->view->article = $relatedArticle;
        $this->view->articleUrl = $this->_helper->url->url(
            array("entry" => $relatedArticle->getTitle()),
            "blogArticle"
        );

        if ($this->_helper->flashMessenger->hasMessages()) {
            $this->view->messages=$this->_helper->flashMessenger->getMessages();
        }
    }

    /**
     * Search for a comment - view for a search form
     */
    public function searchAction()
    {
    }

    /**
     * Action, which is aim for a search comment entry dialog.
     * When input data are invalid, forwards to the {@link searchAction()}.
     */
    public function searchResultAction()
    {
        if ($this->_hasParam("name")) {
            $data=$this->getRequest()->getPost();
            $filters = array(
                'name'   => 'StringTrim',
                'email' => 'StringTrim',
                'message' => 'StringTrim',
                'from' => 'StringTrim',
                'to' => 'StringTrim',
            );

            $validators = array();

            $inputFilter = new Zend_Filter_Input($filters,$validators);

            $inputFilter->setData($data);

            if ($inputFilter->isValid()) {
                $params=array("name"=> $inputFilter->getUnescaped('name'),
                    "email"=> $inputFilter->email,
                    "message"=> $inputFilter->getUnescaped('message'),
                    "from"=> $inputFilter->from,
                    "to"=> $inputFilter->to,
                );
            } else {
                //invalid data
                $messages[]="Data are invalid:";
                $messages = array_merge($messages,Utils::getMessagesOneArray($inputFilter));
                $this->view->messages=$messages;
                $this->_forward("search");
                return;
            }
        }

        //search object
        $search = Search::factorySearch("SearchBlogComment");
        //set the pagination
        $search->setPageParams(
            $this->_helper->Paginator->getPageNumber(),
            self::COMMENTS_PER_PAGE
        );

        //set search parameters if are in the request, otherwise these are loaded from
        //session in the factory
        if (isset($params)) {
            $search->setParams($params);
        }

        //search result
        $comment = new Comment();
        $this->view->foundItems = $comment->getFound($search);
        $this->view->paginator = $search->getPaginator();
        $this->_helper->viewRenderer->setRender('index');

        //get found items count, if no items found sets count in the view and exits
        if (!count($this->view->paginator)) {
            return;
        }
        
        //save search params to session
        $search->saveToSession();
    }

    /**
     * Updates the comment entry in the database.
     * If something fails, forwards to the editAction. If the database update was OK, redirects
     * to the editAction with some flash message.
     */
    public function updateDbAction()
    {
        // Don't auto render
        $this->_helper->viewRenderer->setNoRender();
        $data=$this->getRequest()->getPost();

        $filters = array(
            'name' =>'StringTrim',
            'www' => 'StringTrim',
            'email' => 'StringTrim',
            'posted' => 'StringTrim',
            'message' => 'StringTrim'
        );

        $validators = array(
            'name'   => 'NotEmpty',
            'www' => array(new UrlValid(),'allowEmpty' => true),
            'email'   => 'EmailAddress',
            'message' => 'NotEmpty',
            'posted' => array('NotEmpty',new DateTimeValid())
        );

        $inputFilter = new Zend_Filter_Input($filters, $validators);
        $inputFilter->setData($data);

        if ($inputFilter->isValid()) {
            $name=$inputFilter->getUnescaped("name");
            $email=$inputFilter->getUnescaped("email");
            $message=$inputFilter->getUnescaped("message");
            $message=Comment::prepareCommentText($message);
            $postedDate=new Zend_Date($inputFilter->posted,'dd-MM-yyyy HH:mm:ss',"en_US");
            $www=$inputFilter->getUnescaped('www');
            if (!empty($www) && !preg_match("|^http(s)?://|i",$www)) $www="http://".$www;

            $comment=new Comment();

            try {
                $comment->setId($data["commentId"]);
                $comment->setAuthorName($name);
                $comment->setAuthorEmail($email);
                $comment->setAuthorWWW($www);
                $comment->setPosted($postedDate->toString('yyyy-MM-dd HH:mm:ss'));
                $comment->setMessage($message);
                $comment->update();
            } catch (Zend_Db_Exception $e) {
                $message="Cannot update record, database error: ".$e->getMessage();
                $this->view->messages=array($message);
                $this->_forward("edit");
                return;
            }

            $message="Record was updated";
            $this->_helper->flashMessenger->addMessage($message);
            $this->_helper->redirector->gotoUrlAndExit($this->_helper->url->url(
                array(
                    "controller" => "comment",
                    "action" => "edit",
                    "itemId" => $data["commentId"]
                ),"blogAdminItemAction"),
                array("prependBase" => false)
            );

            return;

        } else {
            //invalid data
            $messages[] = "Data are invalid:";
            $messages = array_merge($messages,Utils::getMessagesOneArray($inputFilter));
            $this->view->messages = $messages;
            $this->_forward("edit");
            return;
        }
    }

    /**
     * Action, which is complete responsible for a removing comment from the database.
     * It views dialog for the confirmation, than if we realy want delete item and
     * serves database removing also.
     */
    public function deleteAction()
    {
        $comment = new Comment();
        $itemId = $this->_getParam("itemId");
        $comment->findById($itemId);

        //"really want" delete flag
        $delflag=false;

        //confirmation was send
        if (isset($_GET['wantdel']))
        {
            //No - redirect entry list
            if ($_GET['wantdel']=="No") {
                $this->_helper->redirector->gotoUrlAndExit($this->_helper->url->url(
									array(
										"controller" => "comment",
										"action" => "index"
									),"blogAdmin"),array("prependBase"=>false));
                return;
            }
            //Yes - delete
            $delflag = $_GET['wantdel']=="Yes" ? true : false;
        }

        //if really want delete, make it
        if ($delflag) {
            //delete from database
            try {
                $comment->delete();
            } catch (Zend_Db_Exception $e) {
                $message = "Cannot delete record, database error: ".$e->getMessage();
                $this->_helper->flashMessenger->addMessage($message);
                $this->_helper->redirector->gotoUrlAndExit($this->_helper->url->url(
									array(
										"controller" => "comment",
										"action" => "delete",
										"itemId" => $comment->getId()
									),"blogAdminItemAction"),array("prependBase"=>false));
                return;
            }

            //redirect after successful deleting
            $this->_helper->flashMessenger->addMessage("Comment with ID ".$comment->getId()
                . " was deleted");
            $this->_helper->redirector->gotoUrlAndExit($this->_helper->url->url(
								array(
									"controller" => "comment",
									"action" => "index"
								),"blogAdmin"),array("prependBase"=>false));
            return;
        }

        $this->view->subject = "comment with ID: ".$comment->getId();
        $this->view->nextInfo = "<br />Comment text: ".$comment->getMessage();
        $this->view->wasDeleted = $delflag;
        //delete url
        $this->view->deleteUrl = $this->_helper->url->url(
					array(
						"controller" => "comment",
						"action" => "delete",
						"itemId" => $comment->getId()
					),"blogAdminItemAction");

        if ($this->_helper->flashMessenger->hasMessages()) {
            $this->view->messages = $this->_helper->flashMessenger->getMessages();
        }

        $this->_helper->viewRenderer->setRender("admin/deleteItem",null,true);
    }
}
