<?php

namespace modules\activities\models;

use Yii;
use yii\helpers\{FileHelper, Json};

/**
 * This model extends product data into a json array".
 *
 */
class ActivitiesData extends \yii\base\Model
{
    const FOLDER_PATH = '@modules/activities/models/Customs';
    const CLASS_PATH = '\\modules\\activities\\models\\Customs\\';
    public function rules()
    {
        return [
          [['*'], 'safe'],
        ];
    }
    public function attributes()
    {
        $types = self::Types();
        return $types;
    }
    public function attributeLabels()
    {
        $labels = [];
        foreach (self::Types() as $name => $value) {
            $labels[$name] = UcWords($value);
        }
        return $labels;
    }

    public static function Types()
    {
        $types = [];
        $data = FileHelper::findFiles(($dir = Yii::getAlias(self::FOLDER_PATH)), ['only' => ['*.php'], 'recursive' => true]);
        if ($data) {
            foreach ($data as $file) {  
                $details = pathinfo($dir . $file);
                $name = $details['filename'];
                $tclass = self::CLASS_PATH  . UcWords($name);
                $class = $tclass::className();
                $types[$name] = $name;
            }
        }
        return $types;
    }

    public static function loadData($modeldata)
    {
        $_this = new self();
        $output = [];
        $content = is_string($modeldata->data) ? Json::decode($modeldata->data, 0) : $modeldata->data;
        foreach (self::Types() as $field => $value) {
            $class = self::CLASS_PATH . 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[$field] = method_exists($model, 'afterLoad') ? $model->afterLoad($modeldata) : $model;            
        }
        return $output;
    }
}
