<?php

namespace common\modules\school\models;

use Yii;

use common\modules\school\models\Lessons;

class Courses extends \common\components\ActiveRecordModel
{
    const PAGE_SIZE = 10;

    const TYPE_IT = 1;
    const TYPE_IM = 2;
    const TYPE_SB = 3;
    const TYPE_DV = 4;

    const IMAGES_FOLDER = '/uploads/courses/';

    public $upload_image;

    public static $type_list = [
        self::TYPE_IT => 'Для сотрудников it-отрасли',
        self::TYPE_IM => 'Для интернет-маркетологов',
        self::TYPE_SB => 'Для собственников бизнеса',
        self::TYPE_DV => 'в разработке',
    ];

    public static function tableName()
    {
        return 'courses';
    }

    public function name()
    {
        return 'Курсы';
    }

    public function attributeLabels() 
    {
        return [
            'title' => 'Заголовок',
            'description' => 'Описание',
            'type' => 'Тип курса',
            'upload_image' => 'Изображения',
            'spec_proposition' => 'Специальное предложение',
            'description_for_course' => 'Описание для страницы курса'
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['title', 'description', 'type'], 'required'],
            [['type', 'spec_proposition'], 'integer'],
            [['title'], 'string', 'max' => 150],
            [['image'], 'string', 'max' => 100],
            [['description', 'description_for_course'], 'safe'],
            [['upload_image'], 'file', 'skipOnEmpty' => true, 'extensions' => 'png, jpg, jpeg, gif'],
        ];
    }

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

    public function beforeDelete()
    {
        if (parent::beforeDelete()) 
        {
            $this->deleteFiles();
            return true;
        } 
        else 
        {
            return false;
        }
    }

    public function getLessons()
    {
        return $this->hasMany(Lessons::className(), ['course_id' => '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 deleteFiles()
    {
        if($this->image){
            if(file_exists($this->getPath() . $this->image)){
                unlink($this->getPath() . $this->image);
            }
        }
    }
    
    public function getClassCourse($type) 
    {
        switch ($type) {
            case Courses::TYPE_IT: $class = 'it'; break;
            case Courses::TYPE_IM: $class = 'im'; break;
            case Courses::TYPE_SB: $class = 'sb'; break;
            case Courses::TYPE_DV: $class = 'dv'; break;
        }
        return $class;
    }
}
