<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Auth;

class IndexController extends Controller
{
  protected $menuItems;

  public function __construct() {
    $this->menuItems = collect([
      [
          'name' => 'strings.dashboard',
          'icon' => 'grid-outline',
          'link' => '/dashboard',
          'permissions' => [
            'dashboard.index'
          ],
      ],
      [
          'name' => 'strings.users',
          'icon' => 'people-outline',
          'link' => '/users',
          'permissions' => [
            'users.index'
          ],
      ],
    ]);
  }

  public function index()
  {
      return view('index');
  }

  /**
   * Get initial data for Vue.js application
   */
  public function vue()
  {
      $permissions = $this->getPermissions();

      $notifications = auth()->user()->unreadNotifications()->get()->toArray();

      $data = [
          'menuItems' => $this->getMenu($permissions),
          'notifications' => $notifications,
      ];
      return $data;
    }

    private function getPermissions()
    {
      $permissionNames = auth()->user()->getAllPermissions();

      $filtered = $permissionNames->filter(function ($item) {
          return false !== stristr($item->name, 'index');
      })->map(function($item) {
        return $item['name'];
      })->values()->toArray();

      return $filtered;
  }

  private function getMenu ($permissions) {
    $filtered = $this->menuItems->filter(function($collection) use ($permissions) {
      $findPermissions = [];
      foreach ($permissions as $permission) {
        if (in_array($permission, $collection['permissions'])) $findPermissions[] = $permission;
      }
      return count($findPermissions) > 0;
    });

    return $filtered;
  }

}
