<?php

namespace app\api\controller;

use ba\Captcha;
use ba\ClickCaptcha;
use app\common\model\User;
use app\common\library\Email;
use app\common\controller\Frontend;
use support\validation\Validator;
use support\validation\ValidationException;
use Webman\Http\Request;
use support\Response;
use PHPMailer\PHPMailer\Exception as PHPMailerException;

class Ems extends Frontend
{
    protected array $noNeedLogin = ['send'];

    public function send(Request $request): Response
    {
        $response = $this->initializeFrontend($request);
        if ($response !== null) return $response;

        $params = $request->post(['email', 'event', 'captchaId', 'captchaInfo']);
        $mail = new Email();
        if (!$mail->configured) {
            return $this->error(__('Mail sending service unavailable'));
        }

        try {
            Validator::make($params, [
                'email' => 'required|email',
                'event' => 'required|string',
                'captchaId' => 'required|string',
                'captchaInfo' => 'required|string',
            ], [
                'email.required' => 'email format error',
                'event.required' => 'Parameter error',
                'captchaId.required' => 'Captcha error',
                'captchaInfo.required' => 'Captcha error',
            ])->validate();
        } catch (ValidationException $e) {
            return $this->error(__($e->getMessage()));
        }

        $captchaObj = new Captcha();
        $clickCaptcha = new ClickCaptcha();
        if (!$clickCaptcha->check($params['captchaId'], $params['captchaInfo'])) {
            return $this->error(__('Captcha error'));
        }

        $captcha = $captchaObj->getCaptchaData($params['email'] . $params['event']);
        if ($captcha && time() - $captcha['create_time'] < 60) {
            return $this->error(__('Frequent email sending'));
        }

        $userInfo = User::where('email', $params['email'])->find();
        if ($params['event'] == 'user_register' && $userInfo) {
            return $this->error(__('Email has been registered, please log in directly'));
        }
        if ($params['event'] == 'user_change_email' && $userInfo) {
            return $this->error(__('The email has been occupied'));
        }
        if (in_array($params['event'], ['user_retrieve_pwd', 'user_email_verify']) && !$userInfo) {
            return $this->error(__('Email not registered'));
        }

        if ($params['event'] == 'user_email_verify') {
            if (!$this->auth->isLogin()) {
                return $this->error(__('Please login first'));
            }
            if ($this->auth->email != $params['email']) {
                return $this->error(__('Please use the account registration email to send the verification code'));
            }
            $password = $request->post('password');
            if (!verify_password($password, $this->auth->password, ['salt' => $this->auth->salt ?? ''])) {
                return $this->error(__('Password error'));
            }
        }

        $code = $captchaObj->create($params['email'] . $params['event']);
        $subject = __($params['event']) . '-' . get_sys_config('site_name');
        $body = __('Your verification code is: %s', [$code]);

        try {
            $mail->isSMTP();
            $mail->addAddress($params['email']);
            $mail->isHTML();
            $mail->setSubject($subject);
            $mail->Body = $body;
            $mail->send();
        } catch (PHPMailerException) {
            return $this->error($mail->ErrorInfo);
        }

        return $this->success(__('Mail sent successfully~'));
    }
}
