<?php


namespace app\modules\accesses\models;

use common\classes\Debug;
use common\models\FieldsValueNew;
use Yii;

/**
 * This is the model class for table "accesses".
 *
 * @property int $id
 * @property string $name
 * @property string $access
 */


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

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

        $fieldValue = FieldsValueNew::find()->where(
            [
                'item_id' => \Yii::$app->request->get('id'),
                'item_type' => FieldsValueNew::TYPE_ACCESS,
            ]
        )
            ->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 afterSave($insert, $changedAttributes)
    {
        $post = \Yii::$app->request->post('Aceesses');

        if ($post['fields']) {
            FieldsValueNew::deleteAll(['item_id' => $this->id, 'item_type' => FieldsValueNew::TYPE_ACCESS]);
            foreach ($post['fields'] as $item) {
                $item['value'] = urldecode($item['value']);

                $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_ACCESS;
                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
    }

}