<?php

namespace Modules\Users\Http\Controllers;

use Illuminate\Http\Request;
use Modules\Users\Entities\Users;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Contracts\Support\Renderable;

class UsersAdminController extends Controller
{
    /**
     * Display a listing of the resource.
     * @return Renderable
     */
    public function index()
    {
        $users = Users::paginate(9);

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

    /**
     * Show the form for creating a new resource.
     * @return Renderable
     */
    public function create()
    {
        return view('users::create');
    }

    /**
     * Store a newly created resource in storage.
     * @param Request $request
     * @return Renderable
     */
    public function store(Request $request)
    {
        $data = $request->all();


        $name = $data['name'];
        $email = $data['email'];
        $username = $data['username'];
        $password = $data['password'];

        $user = new Users();

        $user->name = $name;
        $user->email = $email;
        $user->username = $username;
        $user->password = Hash::make($password);
                
        $user->save();

        return redirect()->route('admin.users.index');
    }

    /**
     * Show the specified resource.
     * @param int $id
     * @return Renderable
     */
    public function show($id)
    {
        return view('users::show');
    }

    /**
     * Show the form for editing the specified resource.
     * @param int $id
     * @return Renderable
     */
    public function edit($id)
    {
        return view('users::edit');
    }

    /**
     * Update the specified resource in storage.
     * @param Request $request
     * @param int $id
     * @return Renderable
     */
    public function update(Request $request)
    {
        $data = $request->all();

        $id = $data['id_user'];
        $name = $data['name'];
        $email = $data['email'];
        $username = $data['username'];
        $password = isset($data['password']) ? $data['password'] : false;

        $user = Users::where('id', $id)->first();
        $user->name = $name;
        $user->email = $email;
        $user->username = $username;
        if($password){
            $user->password = Hash::make($password);
        }
        
        $user->save();

        return redirect()->route('admin.users.index');
        
    }

    /**
     * Remove the specified resource from storage.
     * @param int $id
     * @return Renderable
     */
    public function destroy($id)
    {
        $user = Users::where('id', $id)->first();

        if($user){
            $user->delete();
        }

        return redirect()->route('admin.users.index');
    }
}
