<?php

namespace App\Http\Controllers;

use App\Models\User;
use Spatie\Permission\Models\Role;
use Illuminate\Http\Request;

class UserController extends Controller {

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index() {
        $users = User::paginate(5);
        return view('users.index', compact('users'));
    }

    /**
     * Display a search listing of the resource.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function search(Request $request) {
        $oldSearch = $request->search;
        $users = User::where('name', 'like', '%' . $request->search . '%')
                ->orWhere('email', 'like', '%' . $request->search . '%')
                ->paginate(5);
        
        return view('users.index', compact('oldSearch', 'users'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create() {
        $roles = Role::all();
        
        return view('users.create', compact('roles'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request) {
        $input = $request->validate([
            'name' => 'required|string|max:255|unique:users,name',
            'email' => 'required|string|email|max:255|unique:users,email',
            'password' => 'required|string|min:8',
            'image' => 'nullable|image|mimes:jpeg,jpg,gif,png,svg,webp|max:2048',
            'role_id' => 'required|numeric|integer|exists:roles,id'
        ]);

        $input['password'] = bcrypt($input['password']);

        if ($request->file('image')) {
            $image = $request->file('image');
            $imageDestinationPath = 'data/images/users/';
            $userImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
            $image->move($imageDestinationPath, $userImage);
            $input['image'] = '/' . $imageDestinationPath . $userImage;
        } else {
            unset($input['image']);
        }
        
        $roleId = $input['role_id'];
        unset($input['role_id']);

        User::create($input)->assignRole($roleId);

        return redirect()->route('users.index')
                        ->with('success', 'User added successfully.');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\User  $user
     * @return \Illuminate\Http\Response
     */
    public function show(User $user) {
        $roles = Role::all();

        $role = null;

        foreach ($roles as $currentRole) {
            if ($user->hasRole($currentRole->name)) {
                $role = $currentRole;
                break;
            }
        }
        
        return view('users.show', compact('user', 'role'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\User  $user
     * @return \Illuminate\Http\Response
     */
    public function edit(User $user) {
        $roles = Role::all();
        
        return view('users.edit', compact('user', 'roles'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\User  $user
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, User $user) {
        $input = $request->validate([
            'name' => 'required|string|max:255|unique:users,name,' . $user->id,
            'email' => 'required|string|email|max:255|unique:users,email,' . $user->id,
            'password' => 'nullable|string|min:8',
            'image' => 'nullable|image|mimes:jpeg,jpg,gif,png,svg,webp|max:2048',
            'role_id' => 'required|numeric|integer|exists:roles,id'
        ]);
        
        if ($input['password']) {
            $input['password'] = bcrypt($input['password']);
        } else {
            unset($input['password']);
        }

        if ($request->file('image')) {
            $image = $request->file('image');
            $imageDestinationPath = 'data/images/users/';
            $userImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
            $image->move($imageDestinationPath, $userImage);
            $input['image'] = '/' . $imageDestinationPath . $userImage;
        } else {
            unset($input['image']);
        }
        
        $roleId = $input['role_id'];
        unset($input['role_id']);

        $user->update($input);
        $user->roles()->sync([$roleId]);

        return redirect()->route('users.index')
                        ->with('success', 'User modified successfully.');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\User  $user
     * @return \Illuminate\Http\Response
     */
    public function destroy(User $user) {
        $user->delete();
        return redirect()->route('users.index')
                        ->with('success', 'User removed successfully.');
    }

}
