<?php

namespace backend\models;

use Yii;
use yii\base\Model;
use common\models\User;
use yii\base\Object;

/**
 * ContactForm is the model behind the contact form.
 */
class Profile extends Model
{
    public $firstname;
    public $lastname;
    public $middlename;
    public $username;
    public $password; 
    public $email;
    
    public function __construct()
    {
        parent::__construct();
        
        $this->lastname = \Yii::$app->user->identity->lastname;
        $this->firstname = \Yii::$app->user->identity->firstname;
        $this->middlename = \Yii::$app->user->identity->middlename;
        $this->username = \Yii::$app->user->identity->username;
        $this->email = \Yii::$app->user->identity->email;
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            // name, email, subject and body are required
            [['firstname', 'lastname', 'email', 'password', 'middlename', 'username'], 'required'],
            // email has to be a valid email address
            ['email', 'email'], 
        ];
    }

    public function saveProfile()
    { 
        if ($this->load(Yii::$app->request->post()))
        {
            $user = User::find()->where(['id' => Yii::$app->user->identity->id])->one();
            
            $user->lastname = $this->lastname;
            $user->firstname = $this->firstname;
            $user->middlename = $this->middlename;
            $user->username = $this->username;
            $user->email = $this->email;
            $user->password_hash = Yii::$app->security->generatePasswordHash($this->password); 

            $user->save();  
        }
    }

}
