<?php

namespace App\Http\Controllers\Admin\Pages\Users;

use App\Http\Requests\Users\UserStoreRequest;
use App\Http\Requests\Users\UserUpdateRequest;
use App\Models\User;
use App\Traits\Impersonator;
use DataTables;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Hash;
use Spatie\Permission\Models\Role;

class UserController extends Controller
{

    use Impersonator;
    public function __construct()
    {
        $this->middleware('permission:view users')->only('index', 'ajax');
        $this->middleware('permission:create user')->only('create');
        $this->middleware('permission:store user')->only('store');
        $this->middleware('permission:edit user')->only('edit');
        $this->middleware('permission:update user')->only('update');
        $this->middleware('permission:destroy user')->only('destroy');
    }

    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        return view('app.admin.pages.users.all-users');
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $roles = Role::pluck('name', 'name')->toArray();
        return view('app.admin.pages.users.create-user', compact([
            'roles'
        ]));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(UserStoreRequest $request)
    {
        try {
            $validated = $request->all();

            $validated['password'] = Hash::make($request->input('password'));

            $user = User::create($validated);

            $user->assignRole($request->input('role'));

            return back()->with('success', __('Data successfully created!'));
        } catch (Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }


    /**
     * Show the form for editing the specified resource.
     */
    public function edit(User $user)
    {
        $roles = Role::pluck('name', 'name')->toArray();
        return view('app.admin.pages.users.edit-user', compact([
            'user',
            'roles'
        ]));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(UserUpdateRequest $request, User $user)
    {
        $validated = $request->all();

        try {
            if ($request->filled('password')) {
                $validated['password'] = Hash::make($request->input('password'));
            } else {
                unset($validated['password']);
            }

            $user->update($validated);

            $user->syncRoles([$request->input('role')]);

            return back()->with('success', __('Data successfully updated!'));
        } catch (Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(User $user)
    {
        try {
            $user->delete();
            return back()->with('success', __('Data successfully deleted!'));
        } catch (Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    /**
     * @return JsonResponse
     * @throws Exception
     */
    public function ajax()
    {
        $users = User::query();
        return DataTables::of($users)->editColumn('name', function (User $user) {
            return ucfirst($user->getAttribute('name'));
        })->addColumn('role', function (User $user) {
            return ucfirst($user->getRoleNames()->first() ?? __('Not selected'));
        })->addColumn('options', function (User $user) {
            return view('app.admin.includes.table-elements.action-buttons', [
                'modelName' => 'user',
                'userId' => $user->getAttribute('id'),
                'editUrl' => route('admin:users.edit', $user->getAttribute('id')),
                'deleteUrl' => route('admin:users.destroy', $user->getAttribute('id'))
            ]);
        })->toJson();
    }
}
