<?php

namespace app\models;

use Yii;
use app\models\Profile;
use dektrium\user\models\RegistrationForm as BaseRegistrationForm;

class RegistrationForm extends BaseRegistrationForm
{
    public $role;
    public $fio;
    public $at_org;
    public $org_type;
    public $member_phone;
    public $fax;
    public $firma_full;
    public $inn;
    public $zkpo;
    public $u_address;
    public $f_address;
    public $member;
    public $phone;
    public $member_email;
    public $site;
    // public $captcha;
    public $repeatpassword;

    // public function rules()
    // {
    //     $rules = parent::rules();
    //     $rules[] = [['role', 'fio', 'at_org', 'org_type', 'member_phone', 'phone', 'member_email', 'email', 'username', 'password'], 'required'];
    //     $rules[] = [['fax', 'site', 'member', 'repeatpassword'], 'safe'];
    //     $rules[] = ['role', 'in', 'range' => [1, 2]];
    //     $rules[] = ['org_type', 'in', 'range' => ['entity', 'individual', 'fop']];
    //     $rules[] = ['member_email', 'email'];
    //     // $rules[] = ['captcha', 'captcha', 'captchaAction' => 'registration/captcha'];
    //     $rules[] = ['repeatpassword', 'compare', 'compareAttribute' => 'password', 'message' => Yii::t('app', "Passwords don't match")];
    //     $rules[] = [['firma_full', 'inn', 'zkpo', 'u_address', 'f_address'], 'required', 'when' => function ($model) {
    //         return $model->role == 1;
    //     }, 'whenClient' => "function(attribute, value) {
    //         return $('#registrationform-role input:checked').val() == '1';
    //     }"];
    //     $rules[] = [['firma_full', 'inn', 'zkpo', 'u_address', 'f_address'], 'default', 'value' => null];
    //     return $rules;
    // }

public function rules()
{
    $rules = parent::rules();

    $rules[] = [['role', 'org_type', 'phone', 'u_address', 'fio', 'inn'], 'required'];
    $rules[] = ['inn', 'match', 'pattern' => '/^[0-9]+$/'];
    $rules[] = ['inn', 'string', 'min' => 6, 'max' => 20];
    $rules[] = ['zkpo', 'match', 'pattern' => '/^[0-9]+$/'];
    $rules[] = ['zkpo', 'string', 'min' => 6];
    $rules[] = ['role', 'in', 'range' => [1, 2]];
    $rules[] = ['org_type', 'in', 'range' => ['entity', 'individual', 'fop']];


    $rules[] = [['email', 'username', 'password', 'repeatpassword'], 'required'];
    $rules[] = ['email', 'email'];
    $rules[] = ['repeatpassword', 'compare', 'compareAttribute' => 'password', 'message' => Yii::t('app', "Passwords don't match")];

    $rules[] = [['at_org','member','f_address', 'zkpo'], 'safe'];

    $rules[] = ['at_org', 'required',
        'when' => fn($model) => !($model->org_type === 'entity'),
        'whenClient' => "function () { 
            return !(                
                $('input[name=\"register-form[org_type]\"]:checked').val() == 'entity'
            );
        }"
    ];

    return $rules;    
}    

    public function attributeLabels()
    {
        return array_merge(parent::attributeLabels(), [
            'fio' => Yii::t('app', 'FIO'),
            'role' => Yii::t('app', 'Role'),
            'at_org' => Yii::t('app', 'Company full name'),
            'org_type' => Yii::t('app', 'Organization type'),
            'member_phone' => Yii::t('app', 'Member phone'),
            'fax' => Yii::t('app', 'Fax'),
            'firma_full' => Yii::t('app', 'Full organization name'),
            'inn' => Yii::t('app', 'ЄДРПОУ/ІПН'),
            // 'zkpo' => Yii::t('app', 'ZKPO'),
            'u_address' => Yii::t('app', 'Legal address'),
            'f_address' => Yii::t('app', 'Personal address'),
            'member' => Yii::t('app', 'Contact Person'),
            'phone' => Yii::t('app', 'Phone'),
            'member_email' => Yii::t('app', 'E-mail'),
            'site' => Yii::t('app', 'Site'),
            // 'captcha' => Yii::t('app', 'Captcha'),
            'repeatpassword' => Yii::t('app', 'Repeat Password'),
            'files' => Yii::t('app', 'Files') . ' (jpg, doc, pdf)',
        
        ]);
    }

    public function register()
    {
        if (!$this->validate()) {
            Yii::error('Validation failed: ' . print_r($this->errors, true), __METHOD__);
            return false;
        }

        // Создаем пользователя
        $user = Yii::createObject(User::class);
        $user->setScenario('register');
        $user->username = $this->username;
        $user->email = $this->email;
        $user->password = $this->password;
        $user->fio = $this->fio;
        $user->at_org = $this->at_org;
        
        if(empty(trim($user->at_org))){
            $user->at_org = $this->fio;    
        }
        
        $user->org_type = $this->org_type;
        $user->member_phone = $this->member_phone || 0;
        $user->fax = $this->fax || 0;
        $user->role = $this->role;

        if (!$user->save()) {
            Yii::error('User save failed: ' . print_r($user->errors, true), __METHOD__);
            return false;
        }

        // Создаем профиль
        $profile = Profile::findOne(['user_id' => $user->id]);
        if (!$profile) {
            $profile = new Profile();
            $profile->user_id = $user->id;
        }        
        $profile->fio = $this->fio;
        $profile->at_org = $this->at_org;
        $profile->org_type = $this->org_type;
        $profile->member_phone = $this->member_phone;
        $profile->fax = $this->fax;
        $profile->firma_full = $this->firma_full;
        $profile->inn = $this->inn;
        $profile->zkpo = $this->inn;
        $profile->u_address = $this->u_address;
        $profile->f_address = $this->f_address;
        $profile->member = $this->member;
        $profile->phone = $this->phone;
        $profile->member_email = $this->email;
        $profile->site = $this->site;

        if (!$profile->save()) {
            Yii::error('Profile save failed: ' . print_r($profile->errors, true), __METHOD__);
            $user->delete(); // Удаляем пользователя, если профиль не сохранился
            return false;
        }

        return $user;
    }
}