<?php

namespace app\models;

use Yii;
use yii\behaviors\TimestampBehavior;
use yii\helpers\FileHelper;
use yii\image\drivers\Image;
use yii\db\ActiveRecord;

/**
 * This is the model class for table "images".
 *
 * @property integer $id
 * @property integer $related_id
 * @property string $path
 * @property string $type
 * @property integer $date_create
 */
class Images extends ActiveRecord
{
    public $_file;
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'images';
    }

    public function behaviors()
    {
        return [
            'timestamp' => [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => 'date_create',
                ]
            ]
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['related_id', 'type'], 'required'],
            [['related_id', 'date_create'], 'integer'],
            [['path'], 'string', 'max' => 255],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'related_id' => Yii::t('app', 'Related ID'),
            'path' => Yii::t('app', 'Path'),
            'date_create' => Yii::t('app', 'Date Create'),
            'type' => Yii::t('app', 'Type'),
        ];
    }

    public function upload()
    {
        if (!$this->validate()) {
            return false;
        }
        $path = "uploads/images/{$this->related_id}/";
        $croppedPath = $path . '75x75/';
        if (!is_dir($path)) {
            FileHelper::createDirectory($path);
        }
        if (!is_dir($croppedPath)) {
            FileHelper::createDirectory($croppedPath);
        }
        $time = time();
        $this->path = "{$path}{$this->_file->basename}_{$time}.{$this->_file->extension}";
        if ($this->_file->saveAs($this->path)) {
            /** @var Image $img * */
            $img = Yii::$app->image->load($this->path);

            $img->background('#fff', 0);
            $img->resize('75', '75', Image::INVERSE);
            $img->crop('75', '75');
            $img->save($croppedPath . "{$this->_file->basename}_{$time}.{$this->_file->extension}");

            (new Images([
                'type' => 'thumbnail',
                'path' => $croppedPath . "{$this->_file->basename}_{$time}.{$this->_file->extension}",
                'related_id' => $this->related_id
            ]))->save(false);
        }
        return $this->save(false);
    }

    public function copy($related_id)
    {
        $path = str_replace($this->related_id, $related_id, $this->path);

        $directoryPath = explode('/', $path);

        array_pop($directoryPath);

        $directoryPath = implode('/', $directoryPath);

        FileHelper::createDirectory($directoryPath);

        copy($this->path, $path);

        $model = new Images();
        $data = $this->attributes;
        $data['path'] = $path;
        $data['related_id'] = $related_id;

        return $model->load($data, '') && $model->save(false);
    }

    public function beforeDelete()
    {
        if ($this->thumbnail && is_file($this->thumbnail->path)) {
            unlink($this->thumbnail->path);
        }
        parent::beforeDelete();
    }


}
