<?php
namespace App\Domains\Company\Http\Controllers;

use App\Core\Controller;
use Illuminate\Http\Request;
use App\Exceptions\AuthException;
use App\Domains\Sms\Services\SmsService;
use App\Domains\Virtual\Services\CompanyAccountService;

class AccountController extends Controller
{
    protected $request;
    protected $companyAccountService;

    /**
     * 构造函数，自动注入.
     */
    public function __construct(Request $request, CompanyAccountService $companyAccountService)
    {
        $this->request = $request;
        $this->companyAccountService = $companyAccountService;
        $this->account = $request->user('company');
    }

    /**
     * 修改密码.
     *
     * @return \Illuminate\Http\Response
     */
    public function password()
    {
        $newPassword =  $this->request->get('new_password');

        if ($this->account->password === md5($newPassword . $this->account->salt)) {
            return res(null, '修改成功');
        }

        $attributes = [
            'id' => $this->account->id,
            'password' => $newPassword,
        ];

        $this->companyAccountService->store($attributes);

        return res(null, '修改成功');
    }

    /**
     * 绑定手机.
     *
     * @return \Illuminate\Http\Response
     */
    public function mobile()
    {
        $attributes = [
            'id' => $this->account->id,
            'mobile' => $this->request->get('mobile'),
        ];

        $account = $this->companyAccountService->store($attributes);

        return res($account, '绑定成功');
    }

    /**
     * 找回密码
     *
     * @return void
     */
    public function resetStep1()
    {
        $username = $this->request->get('username');

        if (!$this->account = $this->companyAccountService->fetch($username)) {
            return err('用户名不存在');
        }

        if (empty($this->account->mobile)) {
            throw new AuthException('用户未绑定手机号', AuthException::NOT_BOUND_MOBILE);
        }

        $freqsecs = app(SmsService::class)->sendVcode($this->account->mobile, '密码找回');

        return res(['freg' => $freqsecs, 'mobile' => $this->account->mobile], '发送成功');
    }

    /**
     * 找回密码
     *
     * @return void
     */
    public function resetStep2()
    {
        $username = $this->request->get('username');

        if (!$this->account = $this->companyAccountService->fetch($username)) {
            return err('用户名不存在');
        }

        if (empty($this->account->mobile)) {
            return err('用户未绑定手机号');
        }

        app(SmsService::class)->verifyCode($this->account->mobile, $this->request->get('verify_code'));

        return $this->password();
    }
}
