<?php

namespace Inside\DESK\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\View\View;
use Inside\Authentication\Facades\Authentication;
use Inside\Content\Models\Contents\Tools;
use Inside\Permission\Models\User;
use Laravel\Lumen\Routing\Controller;

class IEController extends Controller
{
    /**
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request)
    {
        $user = Authentication::getUserFromMagicCookie($request);

        if (!$user) {
            return redirect('/oauth2/login');
        }

        /** @var User $permissionUser */
        $permissionUser = User::query()->find($user->uuid);

        $query = Tools::withoutGlobalScopes()->where([
            'status' => 1,
            'langcode' => $user->langcode,
            'internet_explorer_display' => 1
        ]);

        if (!$permissionUser->hasAnyRole('super_administrator')) {
            $fields = ['brands', 'countries', 'management_modes', 'profiles'];

            foreach ($fields as $field) {
                $references = DB::table('inside_pivots')->where('parent_uuid', $user->uuid)->where('related_type', type_to_class($field))->where('related_langcode', $user->langcode)->where('related_field', $field)->pluck('related_uuid')->toArray();

                $query->join('inside_pivots AS inside_pivots_' . $field, function ($join) use ($field, $references) {
                    $join->on('inside_pivots_' . $field . '.parent_uuid', '=', 'inside_content_tools.uuid')
                        ->where(function ($subQuery) use ($field, $references) {
                            $subQuery->whereIn('inside_pivots_' . $field . '.related_uuid', $references);
                        });
                });
            }
        }

        $tools = $query->orderBy('title', 'asc')->groupBy('inside_content_tools.uuid')->get();

        return view('custom.internet-explorer', ['user' => $user, 'tools' => $tools]);
    }
}
