<?php

namespace backend\modules\company\models;

use common\models\FieldsValue;
use common\models\FieldsValueNew;
use Yii;

class Company extends \common\models\Company
{
    public $fields;

    public function init()
    {
        parent::init();

        $fieldValue = FieldsValueNew::find()
            ->where(
                [
                    'item_id' => \Yii::$app->request->get('id'),
                    'item_type' => FieldsValueNew::TYPE_COMPANY,
                ])
            ->all();
        $array = [];
        if(!empty($fieldValue)){
            foreach ($fieldValue as $item){
                array_push($array,
                    ['field_id' => $item->field_id,
                        'value' => $item->value,
                        'order' => $item->order,
                        'type_file' => $item->type_file,
                        'field_name' => $item->field->name]);
            }
            $this->fields = $array;
        }
        else{
            $this->fields = [
                [
                    'field_id'   => null,
                    'value'  => null,
                    'order' => null,
                    'field_name' => null,
                    'type_file' => null,
                ],
            ];
        }
    }

    public function behaviors()
    {
        return [
            'log' => [
                'class' => \common\behaviors\LogBehavior::class,
            ]
        ];
    }

    public function afterSave($insert, $changedAttributes)
    {
        $post = \Yii::$app->request->post('Company');

        FieldsValueNew::deleteAll(['item_id' => $this->id, 'item_type' => FieldsValueNew::TYPE_COMPANY]);

        foreach ( $post['fields'] as $item) {
            $fieldsValue = new FieldsValueNew();
            $fieldsValue->field_id = $item['field_id'];
            $fieldsValue->value = $item['value'];
            $fieldsValue->order = $item['order'];
            $fieldsValue->item_id = $this->id;
            $fieldsValue->item_type = FieldsValueNew::TYPE_COMPANY;
            if(is_file(Yii::getAlias('@frontend') . '/web/' . $item['value'])){
                $fieldsValue->type_file = 'file';
            }else{
                $fieldsValue->type_file = 'text';
            }

            $fieldsValue->save();
        }

        parent::afterSave($insert, $changedAttributes); // TODO: Change the autogenerated stub
    }
}