<?php

namespace App\Http\Controllers\Admin;

use Exception;
use App\Models\Mail;
use Illuminate\Http\Request;

class MailController extends AdminController
{
    /**
     * 邮箱列表
     * @param Request $request
     */
    public function index(Request $request)
    {
        $mails = Mail::all();

        return view('admin.email.bind', compact('mails'));
    }

    /**
     *  绑定邮箱
     *
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(Request $request)
    {
        try {
            // 测试连通性
            $client = (new Mail())->getMailBoxClient([
                'host' => $request->input('imap_host') ,
                'port' => $request->input('imap_port') ,
                'username' => $request->input('email') ,
                'password' => $request->input('password') ,
            ]);
            $client->connect();

            $transport = (new \Swift_SmtpTransport($request->input('smtp_host'), $request->input('smtp_port'), 'ssl'))
                ->setUsername($request->input('email'))
                ->setPassword($request->input('password'));
            $transport->start();

        } catch (Exception $e) {
            return back()->withInput()->with('error', '邮箱验证失败');
        }

        $result = Mail::create($request->all());
        // 默认
        Mail::where('id', '!=', $result->id)->update(['is_default' => 0]);

        if ($result) {
            return redirect('admin/email/bind')->with('success', '邮箱添加成功');
        }

        return back()->withInput()->with('error', '邮箱添加失败');
    }

    /**
     *  删除邮箱
     *
     * @param  int  $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy($id)
    {
        $result = Mail::destroy($id);

        return response()->json(['status' => $result ? 'sucess' : 'error']);
    }
}
