<?php

namespace Agent\Lib;

use Dever;

class Email
{
	# 修改邮箱
    public function act_api()
    {
        //$signature = Dever::input('signature');
        $signature = $_GET['signature'];
        if (!$signature) {
            Dever::alert('您的验证信息已失效，请重新发送验证邮件');
        }

        $signature = Dever::decode($signature);
        $temp = explode('|||', $signature);
        $code = $temp[2];

        $state = Dever::load('passport/reg')->code($code);
        if (!$state) {
            Dever::alert('您的验证信息已失效，请重新发送验证邮件');
        }

        $check = Dever::db('agent/member')->find(array('email' => $temp[1]));
        if ($check) {
            Dever::alert('该邮箱已被认证');
        }

        $where['where_id'] = $temp[0];
        $where['email'] = $temp[1];

        Dever::db('agent/member')->update($where);

        return '邮箱认证成功';
    }

	public function renzheng()
	{
		$email = Dever::input('email');
        $username = Dever::input('username');
		$code = Dever::input('code');
		$mid = Dever::input('mid');
		$email = base64_decode($email);
		$config = Dever::config('base', 'project')->email['agent'];
		$title = $config['title'];
		$content = $config['content'];

		$signature = Dever::encode($mid . '|||' . $email . '|||' . $code);

		$link = Dever::url($config['link'] . '?signature=' . $signature);
		$content = str_replace('{link}', $link, $content);
		$this->send($email, $username, $title, $content);
	}

	public function send($email, $username, $title, $content)
    {
        $config = Dever::config('base', 'project')->email;

        Dever::apply('src/PHPMailer', 'email');
        Dever::apply('src/Exception', 'email');
        Dever::apply('src/SMTP', 'email');
        $mail = new \PHPMailer\PHPMailer\PHPMailer();

        $mail->isSMTP();
        //$mail->SMTPDebug = 2;
        $mail->CharSet = 'UTF-8';
        $mail->Host = $config['smtp'];
        $mail->Port = 465;
        $mail->SMTPSecure = 'ssl';
        $mail->SMTPAuth = true;
        $mail->Username = $config['username'];
        $mail->Password = $config['password'];
        $mail->setFrom($config['from'][0], $config['from'][1]);
        $mail->addAddress($email, $username);
        $mail->Subject = "=?utf-8?B?" . base64_encode($title) . "?=";
        $mail->Body = $content;
        //$mail->addAttachment($file);
        if (!$mail->send()) {
            Dever::alert("Mailer Error: " . $mail->ErrorInfo);
        } else {
            return 'ok';
        }
    }
}
