<?php
/**
 * appRain CMF
 *
 * LICENSE
 *
 * This source file is subject to the MIT license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.opensource.org/licenses/mit-license.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@apprain.com so we can send you a copy immediately.
 *
 * @copyright  Copyright (c) 2010 appRain, Inc. (http://www.apprain.com)
 * @license    http://www.opensource.org/licenses/mit-license.php MIT license
 *
 * HELP
 *
 * Official Website
 * http://www.apprain.com/
 *
 * Download Link
 * http://www.apprain.com/download
 *
 * Documents Link
 * http ://www.apprain.com/documents
 */
class appblogController extends appRain_Base_Core
{
    public $name = 'appBlog';

    /**
     * Execute before the action
     */
    public function __preDispatch()
    {

        //pre(App::Component('appBlog_appBlog')->Helper('Data')->getName());

        $this->set("section_title","Blog");
        $this->set("selected","blog");
    }

    /**
     * This is blog starting page
     * We have configure this page from
     * URI_Manager >> Boot_Router
     */
    public function indexAction($action=null, $id=null,$page = 1)
    {
        // Fetch a page from Page Manager and
        // set Meta information.
        $homepage = $this->staticPageNameToMetaInfo('Blog');

        if($action == 'bypost')
        {
            // Attache few Addons
            $this->addons = Array('defaultvalues','validation','ajaxsubmit');

            // Fetch a Single Post from Information Set
            // by Post Id
            $post = App::InformationSet()->findById($id);
            $this->set('post',$post);

            // Overwrite the page title
            $this->page_title = $post['title'];

            // Fetch all Comments for a particuler post
            $comments = App::Model('Comment')->findAll("postid={$id} AND status='Active'");
            $this->set('comments',$comments);
        }
        else if($action == 'bycat')
        {
            /**
             * See we can how we can optimize the pagination
             * You can make it more easier as per need
             */
            $blogpost = App::InformationSet('blog-post')
                        ->setPagination('Yes')
                        ->setSmartPaging(true)
                        ->setPage($page)
                        ->setLimit(2)
                        ->setHLink(App::Helper('Config')->baseurl("/blog-by-cat/{$id}/[page]/" . App::Helper('Utility')->Text2Normalize(App::CategorySet()->idToName($id))))
                        ->setNextCaption('Next >>')
                        ->setPrevCaption('<< Prev')
                        ->findAll(
                                    "1 ORDER BY id DESC",
                                    Array(
                                            Array("category"=>$id),
                                            "AND",
                                            Array("status"=>"Public")
                                          )
                                 );
            $this->set('blogpost',$blogpost);

            // Overwrite the page title
            $this->page_title = App::CategorySet()->idToName($id);

        }
        else
        {
            /**
             * See we can how we can optimize the pagination
             * You can make it more easier as per need
             */
            $page = is_numeric($action) ? $action : 1;
            $blogpost = App::InformationSet('blog-post')
                        ->setPagination('Yes')
                        ->setSmartPaging(true)
                        ->setPage($page)
                        ->setHLink(App::Helper('Config')->baseurl("/blog"))
                        ->setLimit(2)
                        ->setNextCaption('Next >>')
                        ->setPrevCaption('<< Prev')
                        ->findAll("1 ORDER BY id DESC",Array(Array("status"=>"Public")));
            $this->set('blogpost',$blogpost);
        }

        // Add another add-on with
        // previouse collection
        $this->addons[] = 'dropdownmenu';

        // Assign Common values
        // in template
        $this->set("action",$action);
        $this->set("catid",(($action == 'bycat')?$id:""));
    }

    /**
     * This page is called by an AJAX
     * request. We have have set the layout "empty"
     *
     * Empty layout never attach any template from "View"
     */
    public function submitcommentAction($id=null)
    {
        if(empty($this->data)) $this->redirect("/");

        // Set Empty Layout
        $this->layout = 'empty';

        // This is an simple example of Capture response by AppException Handaler
        // Hope you will like it
        // AJAX SUBMIT Helper capture response in JSON Formate
        // See Referance in Manual section from appRain official site
        try
        {
            $capacha = App::Module('Session')->read('capacha');

            if($capacha['blogcommet'] != $this->data['Comment']['capacha'])
            {
                throw new AppException($this->__("Please fillin the text display left side image correctly."));
            }

            // Save Comments
            // Please apply more logic if you needed
            $this->data['Comment']['postid'] = $id;
            $this->data['Comment']['status'] = 'Inactive';
            $this->data['Comment']['dated'] = App::Helper('Date')->getDate("Y-m-d H:i:s");
            App::Model('Comment')->Save($this->data);

            // Send Email notification using
            // Template Manager Helper
            App::Helper('EmailTemplate')->setParameters(Array(
                                                                'Name'=>$this->data['Comment']['name'],
                                                                'Comment'=>$this->data['Comment']['comment'],
                                                                'EmailAddress'=>$this->data['Comment']['email'],
                                                                'Website'=>$this->data['Comment']['website']
                                                        ))
                                        ->prepare('BlogComment',true);

            $status = 'Success';
            throw new AppException($this->__("Thank you, Your comment is waiting for pending approval."));
        }
        catch (AppException $e)
        {
            // Catch exceptions and display message
            // in JSON format using Cryptography Helper
            echo App::Load("Module/Cryptography")->jsonEncode(array(
                                                                    "_status" =>(isset($status) ? $status : 'Error'),
                                                                    "_message"=>$e->getMessage()
                                                              ));
        }
    }

    /**
     * Manage Blog Comments
     * We have render this page under Blog tab
     * in admin panel.
     */
    public function managecommentAction($action=null, $id = null)
    {
        // Set Admin Tab
        $this->setAdminTab('blog');

        // Update the post if
        // the action is set to 'update'
        if($action == 'update')
        {
            $this->addons = Array('rich_text_editor','date_picker');

            if(!empty($this->data))
            {
                $this->data['Comment']['id'] = $id;
                $this->data['Comment']['dated'] = date('Y-m-d H:i:s',strtotime("{$this->data['Comment']['dated']['year']}-{$this->data['Comment']['dated']['month']}-{$this->data['Comment']['dated']['day']} {$this->data['Comment']['dated']['hour']}:{$this->data['Comment']['dated']['munite']}:{$this->data['Comment']['dated']['second']}"));

                App::Model('Comment')->Save($this->data);

                $this->redirect("/appblog/managecomment/");
                exit;
            }

            $comment = App::Model('Comment')->findById($id);
            $this->set("comment",$comment);
            $this->set('id',$id);
        }
        else
        {
            $this->addons = Array('row_manager');

            // Fetch all comments form 'Comment' model
            // and assign to template
            $comments = App::Model('Comment')->paging("type='Blog' ORDER BY id DESC",$this->get_config('default_pagination'));
            $this->set("comments",$comments);
        }

        $this->set("action",$action);
    }
}
