<?php

namespace App\Http\Controllers;

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

use App\Models\User;

class AuthController extends Controller
{
    public function login(Request $request) {
        // dd($request->all());
        try {
            $credentials = $request->validate([
                'email' => ['required', 'email'],
                'password' => ['required'],
            ]);

            if (!Auth::attempt($credentials)) return response()->json('Usuario o contraseña inválida', 400);
            $token = $request->user()->createToken('Personal Access Token')->plainTextToken;

            $getUser = User::with([
                    'profile.profilePagesPackage.page',
                    'profile.profilePagesPackage.package',
                    'profile.profilePagesPackage.package.actions'
                ])
                ->find($request->user()->id);

            return response()->json([
                'usuario' => $getUser,
                'access_token' => $token,
                'token_type' => 'Bearer'
            ], 200);

        } catch (Exception $e) {
            return response()->json('Error - Login ' . $e, 500);
        }
    }

    public function register(Request $request) {
        try {
            DB::beginTransaction();
            $newUser = new User;
            $newUser->name = $request->name;
            $newUser->email = $request->email;
            $newUser->password = Hash::make($request->password);
            $newUser->save();

            DB::commit();
            return response()->json('Usuario registrado con éxito', 201);
        } catch (Exception $e) {
            DB::rollback();
            return response()->json('Error - Register ' . $e, 500);
        }
    }

    public function logout(Request $request)
    {
        $request->user()->tokens()->delete();
        return response()->json('¡Sección cerrada con éxito!', 200);
    }

    public function getUser() {
        $getUser = User::with([
                'profile.profilePagesPackage.page',
                'profile.profilePagesPackage.package',
                'profile.profilePagesPackage.package.actions'
            ])
            ->find(Auth::id());

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

}
