<?php
namespace App\Admin\Actions\Users;

use App\Models\User;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Illuminate\Support\Facades\Auth;
use PHPUnit\Util\Exception;

class UsersInfo extends Form implements LazyRenderable
{
    use LazyWidget;


    public function __construct($data = [], $key = null)
    {
        parent::__construct($data, $key);
    }

    public function handle(array $input)
    {
        $user = User::query()->where(['id'=>$input['id']])->first();
        if(!$user){
            return $this->response()->error(trans('user.help.refresh_error'));
        }
        if($input['mobile']!=$user->mobile && User::query()->where('mobile',$input['mobile'])->first()){
            return $this->response()->error(trans('user.help.mobile_used'));
        }else{
            $user->mobile = $input['mobile'];
        }
        if($input['email']!=$user->email && User::query()->where('email',$input['email'])->first()){
            return $this->response()->error(trans('user.help.email_used'));
        }else{
            $user->mobile = $input['mobile'];
        }

        if($input['password']!=''){
            $user->password = $input['password'];
        }
        $user->sex = $input['sex'];
        $user->save();
        return $this->response()->success('success')->refresh();
    }


    public function form()
    {
        $user = User::query()->find($this->payload['id']);
        $this->hidden('id')->value($this->payload['id']);
        $this->text('mobile')->default($user->mobile??'')->help(trans('user.help.mobile_help'));
        $this->text('email')->default($user->email??'')->help(trans('user.help.eamil_help'));
        $this->text('password')
            ->minLength(6)
            ->maxLength(20)
            ->customFormat(function ($v) {
                if ($v == $this->password) {
                    return;
                }
                return $v;
            })
            ->help(trans('user.help.password_help'));
        $this->radio('sex',trans('user.fields.sex'))->options([1=>trans('user.fields.man'),2=>trans('user.fields.woman')])->value($user->sex);
    }
}
