<?php
namespace models;

/**
 * Template model class
 * @author Jérôme Brilland
 * @version 3.0
 * @copyright (c) 2018-2021, Jérôme Brilland
 * @license http://www.gnu.org/licenses/gpl.txt GNU General Public License
 */
class Template extends \ActiveRecord {
    
    public function validate() {
        $i18n = \IoC::resolve( 'i18n' );
        $this->validateMaxLength( 'name', 100, $i18n->__( 'too_long_name', 100 ) );
        $this->validateNotEmpty( 'name', $i18n->__( 'name_cannot_be_empty' ) );
        $this->validateMaxLength( 'content_type', 100, $i18n->__( 'too_long_name', 100 ) );
        $this->validateNotEmpty( 'content', $i18n->__( 'content_cannot_be_empty' ) );
        if ( $this->isNewRecord() || $this->isAttributeChanged( 'name' ) ) {
            $this->validateUnique( 'name', $i18n->__( 'template_already_exists', $this->name ) );
        }
    }

    protected function beforeSave() {
        $this->name = trim( $this->name );
        $this->last_modified = time();
    }

    public static function findLastModifiedTemplates( $limit = 5 ) {
        return Template::findMany( ['template_id', 'name', 'updated_at'], ['LIMIT'=> $limit, 'ORDER' => ['updated_at' => 'DESC']] );
    }

    public static function findLastCreatedTemplates( $limit = 5 ) {
        return Template::findMany( ['template_id', 'name', 'created_at'], ['LIMIT'=> $limit, 'ORDER' => ['created_at' => 'DESC']] );
    }

    public function isUsed() {
        $isUsed = Page::exists( ['template_id' => $this->template_id ] );
        if ( !$isUsed ) {
            \IoC::resolve( 'eventmediator' )->trigger( 'check_template_used', [$this, &$isUsed] );
        }
        return $isUsed;
    }
}
