<?php

namespace App\Http\Controllers\FCControllers;
use Auth;
use Exception;
use App\Models\fcmodels\Role;
use App\Models\fcmodels\AuditLog;
use Illuminate\Http\Request;

class RoleController extends Controller
{
    //return index
    public function index()
    {
        try
        {
            $roles = Role::all();
            return view('fcviews.roles.index',compact('roles'));
        }
        catch(Exception $e)
        {
            abort(500,$e->getMessage());
        }
    }

    //get 
    public function get()
    {
        try
        {
            $roles = Role::all();
            return $roles;
        }
        catch(Exception $e)
        {
            abort(500,$e->getMessage());
        }
    }
    //store
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string'
        ],
        [
            'name.required' => 'Please enter role name',            
        ]);
        $data = new Role();
        $data->name = $request->name;
        $data->save ();
        //log
        $roleLog = new AuditLog();
        $roleLog->audit_module = "Admin";
        $roleLog->audit_activity = "Role name ".$request->name ." added by Admin ID# " .Auth::id();
       
        $roleLog->user_category = "Admin";
        $roleLog->user_id = Auth::id();
        
        $roleLog->save();
        
        return response()->json($data);
    }

    //edit
    public function update(Request $request)
    {
        $request->validate([
            'name' => 'required|string'
        ],
        [
            'name.required' => 'Please enter role name',            
        ]);
        $role = Role::where('role_id',$request->id)->get();
        $data = Role::findOrFail($request->id);
        $data->name = $request->name;
        $data->save ();
        //log
        $roleLog = new AuditLog();
        $roleLog->audit_module = "Admin";
        $roleLog->audit_activity = "Role of details ".$role." updated to " .$data ." updated by Admin ID# " .Auth::id();
       
        $roleLog->user_category = "Admin";
        $roleLog->user_id = Auth::id();
        
        $roleLog->save();
        
        return response()->json($data);
    }

    //delete
    public function delete(Request $request,$id){
        //find user details to delete
        $role = Role::where('role_id',$id)->get();
        //set delete
        $deleterole = Role::findOrFail($id);
        $deleterole->delete();
        //set logging
        $roleLog = new AuditLog();
        $roleLog->audit_module = "Admin";
        $roleLog->audit_activity = "Role of details: ".$role." deleted by Admin ID#" .Auth::id();
        
        $roleLog->user_category = "Admin";
        $roleLog->user_id = Auth::id();
        $roleLog->save();
    }
}
