<?php

namespace App\Http\Controllers\Client;

use App\Models\Company;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;

// use DB;
use Illuminate\Support\Facades\DB;

class RoleController extends Controller
{
    function __construct()
    {
        // $this->middleware('permission:صلاحيات المستخدمين');
    }

    public function index(Request $request)
    {
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $roles = Role::where('company_id',$company_id)->get();
        $rolePermissions = Permission::join("role_has_permissions","role_has_permissions.permission_id","=","permissions.id")->get();
        $permission = permission::orderBy('key','ASC')->get();
        return view('client.roles.index', compact('company_id','roles','rolePermissions','permission'));
    }

    public function create()
    {
        $permission = Permission::get();
        return view('client.roles.create', compact('permission'));
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|unique:roles,name',
            'permission' => 'required',
        ]);
        
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);

        $role = Role::create([
            'name' => $request->input('name'),
            'guard_name' => 'client-web',
            'company_id' => $company_id
        ]);
        $role->syncPermissions($request->input('permission'));
        
        return response()->json(['message' => 'تم اضافة الصلاحية بنجاح','status'=>true]);
    }

    public function edit($id)
    {
        $role = Role::findOrFail($id);
        $permission = Permission::get();
        $rolePermissions = DB::table("role_has_permissions")->where("role_has_permissions.role_id", $id)
            ->pluck('role_has_permissions.permission_id', 'role_has_permissions.permission_id')
            ->all();
        return view('client.roles.edit', compact('role', 'permission', 'rolePermissions'));
    }

    public function update(Request $request)
    {
        $this->validate($request, [
            'role_id' => 'required',
            'permission' => 'required',
        ]);
        $role = Role::findOrFail($request->role_id);
        $role->syncPermissions($request->input('permission'));

        return response()->json(['message' => 'تم تعديل الصلاحية بنجاح', 'status' => true]);
    }

    public function destroy(Request $request)
    {
        DB::table("roles")->where('id', $request->role_id)->delete();
        return redirect()->route('client.roles.index')
            ->with('success', 'تم حذف الدور او الصلاحية بنجاح');
    }


}
