<?php
namespace app\admin\controller;


use app\common\Smtp;
use app\model\EmailStyle;
use think\facade\Config;
use think\facade\View;

/**
 * 邮箱配置
 * Class Email
 * @package app\admin\controller
 */
class Email extends AdminController {

    public function index(){

        $email = config('email') ;
        $emailStyle = EmailStyle::select();
        $templates = [] ;

        if( !$emailStyle->isEmpty() ){
            foreach ($emailStyle as $key=>$value){
                if( !isset($templates[$value->type]) ){
                    $templates[$value->type] = $value ;
                }
            }
        }
        View::assign('lost',$templates[0] ?? []);
        View::assign('order',$templates[1] ?? []);

        View::assign('email',$email) ;
        return View::fetch();
    }

    public function store(){
//        $configs = request()->all('c/a',[]) ;
        $configs = request()->post('c/a',[]) ;
        $lost = request()->post('lost/a',[]);
        $order = request()->post('order/a',[]);

        setConfig($configs ,'email') ;

        $templates = [$lost,$order] ;
        $returnArray = [] ;

        foreach($templates as $key=>$value ){
            if( empty( $value['id'] ) ){
                $data = $value;
                unset($data['id']);
                $rs = EmailStyle::create($data);
                $returnArray[$key]= $rs->id ;
            }else{
                EmailStyle::update($value);
            }
        }
        return $this->responseSuccess($returnArray);
    }

    // 测试有邮件
    public function test(){

        $email = request()->post('c/a',[]) ;

        foreach($email as $value){
            if( empty($value) ){
                return $this->responseError('请先配置邮件参数');
            }
        }
        $smtp = new Smtp($email['smtp'],$email['port'],true,$email['username'],$email['userpass']);
        //$smtp->debug = true ;
        if( $smtp->sendmail($email['test'],$email['username'],'title','123123','HTML') ){
            return $this->responseSuccess('发送成功');
        }

        return $this->responseError('发送失败') ;
    }
}
