<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\Role\BulkDestroyRole;
use App\Http\Requests\Admin\Role\DestroyRole;
use App\Http\Requests\Admin\Role\IndexRole;
use App\Http\Requests\Admin\Role\StoreRole;
use App\Http\Requests\Admin\Role\UpdateRole;
use App\Models\Role;
use Illuminate\Http\Request;
use App\Models\Permission;
use Brackets\AdminListing\Facades\AdminListing;
use Exception;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Contracts\Routing\ResponseFactory;
use Illuminate\Contracts\View\Factory;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Response;
use Illuminate\Routing\Redirector;
use Illuminate\Support\Facades\DB;
use Illuminate\View\View;

class RolesController extends Controller
{

    /**
     * Display a listing of the resource.
     *
     * @param IndexRole $request
     * @return array|Factory|View
     */
    public function index(IndexRole $request)
    {
        // create and AdminListing instance for a specific model and
        $data = AdminListing::create(Role::class)->processRequestAndGet(
            // pass the request with params
            $request,

            // set columns to query
            ['id', 'name', 'guard_name'],

            // set columns to searchIn
            ['id', 'name', 'guard_name']
        );

        if ($request->ajax()) {
            if ($request->has('bulk')) {
                return [
                    'bulkItems' => $data->pluck('id')
                ];
            }
            return ['data' => $data];
        }

        return view('admin.role.index', ['data' => $data]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @throws AuthorizationException
     * @return Factory|View
     */
    public function create()
    {
        $this->authorize('admin.role.create');

        return view('admin.role.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param StoreRole $request
     * @return array|RedirectResponse|Redirector
     */
    public function store(StoreRole $request)
    {
        // Sanitize input
        $sanitized = $request->getSanitized();

        // Store the Role
        $role = Role::create($sanitized);

        if ($request->ajax()) {
            return ['redirect' => url('admin/roles'), 'message' => trans('brackets/admin-ui::admin.operation.succeeded')];
        }

        return redirect('admin/roles');
    }

    /**
     * Display the specified resource.
     *
     * @param Role $role
     * @throws AuthorizationException
     * @return void
     */
    public function show(Role $role)
    {
        $this->authorize('admin.role.show', $role);

        // TODO your code goes here
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param Role $role
     * @throws AuthorizationException
     * @return Factory|View
     */
    public function edit(Role $role)
    {
        $this->authorize('admin.role.edit', $role);


        return view('admin.role.edit', [
            'role' => $role,
        ]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param UpdateRole $request
     * @param Role $role
     * @return array|RedirectResponse|Redirector
     */
    public function update(UpdateRole $request, Role $role)
    {
        // Sanitize input
        $sanitized = $request->getSanitized();

        // Update changed values Role
        $role->update($sanitized);

        if ($request->ajax()) {
            return [
                'redirect' => url('admin/roles'),
                'message' => trans('brackets/admin-ui::admin.operation.succeeded'),
            ];
        }

        return redirect('admin/roles');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param DestroyRole $request
     * @param Role $role
     * @throws Exception
     * @return ResponseFactory|RedirectResponse|Response
     */
    public function destroy(DestroyRole $request, Role $role)
    {
        $role->delete();

        if ($request->ajax()) {
            return response(['message' => trans('brackets/admin-ui::admin.operation.succeeded')]);
        }

        return redirect()->back();
    }

    /**
     * Remove the specified resources from storage.
     *
     * @param BulkDestroyRole $request
     * @throws Exception
     * @return Response|bool
     */
    public function bulkDestroy(BulkDestroyRole $request) : Response
    {
        DB::transaction(static function () use ($request) {
            collect($request->data['ids'])
                ->chunk(1000)
                ->each(static function ($bulkChunk) {
                    Role::whereIn('id', $bulkChunk)->delete();

                    // TODO your code goes here
                });
        });

        return response(['message' => trans('brackets/admin-ui::admin.operation.succeeded')]);
    }

    public function role($role)
    {
        // $permissionsForRole = DB::table('role_has_permissions')
        //     ->where('role_id', $role)
        //     ->pluck('permission_id');
        $roles= Role::where('id',$role)->first();
        // Fetch the details for each permission
        // $permissionsDetails = Permission::where('guard_name',$roles->guard_name)->get();
        $permissionsDetails = Permission::all();
        // dd($permissionsDetails);
        $permissionsForRoles = [];
        foreach ($permissionsDetails as $per) {
            $permissionsForRole = DB::table('role_has_permissions')
                ->where('permission_id', $per->id)
                ->where('role_id',$roles->id)
                ->get()
                ->toArray();
            $permissionsForRoles[] = $permissionsForRole;
        }
        // dd($psermissionsDetails);
        return view('admin.role.rolepermission', [
            'permissions' => $permissionsDetails,
            'role'=>$roles,
            'permissionsForRoles' => $permissionsForRoles
        ]);
    }
    public function permissioncheck($role,Request $request)
    {
        // Get an array of selected permission IDs from the request
        $permission_ids = $request->input('permissions', []);
        // Get the existing permissions for the role from the database
        $existingPermissions = DB::table('role_has_permissions')
            ->where('role_id', $role)
            ->pluck('permission_id')
            ->toArray();
        // Find permissions to be removed
        $permissionsToRemove = array_diff($existingPermissions, $permission_ids);
        // dd($permission_ids);
        // Remove permissions that are not present in the request
        if (!empty($permissionsToRemove)) {
            DB::table('role_has_permissions')
                ->where('role_id', $role)
                ->whereIn('permission_id', $permissionsToRemove)
                ->delete();
        }
        // Iterate over the selected permission IDs
        foreach ($permission_ids as $per_id) {
            // Check if the role already has the permission
            $existingPermission = DB::table('role_has_permissions')
                ->where('role_id', $role)
                ->where('permission_id', $per_id)
                ->first();
            if (!$existingPermission) {
                // If the role does not have the permission, insert it
                DB::table('role_has_permissions')->insert([
                    'permission_id' => $per_id,
                    'role_id' => $role
                ]);
            }
        }
        return redirect('admin/roles/'.$role);
    }
}
