<?php

namespace frontend\models;

use common\components\Helper;
use common\models\Customer;
use common\models\User;
use yii\base\Model;
use Yii;

/**
 * Signup form
 * @property  \common\models\Customer $customer
 */
class PasswordChangeModel extends Model
{
    public $email;
    public $customer;
    public $card;
    public $companyName;
    public $plainPassword;
    public $groupTrainingUrl;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [

            ['email', 'filter', 'filter' => 'trim'],
            ['email', 'required'],
            ['email', 'email'],
            ['email', 'string', 'max' => 255],
            ['email', 'validateUnique'],

        ];
    }

    public function validateUnique($attribute, $params)
    {
        $customerWithProvidedEmail = Customer::findOne(['email' => $this->email]);
        if (isset($customerWithProvidedEmail)) {
            if ($customerWithProvidedEmail->id_customer != $this->customer->id_customer) {
                $this->addError("email", "Az e-mail cím már  használatban van");
            }
        }
    }

    /**
     * Signs user up.
     *
     * @return boolean
     */
    public function changePassword()
    {
        if ($this->validate()) {

            $this->customer->email = $this->email;
            $this->plainPassword = Helper::generateRandomString(
                8,
                "0123456789ABCDEFGHIJKLMNOPQRSTUVWXabcdefghijklmnopqrstuvwx"
            );
            $this->customer->setPassword($this->plainPassword);

            if ($this->customer->save(false)) {

                $message = \Yii::$app->mailer->compose("customer_password_change", ['model' => $this]);

                $message
                    ->setFrom(["noreply@fitnessadmin.hu" => Helper::getCompanyName()])
                    ->setTo($this->customer->email)
                    ->setSubject("Értesítés - " . Helper::getCompanyName() . " - új jelszó")
                    ->send();

                \Yii::$app->session->setFlash('success', 'Email módosítva, jelszó elküldve');

                return true;
            }
        }

        return false;
    }
}
