<?php

namespace common\models;
use Yii;

/**
 * This is the model class for table "project_image".
 *
 * @property integer $project_image_id
 * @property integer $project_id
 * @property string $image
 * @property string $alt
 * @property string $title
 *
 * @property Project $project
 */
class ProjectImage extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'project_image';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['project_id'], 'required'],
            [['project_id'], 'integer'],
            [['image', 'alt', 'title'], 'string', 'max' => 255],
            [['project_id'], 'exist', 'skipOnError' => true, 'targetClass' => Project::className(), 'targetAttribute' => ['project_id' => 'project_id']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'project_image_id' => Yii::t('app', 'project_image_id'),
            'project_id' => Yii::t('app', 'project_id'),
            'image' => Yii::t('app', 'image'),
            'alt' => Yii::t('app', 'alt'),
            'title' => Yii::t('app', 'title'),
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getProject()
    {
        return $this->hasOne(Project::className(), ['project_id' => 'project_id']);
    }
    
    /**
     * fetch stored image file name with complete path
     * @return string
     */
    public function getImageFile()
    {
        return isset($this->image) ? '/storage/projects/' . $this->image : null;
    }
    
    /**
     * fetch stored image url
     * @return string
     */
    public function getImageUrl()
    {
        // return a default image placeholder if your source image is not found
        return isset($this->image) ? '/storage/projects/'. $this->image : '/storage/no-photo.png';
    }
    
    public function deleteImage() {
        $file = $this->getImageFile();
        
        // check if file exists on server
        if (empty($file) || !file_exists($file)) {
            return false;
        }
        
        // check if uploaded file can be deleted on server
        if (!unlink($file)) {
            return false;
        }
        
        // if deletion successful, reset your file attributes
        $this->image = null;
        $this->filename = null;
        
        return true;
    }
    
    public function beforeDelete()
    {
        if (parent::beforeDelete()) {
            $this->deleteImage();
            return true;
        } else {
            return false;
        }
    }
}
