<?php
namespace controllers;

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

class PageController extends CRUDController {

    protected $modelClassName = 'models\Page';

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

    public function doList() {
        parent::doList();
        $this->pages = $this->models;
        $i18n = IoC::resolve( 'i18n' );
        $this->title = $i18n->__( 'list' );
    }

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

    public function doUpdateform() {
        parent::doUpdateform();
        $this->title = $this->page->name;
    }

    public function doShow() {
        $this->page = Page::findOne( '*', ['name' => $this->request->getAttribute( 'name' )] );
        if ( empty( $this->page ) ) {
            $this->forward( self::class, 'addform' );
        }
        $this->title = $this->page->name;
        $this->page->content = preg_replace_callback( '/\.\{color:([A-Z][a-z0-9]+){2,}\}/', function( $matches ) {
            return strtolower( $matches[0] );
        }, $this->page->content );
        $this->page->content = preg_replace( '/([A-Z][a-zà-ÿ0-9]+){2,}/', '$0:[$0]', $this->page->content );
    }

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

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

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