<?php

namespace common\modules\school\models;

use Yii;
use common\modules\school\components\Utilities;
use common\modules\school\models\Courses;
use common\modules\testings\models\Test;
use common\modules\school\models\LessonImage;

/**
 * This is the model class for table "testings_questions_image".
 *
 * @property integer $id
 * @property integer $question_id
 * @property string $filename
 */
class Lessons extends \common\components\ActiveRecordModel
{
    const PAGE_SIZE = 10;

    const IMAGES_FOLDER = '/uploads/lessons_docs/';

	public $filesUpload;
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'lessons';
    }

    public function name()
    {
        return 'Уроки';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['title', 'video_id', 'course_id', 'number'], 'required'],
            [['title'], 'string', 'max' => 150],
            [['video_id'], 'string', 'max' => 100],
            [['course_id', 'number', 'test_id'], 'integer'],
            [['text'], 'safe'],
            [['filesUpload'], 'file', 'skipOnEmpty' => true, 'extensions' => 'png, jpg, jpeg, gif, rar, ai, ppt, doc, docx', 'maxFiles' => 10],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'test_id' => 'Тест',
            'title' => 'Заголовок',
            'text' => 'Полезные материалы',
            'video_id' => 'Код видео',
            'course_id' => 'Курс',
            'number' => 'Номер урока',
            'filesUpload' => 'Документы'
        ];
    }

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

    public function getCourse()
    {
        return $this->hasOne(Courses::className(), ['id' => 'course_id']);
    }
    
    public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)) {
            $this->video_id = $this->getVideoId();

            return $this->video_id;
        }
        else {
            return false;
        }
    }
    
    public function getVideoId()
    {
        if ($this->video_id) {
            if (Utilities::checkUrl($this->video_id)) {
                if (strrpos($this->video_id, '=')){
                    $this->video_id=substr($this->video_id, strrpos($this->video_id, '=')+1);
                }
            }
             return $this->video_id;
        }
        else {    
            return false;
        }
    }    
    
    public function getFiles()
    {
        return $this->hasMany(LessonImage::className(), ['lesson_id' => 'id']);
    }

    public function getTest()
    {
        return $this->hasOne(Test::className(), ['id' => 'test_id']);
    }
    
    public function getPath() 
	{
		return Yii::getAlias('@frontend/web') . self::IMAGES_FOLDER;
	}
    
    public function upload()
    {
        if ($this->validate()) 
        {
        	if(!file_exists($this->getPath()))
            {
                mkdir($this->getPath(), 0777, true);
            }

            foreach ($this->filesUpload as $file) 
            {
            	$filename = date('dmYHis-') . uniqid() . '.' . $file->extension;
                $file->saveAs($this->getPath() . $filename);

                $image = new LessonImage();
                $image->lesson_id = $this->id;
                $image->filename = $filename;
                $image->save();
            }

            return true;
        } 
        else 
        {
            return false;
        }
    }
    
    public function deleteFiles()
    {
    	if($this->files)
    	{
    		foreach ($this->files as $file) 
    		{
    			if(file_exists($this->getPath() . $file->filename))
		        {
		        	unlink($this->getPath() . $file->filename);
		        }
		        $file->delete();
    		}
    	}
    }
}
