<?php

namespace App\Http\Controllers\V1;

use App\Models\User;
use App\Services\Api\ErrorMsgServive;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Mail;
use App\Models\MailCode;
use Illuminate\Support\Facades\Validator;

class EmailController extends Controller
{
    /**
     发送邮箱验证码
     在 .env 文件配置如下，可测试邮件发送（最好自己申请一个邮箱获取信息）
     MAIL_MAILER=smtp
     MAIL_HOST=ssl://smtp.163.com
     MAIL_PORT=465
     MAIL_USERNAME=18738190585@163.com
     MAIL_PASSWORD=VIBTDHQAYLKJYIGC
     MAIL_ENCRYPTION=
     MAIL_FROM_ADDRESS=18738190585@163.com
     MAIL_FROM_NAME="${APP_NAME}"
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function sendEmailCode(Request $request)
    {
        $email = $request->input('email');

        $validator = Validator::make($request->all(), [
            'email' => 'required|email',
        ]);
        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }
        $code = rand(1000, 9999);
        $notice = '本次验证码是' . '【 ' . $code . ' 】 ' . '有效期 5 分钟';
        $subject = '邮箱验证通知';
        try {
            Mail::raw($notice, function ($message) use ($email, $subject) {
                $message->subject($subject);
                $message->to($email);
            });
            $mailCode = new MailCode();
            $mailCode->account = $email;
            $mailCode->code = $code;
            $mailCode->state = 0;
            $mailCode->created_at = date('Y-m-d H:i:s');
            $mailCode->save();
            return $this->success();
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    //判断邮箱验证码 5分钟有效期 （这不是个API接口：哪里需要就放到哪里验证）
    public static function isEmailCodeRight($email, $code)
    {
        $result = MailCode::query()
            ->where('account', $email)
            ->where('code', $code)
            ->where('state', 0)
            ->where('created_at', '>', Carbon::now()->subMinutes(5))
            ->orderBy('id', 'desc')
            ->first();

        if (!$result) {
            return false;
        }
        $result->state = 1; //验证通过就失效
        $result->save();

        return true;
    }


    /**
     * @param $email
     * @param $title
     * @param $notice
     * @return bool
     * 邮箱发送通知
     */
    public static function sendNotice($email = null,$title = null, $notice = null)
    {
        try {
            Mail::raw($notice, function ($message) use ($email, $title) {
                $message->subject($title);
                $message->to($email);
            });
            return true;
        } catch (\Exception $e) {
            return false;
        }
    }


}
