<?php

namespace backend\models;

use Yii;
use Yii\helpers\Json;

/**
 * This model extends product data into a json array".
 *
 */
class AccountsData extends \yii\base\Model
{
    private $location = '';
    private $dir = '';
    private $modelpath = '';
    private $dynamicFields = [];
    const type = 'accounts';


    public function __construct()
    {
        static $cachedData = null;
        if ($cachedData === null) {
            $dir = \in_array('frontend', array_keys(System::getAliases())) ? Yii::getAlias('@frontend') . '/models/' . self::type . '/' : null;
            $this->location = \file_exists($dir) ? 'frontend' : 'backend';
            $this->dir = Yii::getAlias('@' . $this->location) . '/models/' . self::type . '/';
            $this->modelpath = '\\' . $this->location . '\\models\\' . self::type . '\\';
            $cachedData = array_diff(scandir($this->dir), ['.','..', '.gitkeep', '.bak']);
        }
        foreach ($cachedData as $file) {
            $name = str_replace('.php', '', $file);
            $this->dynamicFields[$name] = '';
        }
    }

    public function rules()
    {
        return [
        [['*'], 'safe'],
        ];
    }
    public function attributes()
    {
        return self::Types();
    }
    public function attributeLabels()
    {
        $labels = [];
        foreach (self::Types() as $name => $value) {
            $labels[$name] = UcWords($value);
        }
        return $labels;
    }
    public function Types()
    {
        $files = [];
        $data = array_diff(scandir($this->dir), ['.','..', '.gitkeep', '.bak']);
        if ($data) {
            foreach ($data as $file) {
                $details = pathinfo($this->dir . $file);
                if (isset($details['extension']) && $details['extension'] == 'php') {
                    $name = str_replace('.php', '', $file);
                    $tclass = '\\' . $this->location . '\\models\\' . self::type . '\\' . $name;
                    $class = $tclass::className();
                    $types[$name] = $name;
                }
            }
        }
        return $types;
    }
    public static function Data($data)
    {
        $output = new self();
        $content = Json::decode($data, 0);
        foreach ($output->types() as $field => $value) {
            $class = $output->modelpath . UcWords($field);
            $model = new $class();
            if (is_object($content) && property_exists($content, $field)) {
                foreach ($model->attributes as $attfield => $value) {
                    is_object($content->$field) && property_exists($content->$field, $attfield) ? $model->$attfield = $content->$field->$attfield : false;
                }
            }
            $output->dynamicFields[$field] = $model;
        }
        return $output->dynamicFields;
    }
}
