<?php

namespace App\FormModel\admin\news;

use App\Model\AppNews;

class NewsFormModel
{

    private array $attributes = [];

    public function setAttributes(array $attr, $allowProp = [])
    {
        if (!$allowProp) {
            $this->attributes = $attr;
        }

        foreach($allowProp as $prop) {
            if (isset($attr[$prop])) {
                $this->attributes[$prop] = $attr[$prop];
            }
        }
        return $this;
    }

    public function insert()
    {
        $model = new AppNews();
        $this->attributes['column_tag'] = $this->attributes['column1'] ?: 0;
        $this->attributes['second_column'] = $this->attributes['column2'] ?: 0;
        unset($this->attributes['column1']);
        unset($this->attributes['column2']);
        $model->setRawAttributes($this->attributes);
        $model->save();
    }

    public function update()
    {
        $model = AppNews::find($this->attributes['id']);
        $model->title = $this->attributes['title'];
        $model->keywords = $this->attributes['keywords'];
        $model->description = $this->attributes['description'];
        $model->cover = $this->attributes['cover'];
        $model->content = $this->attributes['content'];
        $model->platform = $this->attributes['platform'];
        $model->column_tag = $this->attributes['column1'] ?: 0;
        $model->second_column = $this->attributes['column2'] ?: 0;
        $model->save();
    }
}