<?php

namespace App\Http\Controllers;

use App\MailEvent;
use App\Role;
use Illuminate\Http\Request;

class SendEmailsController extends Controller
{


    //
    /**
     * SendEmailsController constructor.
     */
    public function __construct()
    {
        $this->middleware('auth')->except([]);
    }

    public function index()
    {
        $roles = Role::all();
        $emailEvents = MailEvent::query()->with('roles')->orderBy('id')->paginate();
        foreach ($emailEvents as $emailEvent) {
            $emailEvent->template = json_decode($emailEvent->template);
            $emailEvent->remark_show = true;
            $emailEvent->remark_edit = false;
            $emailEvent->template_show = true;
            $emailEvent->template_edit = false;
            $emailEvent->role_selected = '';
        }
        return view('maintenance.emails.index', compact('roles', 'emailEvents'));
    }

    public function addRole(Request $request)
    {
        $roleId = $request->roleId;
        $role = Role::find($roleId);
        $eventMailId = $request->eventMailId;
        if (MailEvent::query()->find($eventMailId)->roles()->where('roles.id', $roleId)->exists()) {
            return ['success' => false, 'data' => '角色已存在'];
        } else {
            MailEvent::query()->find($eventMailId)->roles()->attach($role->id);
            return ['success' => true, 'data' => ['role' => $role]];
        }
    }

    public function deleteRole(Request $request)
    {
        $roleId = $request->roleId;
        $role = Role::find($roleId);
        $eventMailId = $request->eventMailId;
        MailEvent::query()->find($eventMailId)->roles()->detach($role->id);
        return ['success' => true, 'data' => $role];
    }

    public function updateTemplate(Request $request)
    {
        $model = MailEvent::query()->find($request->id);
        $model->update([
            'template' => $request->template,
        ]);
        return ['success' => true];
    }

    public function active(Request $request)
    {
        $model = MailEvent::query()->find($request->id);
        $model->update([
            'is_active' => !$model->is_active,
        ]);
        return ['success' => true, 'data' => !$model->is_active];
    }

    public function updateRemark(Request $request)
    {
        $this->validate($request, [
            'remark' => 'required|string',
        ]);
        $model = MailEvent::query()->find($request->id);
        $model->update([
            'remark' => $request->remark,
        ]);
        return ['success' => true];
    }
}
