<?php
namespace PortalPeople\documentdesigner\models;

use Yii;
use yii\db\ActiveRecord;

/**
 * DocumentLayout model for storing document designs securely
 */
class DocumentLayout extends ActiveRecord
{
    public static function tableName()
    {
        return 'document_layouts';
    }

    /**
     * Validation rules for safe input
     */
    public function rules()
    {
        return [
            [['name', 'content'], 'required'],
            ['name', 'string', 'max' => 128],
            ['content', 'string'],
            ['type', 'in', 'range' => ['html', 'url']],
        ];
    }

    /**
     * Sanitize content before saving
     */
    public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)) {
            // Strip dangerous tags if HTML
            if ($this->type === 'html') {
                $this->content = strip_tags($this->content, '<div><span><p><table><tr><td><b><i><u><br><img><style>');
            }
            // Validate URL if type=url
            if ($this->type === 'url') {
                $this->content = filter_var($this->content, FILTER_SANITIZE_URL);
            }
            return true;
        }
        return false;
    }
}
