<?php
namespace controllers;

use \CRUDController;
use models\Page;
use \IoC;

class PageController extends CRUDController {

    protected $modelClassName = 'models\Page';
    
    protected $itemsPerPage = 15;

    protected function beforeFilter() {
        if ( in_array( $this->request->getAttribute( 'action' ), ['updateform', 'update', 'delete'] ) ) {
            $page = Page::findOne( ['page_id'], ['title' => $this->request->getAttribute( 'title' )] );
            if ( empty( $page ) ) {
                $this->forward( 'controllers\\ErrorController', '404' );
            }
            $this->request->setAttribute( 'id', $page->page_id );
        }
    }

    public function doList() {
        parent::doList();
        $this->pages = $this->models;
        $i18n = IoC::resolve( 'i18n' );
        $this->title = $i18n->__( 'list' );
        if ( $this->request->hasParameter( 'page' ) ) {
            if ( $this->paginator->isValidPage( $this->request->getParameters()->getInt( 'page' ) ) ) {
                $this->render( 'ajax_pages.html' );
            } else {
                exit();
            }
        }
    }
    
    public function doSearch() {
        $keywords = strtolower( $this->request->getParameters()->getString( 'keywords' ) );
        $this->where = ['OR' => ['title[~]' => $keywords, 'content[~]' => $keywords]];
        $this->doList();
        $this->render( 'list.html' );
    }

    public function doAddform() {
        $i18n = IoC::resolve( 'i18n' );
        $this->title = $i18n->__( 'create_new_page' );
        parent::doAddform();
        if ( empty( $this->page->title ) ) {
            $this->page->title = $this->request->getAttribute( 'title', '' );
        }
        $this->originalTitle = $this->request->getAttribute( 'title' );
    }

    public function doUpdateform() {
        parent::doUpdateform();
        $this->originalTitle = $this->request->getAttribute( 'title' );
        $this->title = $this->originalTitle;
    }

    public function doShow() {
        $this->page = Page::findOne( '*', ['title' => $this->request->getAttribute( 'title' )] );
        if ( empty( $this->page ) ) {
            $this->forward( self::class, 'addform' );
        }
        $this->title = $this->page->title;
    }

    protected function afterAdd() {
        $this->redirect( BASE_URL . '/' . $this->model->title );
    }

    protected function afterUpdate() {
        $this->redirect( BASE_URL . '/' . $this->model->title );
    }

    protected function afterDelete() {
        $this->redirect( BASE_URL . '/list' );
    }
}
