<?php
    namespace common\modules\comment\models;

    use common\models\User;
    use yii\db\ActiveQuery;

    /**
     * Class Comment
     * @property bool    $guestComment
     * @property integer $comment_id
     * @property string  $text
     * @property int     $user_id
     * @property string  $user_name
     * @property string  $user_email
     * @property int     $comment_pid
     * @property int     $status
     * @property string  $date_add
     * @property string  $date_update
     * @property string  $date_delete
     * @property string  $model
     * @property int     $model_id
     * @property Rating  $rating
     * @property User    $user
     * @package common\modules\comment\models
     */
    class Comment extends \yii\db\ActiveRecord
        implements \common\modules\comment\interfaces\CommentInterface
    {

        const STATUS_HIDDEN = 0;
        const STATUS_DELETED = 2;
        const STATUS_ACTIVE = 1;
        const STATUS_PERSONAL = 3;

        const SCENARIO_USER = 'user';
        const SCENARIO_GUEST = 'guest';

        /**
         * @var bool
         */
        public $guestComment = true;

        public function rules()
        {
            return [
                [
                    [
                        'text',
                        'user_name',
                        'user_email',
                    ],
                    'required',
                ],
                [
                    [
                        'rating',
                    ],
                    'safe',
                ],
                [
                    [ 'user_email' ],
                    'email',
                ],
                [
                    [ 'user_name' ],
                    'string',
                ],
                [
                    [
                        'comment_id',
                        'comment_pid',
                    ],
                    'integer',
                ],
                [
                    [ 'status' ],
                    'default',
                    'value' => 1,
                ],
                [
                    [ 'comment_pid' ],
                    'exist',
                    'targetAttribute' => 'comment_id',
                    'filter'          => [
                        'model'    => $this->model,
                        'model_id' => $this->model_id,
                    ],
                ],
            ];
        }

        public function scenarios()
        {
            return [
                self::SCENARIO_GUEST => [
                    'user_name',
                    'user_email',
                    'text',
                    'comment_pid',
                ],
                self::SCENARIO_USER  => [
                    'text',
                    'comment_pid',
                ],
            ];
        }

        /**
         * @inheritdoc
         */
        public function behaviors()
        {
            return [
                [
                    'class'              => \yii\behaviors\TimestampBehavior::className(),
                    'createdAtAttribute' => 'date_add',
                    'updatedAtAttribute' => 'date_update',
                    'value'              => new \yii\db\Expression('NOW()'),
                ],
            ];
        }

        public function afterSave($insert, $changedAttributes)
        {
            if($this->model == User::className()) {
                if($user = User::findOne($this->model_id)) {
                    /**
                     * @var User $user
                     */
                    $user->updateRating();
                }
            }
            parent::afterSave($insert, $changedAttributes);
        }

        /**
         * @inheritdoc
         */
        public static function tableName()
        {
            return '{{%comment}}';
        }

        /**
         * @inheritdoc
         */
        public function attributeLabels()
        {
            return [
                'text'       => \Yii::t('app', 'Комментарий'),
                'user_name'  => \Yii::t('app', 'Имя'),
                'user_email' => \Yii::t('app', 'Email'),
            ];
        }

        public function getGuestComment()
        {
            return $this->guestComment;
        }

        public function setGuestComment($value)
        {
            $this->guestComment = $value;
        }

        /**
         * @param string  $model
         * @param integer $model_id
         *
         * @return ActiveQuery
         */
        public function getComments($model, $model_id)
        {
            return $this->find()
                        ->where([
                            'comment.model'    => $model,
                            'comment.model_id' => $model_id,
                            'comment.status'   => 1,
                        ])->with('rating');
        }

        public function postComment()
        {
            if($this->checkCreate()) {
                if($this->insert()) {
                    $this->clearSafe();
                    return true;
                } else {
                    return false;
                }
            } else {
                $this->addError('comment_id', 'You can`t post comment here');
                return false;
            }
        }

        public function updateComment()
        {
            if($this->checkUpdate()) {
                if(empty( $this->comment_id )) {
                    $this->addError('comment_id', 'Comment ID not found');
                    return false;
                } else {
                    if($this->update()) {
                        $this->clearSafe();
                        return true;
                    } else {
                        return false;
                    }
                }
            } else {
                $this->addError('comment_id', 'You can`t update this post');
                return false;
            }
        }

        public function deleteComment()
        {
            if($this->checkDelete()) {
                if(empty( $this->comment_id )) {
                    $this->addError('comment_id', 'Comment ID not found');
                    return false;
                } else {
                    if($this->status == self::STATUS_DELETED) {
                        return false;
                    }
                    $this->status = self::STATUS_DELETED;
                    if($this->update()) {
                        $this->clearSafe();
                        return true;
                    } else {
                        return false;
                    }
                }
            } else {
                $this->addError('comment_id', 'You can`t delete this post');
                return false;
            }
        }

        public function checkCreate()
        {
            if($this->getGuestComment()) {
                return true;
            } else {
                return \Yii::$app->user->can(\common\modules\comment\Permissions::CREATE, [
                    'model'    => $this->model,
                    'model_id' => $this->model_id,
                ]);
            }
        }

        public function checkUpdate()
        {
            if($this->scenario == self::SCENARIO_GUEST) {
                return false;
            } else {
                return \Yii::$app->user->can(\common\modules\comment\Permissions::UPDATE, [
                    'model'    => $this->model,
                    'model_id' => $this->model_id,
                ]) || \Yii::$app->user->can(\common\modules\comment\Permissions::UPDATE_OWN, [
                    'model'    => $this->model,
                    'model_id' => $this->model_id,
                ]);
            }
        }

        public function checkDelete()
        {
            if($this->scenario == self::SCENARIO_GUEST) {
                return false;
            } else {
                return \Yii::$app->user->can(\common\modules\comment\Permissions::DELETE, [
                    'model'    => $this->model,
                    'model_id' => $this->model_id,
                ]) || \Yii::$app->user->can(\common\modules\comment\Permissions::DELETE_OWN, [
                    'model'    => $this->model,
                    'model_id' => $this->model_id,
                ]);
            }
        }

        protected function clearSafe($setNew = true)
        {
            $safe = $this->safeAttributes();
            $count = count($safe);
            $values = array_fill(0, $count, NULL);
            $result = array_combine($safe, $values);
            $this->setAttributes($result);
            $this->setIsNewRecord($setNew);
        }

        public function getParent()
        {
            return $this->hasOne(self::className(), [ 'comment_id' => 'comment_pid' ]);
        }

        public function getAuthor()
        {
            //            if($this->user_id != NULL) {
            return $this->hasOne(\common\models\User::className(), [ 'id' => 'user_id' ]);
            //            } else {
            //                return ['firstname' => $this->user_name, 'email' => $this->user_email];
            //            }
        }

        public function checkRating()
        {
            $rating = $this->hasOne(\common\modules\comment\models\Rating::className(), [
                'model_id' => 'comment_id',
            ])
                           ->andWhere([
                               'model' => $this->className(),
                           ])
                           ->one();
            if(!$rating instanceof \common\modules\comment\models\Rating && !empty($this->primaryKey)) {
                $rating = new \common\modules\comment\models\Rating([
                    'model'    => $this->className(),
                    'model_id' => $this->comment_id,
                    'user_id'  => $this->user_id,
                ]);
                $rating->save();
            }
        }

        public function getRating()
        {
            $this->checkRating();
            return $this->hasOne(\common\modules\comment\models\Rating::className(), [
                'model_id' => 'comment_id',
            ])
                        ->andWhere([ 'model' => $this->className() ]);
        }

        public function hasRating($return = true)
        {
            $rating = $this->hasOne(\common\modules\comment\models\Rating::className(), [
                'model_id' => 'comment_id',
            ])
                           ->andWhere([ 'model' => $this->className() ])
                           ->andWhere([
                               'not',
                               [ 'value' => NULL ],
                           ])
                           ->one();
            if($return) {
                return $rating;
            } else {
                return $rating ? true : false;
            }
        }

        public function getUser()
        {
            return $this->hasOne(User::className(), [ 'id' => 'user_id' ]);
        }

    }
