<?php

namespace app\models;

use Yii;
use yii\base\Model;
use yii\db\ActiveRecord;

/**
 * @package app\models
 *
 * @property string $first_name
 * @property string $last_name
 * @property string $patronymic
 * @property string $phone
 * @property string $email
 * @property string $address
 * @property string $current_password
 * @property string $new_password
 * @property string $confirm_password
 */
class ProfileForm extends Model
{
    public $first_name;
    public $last_name;
    public $patronymic;
    public $phone;
    public $email;
    public $address;
    public $count;
    public $current_password;
    public $new_password;
    public $confirm_password;

    private $_user;


    public function rules()
    {
        return [
            [['first_name', 'last_name', 'patronymic', 'phone', 'email', 'address'], 'required'],

            [['first_name', 'last_name', 'patronymic', 'phone', 'address'], 'string', 'max' => 255],
            ['count', 'integer'],
            ['email', 'email'],
            ['email', 'string', 'max' => 255],
            ['email', 'unique', 'targetClass' => User::class, 'filter' => function($query) {
                $query->andWhere(['not', ['id' => Yii::$app->user->id]]);
            }, 'message' => 'Этот email уже используется другим пользователем.'],

            ['current_password', 'validateCurrentPassword'],
            ['new_password', 'string', 'min' => 10],
            ['confirm_password', 'compare', 'compareAttribute' => 'new_password', 'message' => 'Пароли не совпадают'],

            [['new_password', 'confirm_password'], 'required', 'when' => function($model) {
                return !empty($model->current_password);
            }, 'whenClient' => "function (attribute, value) {
                return $('#profileform-current_password').val() != '';
            }"],
        ];
    }


    public function attributeLabels()
    {
        return [
            'first_name' => 'Имя',
            'last_name' => 'Фамилия',
            'patronymic' => 'Отчество',
            'phone' => 'Телефон',
            'count' => 'Количество людей, проживающих по данному адресу',
            'address' => 'Адрес',
            'current_password' => 'Текущий пароль',
            'new_password' => 'Новый пароль',
            'confirm_password' => 'Подтверждение нового пароля',
        ];
    }


    public function validateCurrentPassword($attribute, $params)
    {
        if (!empty($this->current_password)) {
            $user = $this->getUser();
            if (!$user || !$user->validatePassword($this->current_password)) {
                $this->addError($attribute, 'Текущий пароль указан неверно.');
            }
        }
    }


    public function loadUserData()
    {
        $user = $this->getUser();
        if ($user) {
            $this->first_name = $user->first_name;
            $this->last_name = $user->last_name;
            $this->patronymic = $user->patronymic;
            $this->phone = $user->phone;
            $this->email = $user->email;
            $this->address = $user->address;
            $this->count = $user->count;
        }
    }


    public function save()
    {
        if (!$this->validate()) {
            return false;
        }

        $user = $this->getUser();
        if (!$user) {
            return false;
        }

        $user->first_name = $this->first_name;
        $user->last_name = $this->last_name;
        $user->patronymic = $this->patronymic;
        $user->phone = $this->phone;
        $user->email = $this->email;
        $user->address = $this->address;
        $user->count = $this->count;

        if (!empty($this->new_password)) {
            $user->password = Yii::$app->security->generatePasswordHash($this->new_password);
        }

        return $user->save();
    }

    protected function getUser()
    {
        if ($this->_user === null) {
            $this->_user = User::findOne(Yii::$app->user->id);
        }
        return $this->_user;
    }
}