<?php

namespace Controller;

use Lib\Mail\Mail;
use Model\email;

/**
 * @author:dc
 * @time 2023/2/13 11:28
 * Class Home
 * @package Controller
 */
class Home {


    /**
     * 登录操作
     * @return int[]
     * @author:dc
     * @time 2023/2/13 11:50
     */
    public function login(){
        //        $mail,$password,$imap,$smtp
        $formData = app()->request(['email','password','imap','smtp']);

        if(empty($formData['email']) || !preg_match("/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/",$formData['email'])){
            app()->e('email_verify_error');
        }

        if(empty($formData['password'])){
            app()->e('password_verify_error');
        }

        if(empty($formData['imap'])){
            app()->e('imap_verify_error');
        }

        if(empty($formData['smtp'])){
            app()->e('smtp_verify_error');
        }

        // 进行远程登录,验证
        Mail::login($formData['email'],$formData['password'],$formData['imap']);

        // 是否存在
        $id = db()->value(email::hasEmail($formData['email']));

        $data = [
            'password'  =>  base64_encode($formData['password']),
            'imap'  =>  $formData['imap'],
            'smtp'  =>  $formData['smtp'],
            'status'    =>  1,
            'pwd_error'    =>  0,
            'name'    =>  '',
            'token'    =>  md5($formData['email'].$formData['password'].$formData['imap']),
        ];

        if($id){
            // 修改
            $ret = db()->update(email::$table,$data,dbWhere(['id'=>$id]));
        }else{
            // 新增
            $ret = db()->insert(email::$table,$data);
        }


        if($ret){
            app()->_json([
                'token' => $data['token']
            ]);
        }

        app()->e('login_error');


    }

}