<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Auth;

class IndexController extends Controller
{
  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) {
    $menuItems = collect([
      [
          'name' => 'strings.dashboard',
          'icon' => 'grid-outline',
          'link' => '/dashboard',
          'permissions' => [
            'dashboard.index'
          ],
      ],
      [
          'name' => 'strings.customers',
          'icon' => 'people-outline',
          'link' => '/customers',
          'permissions' => [
            'customers.index'
          ],
      ],
      [
          'name' => 'strings.users',
          'icon' => 'people-outline',
          'link' => '/users',
          'permissions' => [
            'users.index'
          ],
      ],
      [
          'name' => 'strings.purchase_orders',
          'icon' => 'file-text-outline',
          'link' => '/purchase-orders',
          'permissions' => [
            'purchase_orders.index'
          ],
      ],
    ]);

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

    $chunk = $filtered->chunk(3);

    return $chunk[0];
  }

}
