<?php

namespace App\Http\Controllers;

use App\Models\Applience;
use App\Models\ToolAdditionalOption;
use App\Models\User;
use App\Models\UserToolSetup;
use Illuminate\Contracts\View\View;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;

class AccessManagerController extends Controller
{
    public function show() : View 
    {
        return view('access_manager.request');
    }

    public function loadRequests()
    {
        $users = User::where('role', 4)
        ->whereIn('setupDone', [0,2,3])
        ->get();

        return $this->generateResponse('Success', '', $users);
    }

    public function unfinished()
    {
        $users = User::where('role', 4)
        ->whereIn('setupDone', [0,2,3])
        ->count();

        return $this->generateResponse('Success', '', $users);
    }

    public function processUser($userId)
    {
        $user = User::findOrFail($userId);
        /*
        $jobRole = $user->jobRole()->first();

        

        print('<pre>'.print_r('User: '.$user->name,true).'</pre>');
        print('<pre>'.print_r('Job Role: '.$jobRole->name,true).'</pre>');

        $userToolsSetup = $user->toolsSetup()->get();

        foreach ($userToolsSetup as $userTool) {
            //dd($userTool->tool()->first());
            //$tool = $roleTool->tool()->first();
            //$toolOption = $roleTool->toolOption()->first();
            print('<pre>'.print_r('Tool: '.$userTool->tool()->first()->name,true).'</pre>');
            print('<pre>'.print_r('Tool Additional Data: '.$userTool->toolAdditionalOption()->first()->type.': '.$userTool->toolAdditionalOption()->first()->option,true).'</pre>');
        }
        */

        return view('access_manager.processUser')
        ->with('userID', $userId)
        ->with('user', $user);
    }

    public function loadUserTools($userId)
    {
        $formattedArray = [];
        $user = User::findOrFail($userId);
        $userToolsSetup = $user->toolsSetup()->get();

        foreach ($userToolsSetup as $userTool) {
            $tool       = $userTool->tool()->first();

            $toolOptions = ToolAdditionalOption::whereIn('id', json_decode($userTool->tool_option_id))->pluck('option')->toArray();
            $toolOptions = implode(', ', $toolOptions);

            $formattedArray[] = [
                'toolSetupID'       => $userTool->id,
                'toolID'            => $tool->id,
                'toolName'          => $tool->name,
                'toolURL'           => $tool->url,
                'status'            => $userTool->status,
                'toolOptionType'    => 'Role',
                'toolOptionName'    => $toolOptions
            ]; 
        }

        return $this->generateResponse('Success', '', $formattedArray);
    }

    public function createToolAcess($userId, $toolId, Request $request) 
    {      
        $tool = UserToolSetup::where('user_id', $userId)->where('tool_id', $toolId)->first();
        if ($request->input('PassboltLink') === 'Yes') {
            $tool->PassboltLink = $request->input('PassboltLink');
            $tool->isPassboltLink = 1;
        } else {
            $tool->login = $request->input('Login');
            $tool->password = Crypt::encrypt($request->input('Password'));
            //Crypt::decrypt($encrypted_password);
            $tool->isPassboltLink = 0;
        }
        
        $tool->status = 1;
        $tool->save();
        if (UserToolSetup::where('user_id', $userId)->where('status', 0)->count() == 0) {
            $user = User::find($userId);
            $user->setupDone = 1;
            $user->save();
        }

        return $this->generateResponse('Success', '', []);
    }

    public function deleteTool($ID, Request $request)
    {
        $tool = UserToolSetup::find($ID);

        if (empty($tool)) {
            return $this->generateResponse('Error', 'Tool Setup Not Found.', []);
        }

        $user = User::find($tool->user_id);
        $tool->delete();

        if ($user->setupDone == 2) {
            $userToolsSetup = $user->toolsSetup()->count();
            if ($userToolsSetup <= 0) {
                $user->delete();
                return $this->generateResponse('Success', '', ['userExist' => 0]);
            }
        }

        if ($user->setupDone == 3) {
            $userToolsSetup = $user->toolsSetup()->whereIn('status',[0,2])->count();
            if ($userToolsSetup <= 0) {
                $user->setupDone = 1;
                $user->save();
            }
        }

        return $this->generateResponse('Success', '', ['userExist' => 1]);
    }
}