<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

use App\Models\User;

class UsersController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $filter = json_decode($request->get('filter'));

        $getUsers = User::with('profile')
            ->where('name', 'LIKE', '%' . $filter->name . '%')
            ->where('email', 'LIKE', '%' . $filter->email . '%');

        if(isset($filter->profile) && $filter->profile) {
            $getUsers = $getUsers->whereHas('profile', function($query) use ($filter) {
                $query->where('name', 'LIKE', '%' . $filter->profile . '%');
            });
        }

        $getUsers = $getUsers->orderBy('id', 'DESC')->paginate($request->get('rows'));

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

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        try {
            if(User::where('email', $request->email)->exists()) return response()->json('El usuario ya se encuentra registrado.', 400);

            DB::beginTransaction();

            $newUser = new User;
            $newUser->name = $request->name;
            $newUser->email = $request->email;
            $newUser->password = Hash::make('12345678');
            $newUser->id_profile = $request->profile['id'];
            $newUser->save();

            DB::commit();
            return response()->json('Usuario guardado con éxito', 201);
        } catch (Exception $th) {
            DB::rollback();
            return response()->json('[Error - UsersController@store]: ' . $th, 500); 
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        $getUser = User::with('profile')->find($id);
        return response()->json($getUser, 200);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        try {
            DB::beginTransaction();

            $updateUser = User::find($id);
            $updateUser->name = $request->name;
            $updateUser->email = $request->email;
            $updateUser->id_profile = $request->profile['id'];
            $updateUser->save();

            DB::commit();
            return response()->json('Usuario editado con éxito', 200);
        } catch (Exception $th) {
            DB::rollback();
            return response()->json('[Error - UsersController@update]: ' . $th, 500); 
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        try {
            DB::beginTransaction();

            $updateUser = User::find($id);
            $updateUser->active = $updateUser->active == 1 ? 0 : 1;
            $updateUser->save();

            DB::commit();
            return response()->json('Cambio de estatus con éxito', 200);
        } catch (Exception $th) {
            DB::rollback();
            return response()->json('[Error - UserController@destroy]: ' . $th, 500);
        }
    }
}
