<?php

use Mtc\Core\Admin\Menu;
use Mtc\Core\Admin\Role;
use Mtc\Core\Permissions;

$path  = '../../../';
require_once $path . 'core/includes/header.inc.php';
$page_meta['title'] = 'User Roles';

$id = filter_input(INPUT_GET, 'id');
$role = Role::query()
    ->findOrNew($id);

$messages = [];

if (filter_input(INPUT_POST, 'action') === 'update') {
    /** @var Role $role */
    $role = Role::query()
        ->firstOrNew([
            'id' => filter_input(INPUT_POST, 'id')
        ]);
    $role->fill($_POST);
    $role->save();

    $role->assign($_POST['permissions']);
    $messages[] = [
        'content' => 'Role permissions set',
        'type' => 'success'
    ];

}

$twig->display('admin/roles/edit.twig', [
    'role' => $role,
    'page_meta' => $page_meta,
    'self' => \Util::add_query_arg([ 'id' => $id ]),
    'id' => $id,
    'messages' => $messages,
    'all' => [
        'Menu Permissions' => Menu::query()
            ->with('subItems')
            ->where('sub_id', 0)
            ->where('title', '!=', Menu::MENU_MTC_ONLY)
            ->where('constant', '!=', Permissions::MENU_PERMISSIONS)
            ->get(),
        'Custom Permissions' => Menu::query()
            ->with('subItems')
            ->where('sub_id', 0)
            ->where('title', '!=', Menu::MENU_MTC_ONLY)
            ->where('constant', '=', Permissions::MENU_PERMISSIONS)
            ->get(),
    ],
]);
