<?php
namespace Passport\Lib;

use Dever;
use Dever\Session\Oper as Save;

class Email
{
	public function forget()
	{
		$email = Dever::input('email');
		$code = Dever::input('code');
		$email = base64_decode($email);
		$config = Dever::config('base', 'project')->email['forget'];
		$title = $config['title'];
		$content = $config['content'];

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

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

	public function send($email, $title, $content)
    {
        $user = Dever::db('passport/user')->one(array('email' => $email));
        if (!$user) {
        	Dever::alert('该邮箱还未注册');
        }
        $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($user['email'], $user['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';
        }
    }
}
