<?php

namespace App\Http\Controllers;

use App\Http\Requests\UserRequest;
use App\Http\Resources\UserResource;
use Illuminate\Support\Facades\DB;
use App\Mail\WelcomePassword;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Password;
use Keygen\Keygen;

class UserAdminController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        try{
            $perPage = $request->per_page ? intval($request->per_page) : 10;
            $page = $request->page ? intval($request->page) : 1;
            $orderBy = $request->orderBy ? strval($request->orderBy) : 'id';
            $orderDir = $request->orderDir ? strval($request->orderDir) : 'DESC';
            $term = $request->term ? strval($request->term) : "";

            $users = User::SearchUsers($perPage,$page,$orderBy,$orderDir,$term);

            if(isset(($users['error']))){
                throw new \Exception("Estamos com algum instabilidade no momento. Tente novamente em instantes.");
            }
            return response()->json($users,200);

        }catch(\Exception $e){
            return response()->json(['errors' => ['message'=>[$e->getMessage()]]],404);
        }
        
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(UserRequest $request)
    {
        try{
            DB::beginTransaction();
            $user = User::create($request->all());

            $user->assignRole('admin');

            if(empty($request->password)){
                $this->sendPassword($user);
            }
            DB::commit();
        }catch(\Exception $ex){
            DB::rollBack();
            return response()->json(['error' => $ex->getMessage()],401);
        }

        return response()->json($user,201);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        try{
            $user = User::findOrfail($id);
        }catch(\Exception $ex){
            return response()->json(['error' => 'Usuário não encontrado!'],404);
        }

        return response()->json($user,200);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(UserRequest $request, $id)
    {
        try{

            $user = User::findOrfail($id);

            $user->update($request->all());

        }catch(\Exception $ex){
            return response()->json(['error' => $ex->getMessage()],404);
        }

        return response()->json($user,200);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        try{
            $user = User::findOrfail($id);
            $user->delete();

        }catch(\Exception $ex){
            return response()->json(['error' => $ex->getMessage()],404);
        }

        return response()->json(['success' => 'Usuário excluído com êxito'],200);
    }

    
    /**
   * Send email with password
   * @param User $user
   * @return Response
   */
    protected function sendPassword(User $user)
    {
        try {
            $password = Keygen::alphanum(8)->generate('strtolower');
            //$hashed_random_password = Hash::make($password);
            $user->password = $password;
            $user->save();
            Mail::to($user)->send(new WelcomePassword($password));
            Password::deleteToken($user);

            return true;
        } catch (\Exception $e) {
            return false;
        }
    }

}
