<?php

namespace app\models;

use Yii;
use yii\base\Model;
use yii\web\UploadedFile;

class ProfileForm extends Model
{
    public $name;
    public $last_name;
    public $email;
    public $phone;
    public $address;

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['name', 'last_name', 'email', 'phone'], 'required'],
            ['email', 'email'],
            ['email', 'unique', 'targetClass' => User::class, 'filter' => ['!=', 'id', Yii::$app->user->id], 'message' => 'Этот email уже используется.'],
            [['phone', 'address'], 'string', 'max' => 255],
            [['name', 'last_name'], 'string', 'max' => 100],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'name' => 'Имя',
            'last_name' => 'Фамилия',
            'email' => 'Email',
            'phone' => 'Телефон',
            'address' => 'Адрес доставки',
        ];
    }
    public function loadFromUser($user)
    {
        $this->name = $user->name ?? '';
        $this->last_name = $user->last_name ?? '';
        $this->email = $user->email ?? '';
        $this->phone = $user->phone ?? '';
        $this->address = $user->address ?? '';
    }

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

        $user->name = $this->name;
        $user->last_name = $this->last_name;
        $user->email = $this->email;
        $user->phone = $this->phone;
        $user->address = $this->address;
        return $user->save();
    }
}