<?php

namespace common\modules\analyticsSchool\models;

use Yii;
use yii\web\UploadedFile;

/**
 * This is the model class for table "analytics_school_lessons".
 *
 * @property integer $id
 * @property integer $course_id
 * @property string $name
 * @property string $video_link
 * @property string $content
 *
 * @property AnalyticsSchoolCourse $course
 */
class AnalyticsSchoolLesson extends \common\components\ActiveRecordModel
{
    public $filename = [];
    public $file = [];
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'analytics_school_lesson';
    }

    /**
     * @return string
     */
    public function name(){
        return 'Уроки';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['course_id', 'name', 'content'], 'required'],
            [['course_id'], 'integer'],
            [['filename', 'file'], 'safe'],
            [['video_link', 'content'], 'string'],
            [['name'], 'string', 'max' => 255],
            [['course_id'], 'exist', 'skipOnError' => true, 'targetClass' => AnalyticsSchoolCourse::className(), 'targetAttribute' => ['course_id' => 'id']],
        ];
    }

    public function validate($attributeNames = null, $clearErrors = true){
        if (!parent::validate($attributeNames = null, $clearErrors = true))
            return false;

        $files = UploadedFile::getInstances($this, 'file');
        foreach($files as $index=>$file) {
            if (isset($this->filename[$index])) {
                $model = new AnalyticsSchoolLessonFile();
                $model->document = $file;
                if (!$model->validate(['document'])) {
                    $this->addError('file', current(current($model->getErrors())));
                    return false;
                }
            }
        }

        return true;
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'course_id' => 'Курс',
            'name' => 'Название урока',
            'video_link' => 'Ссылка на видео',
            'content' => 'Материал урока',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCourse() {
        return $this->hasOne(AnalyticsSchoolCourse::className(), ['id' => 'course_id']);
    }

    /**
     * @return array
     */
    public function behaviors(){
        return [];
    }
}
