<?php

namespace common\modules\product\models;

use Yii;
use yii\web\UploadedFile;

/**
 * This is the model class for table "product_image".
 *
 * @property integer $product_image_id
 * @property integer $product_id
 * @property integer $product_variant_id
 * @property string $image
 * @property string $alt
 * @property string $title
 * @property Product $product
 * @property ProductVariant $productVariant
 */
class ProductImage extends \yii\db\ActiveRecord
{
    public $imageUpload;
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'product_image';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['product_id'], 'required'],
            [['product_image_id', 'product_id', 'product_variant_id'], 'integer'],
            [['alt', 'title', 'image'], 'string', 'max' => 255],
            [['product_id'], 'exist', 'skipOnError' => true, 'targetClass' => Product::className(), 'targetAttribute' => ['product_id' => 'product_id']],
            [['product_variant_id'], 'exist', 'skipOnError' => true, 'targetClass' => ProductVariant::className(), 'targetAttribute' => ['product_variant_id' => 'product_variant_id']],
            [['imageUpload'], 'safe'],
            [['imageUpload'], 'file', 'extensions' => 'jpg, gif, png'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'product_image_id' => Yii::t('product', 'Product Image ID'),
            'product_id' => Yii::t('product', 'Product ID'),
            'product_variant_id' => Yii::t('product', 'Product Variant ID'),
            'product' => Yii::t('product', 'Product'),
            'product' => Yii::t('product', 'Product'),
            'product_variant' => Yii::t('product', 'Product Variant'),
            'image' => Yii::t('product', 'Image'),
            'alt' => Yii::t('product', 'Alt'),
            'title' => Yii::t('product', 'Title'),
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getProduct()
    {
        $return = $this->hasOne(Product::className(), ['product_id' => 'product_id']);
        if (empty($return)) {
            $return = $this->productVariant->product_id;
        }
        return $return;
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getProductVariant()
    {
        return $this->hasOne(Product::className(), ['product_variant_id' => 'product_variant_id']);
    }

    /**
     * @inheritdoc
     * @return ProductImageQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new ProductImageQuery(get_called_class());
    }

    /**
     * fetch stored image file name with complete path
     * @return string
     */
    public function getImageFile()
    {
        return isset($this->image) ? '/storage/products/' . $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/products/'. $this->image : '/storage/no_photo.png';
    }

    /**
     * Process upload of image
     *
     * @return mixed the uploaded image instance
     */
    public function uploadImage() {
        // get the uploaded file instance. for multiple file uploads
        // the following data will return an array (you may need to use
        // getInstances method)
        $image = UploadedFile::getInstance($this, 'imageUpload');

        // if no image was uploaded abort the upload
        if (empty($image)) {
            return false;
        }

        // store the source file name
        $this->filename = $image->name;
        $ext = end((explode(".", $image->name)));

        // generate a unique file name
        $this->image = Yii::$app->security->generateRandomString().".{$ext}";

        // the uploaded image instance
        return $image;
    }

    /**
     * Process deletion of image
     *
     * @return boolean the status of deletion
     */
    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;
    }
}
