<?php

namespace backend\modules\company\models;

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

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,
                        'field_name' => $item->field->name]);
            }
            $this->fields = $array;
        }
        else{
            $this->fields = [
                [
                    'field_id'   => null,
                    'value'  => null,
                    'order' => null,
                    'field_name' => null,
                ],
            ];
        }
    }

    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) {
            $fildsValue = new FieldsValueNew();
            $fildsValue->field_id = $item['field_id'];
            $fildsValue->value = $item['value'];
            $fildsValue->order = $item['order'];
            $fildsValue->item_id = $this->id;
            $fildsValue->item_type = FieldsValueNew::TYPE_COMPANY;

            $fildsValue->save();
        }

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