<?php

namespace common\modules\school\models;

use Yii;
use dosamigos\transliterator\TransliteratorHelper;

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 = 100;

    const IMAGES_FOLDER = '/uploads/lessons_docs/';

    public $errors;
    /**
     * @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'],
        ];
    }

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

    /**
     * @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 getUrl($image) 
    {
        return Yii::$app->params['frontUrl'].self::IMAGES_FOLDER.$image;
    }
    
    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 = $file;
                $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))
		        {
                    if(!in_array($file->filename, $this->filesUpload)){
                        unlink($this->getPath() . $file->filename);
                    }        	
		        }
		        $file->delete();
    		}
    	}             
    }
    
    public function getFilename($name) {
      $filename = str_replace("-", "_", $name);
      $filename = TransliteratorHelper::process($filename, '', 'en');
      $filename = preg_replace('/[^0-9a-z_\.]/i', '', $filename);
      return $filename;
    }
}
