<?php

namespace App\Http\Controllers\Platform;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use App\Models\User;
use App\Models\UserExtra;
use App\Services\UtilService;

class PasswordController extends Controller
{
    public function getback(Request $request)
    {
        $request->validate([
           'phone'  => 'required',
           'auth_code' => 'required',
           'new_password' => 'required',
        ]);
                   
        $phone = $request->input('phone');
        if (!UtilService::isPhoneNum($phone)) {
            $this->jsonReturn(10033, "手机号码错误");
        }
        $srvAuthCode = Cache::get("sms_auth_code:" . $phone);
        
        if ($request->input("auth_code") != $srvAuthCode) { //验证码错误
            return $this->jsonReturn(1003, "验证码错误");
        }
                
        $new_password = $request->input('new_password');
        
        if ($phone == $new_password) {
            return $this->jsonReturn(12001, "密码不可以是手机号");
        } 
        
        $user = User::findByMobile($phone);
        if (empty($user)) {
            return $this->jsonReturn(11008, "手机号未绑定账号");
        }
        
        if ($user->account == $new_password) {
            return $this->jsonReturn(12002, "密码不可以是帐号");
        }
        
        if ($user->password == User::encryptPassword($new_password)) {
            return $this->jsonReturn(11007, "新旧密码相同");
        }
                          
        $ret = User::changePassword($user->uid, $new_password);
        if ($ret) {
            //更新密码强度
            $userExtra = UserExtra::find($user->uid);
            if (empty($userExtra)) {
                $userExtra = new UserExtra();
            }
            $userExtra->uid = $user->uid;
            $userExtra->password_strength = UserExtra::getPasswordStrength($new_password);
            $userExtra->save();
            return $this->jsonReturn(0, "密码重置成功");
        }else {
            return $this->jsonReturn(11007, "操作失败");
        }
    }

    
}
