<?php

namespace Filanco\Cms\Http\Controllers;

use Illuminate\Http\Request;
use Filanco\Cms\Facades\Cms;

class CmsRoleController extends CmsBreadController
{
    // POST BR(E)AD
    public function update(Request $request, $id)
    {
        Cms::canOrFail('edit_roles');

        $slug = $this->getSlug($request);

        $dataType = Cms::model('DataType')->where('slug', '=', $slug)->first();

        $data = call_user_func([$dataType->model_name, 'findOrFail'], $id);
        $this->insertUpdateData($request, $slug, $dataType->editRows, $data);

        $data->permissions()->sync($request->input('permissions', []));

        return redirect()
            ->route("Cms.{$dataType->slug}.index")
            ->with([
                'message'    => "Успешно сохранено {$dataType->display_name_singular}",
                'alert-type' => 'success',
            ]);
    }

    // POST BRE(A)D
    public function store(Request $request)
    {
        Cms::canOrFail('add_roles');

        $slug = $this->getSlug($request);

        $dataType = Cms::model('DataType')->where('slug', '=', $slug)->first();

        $data = new $dataType->model_name();
        $this->insertUpdateData($request, $slug, $dataType->addRows, $data);

        $data->permissions()->sync($request->input('permissions', []));

        return redirect()
            ->route("Cms.{$dataType->slug}.index")
            ->with([
                'message'    => "Successfully Added New {$dataType->display_name_singular}",
                'alert-type' => 'success',
            ]);
    }
}
