<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class AuthController extends Controller
{
    /**
     * Registro de usuario
     */
    public function register(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'name' => 'required|string|max:255|regex:/^[\pL\s\-]+$/u',
                'email' => 'required|email|unique:users,email|max:255',
                'password' => [
                    'required',
                    'string',
                    'min:8',
                    'confirmed',
                    'regex:/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/'
                ],
            ], [
                'password.regex' => 'La contraseña debe contener al menos una mayúscula, una minúscula, un número y un carácter especial.',
                'name.regex' => 'El nombre solo puede contener letras y espacios.',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'errors' => $validator->errors()
                ], 422);
            }

            $user = User::create([
                'name' => strip_tags(trim($request->name)),
                'email' => strtolower(trim($request->email)),
                'password' => Hash::make($request->password),
                'email_verified_at' => null,
            ]);

            $user->assignRole('administrador');


            Log::info('Usuario registrado', ['user_id' => $user->id, 'email' => $user->email]);

            $token = $user->createToken('api_token', ['*'], now()->addHours(12))->plainTextToken;

            return response()->json([
                'success' => true,
                'message' => 'Usuario registrado exitosamente',
                'user' => [
                    'id' => $user->id,
                    'name' => $user->name,
                    'email' => $user->email,
                    'roles' => $user->getRoleNames(),
                    'permissions' => $user->getAllPermissions()->pluck('name')
                ],
                'token' => $token,
                'token_type' => 'Bearer',
                'expires_in' => 12 * 60 * 60 
            ], 201);

        } catch (\Exception $e) {
            Log::error('Error en registro', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);

            return response()->json([
                'success' => false,
                'message' => 'Error en el servidor. Por favor, intente más tarde.'
            ], 500);
        }
    }

    public function login(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'email' => 'required|email|max:255',
                'password' => 'required|string',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'errors' => $validator->errors()
                ], 422);
            }

            $credentials = [
                'email' => strtolower(trim($request->email)),
                'password' => $request->password
            ];

            if (!Auth::attempt($credentials)) {

                Log::warning('Intento de login fallido', ['email' => $request->email]);
                
                return response()->json([
                    'success' => false,
                    'message' => 'Credenciales inválidas'
                ], 401);
            }

            $user = User::where('email', $credentials['email'])->firstOrFail();

            // Verificar si el usuario está activo (puedes agregar un campo 'is_active' después)
            // if (!$user->is_active) {
            //     return response()->json(['error' => 'Cuenta desactivada'], 403);
            // }

            $user->tokens()->delete();

            $token = $user->createToken('api_token', ['*'], now()->addHours(12))->plainTextToken;

            Log::info('Login exitoso', ['user_id' => $user->id]);

            return response()->json([
                'success' => true,
                'message' => 'Login exitoso',
                'user' => [
                    'id' => $user->id,
                    'name' => $user->name,
                    'email' => $user->email,
                    'roles' => $user->getRoleNames(),
                    'permissions' => $user->getAllPermissions()->pluck('name')
                ],
                'token' => $token,
                'token_type' => 'Bearer',
                'expires_in' => 12 * 60 * 60
            ]);

        } catch (\Exception $e) {
            Log::error('Error en login', [
                'error' => $e->getMessage(),
                'email' => $request->email
            ]);

            return response()->json([
                'success' => false,
                'message' => 'Error en el servidor. Por favor, intente más tarde.'
            ], 500);
        }
    }


    public function logout(Request $request)
    {
        try {
            if ($request->user()) {
                Log::info('Logout exitoso', ['user_id' => $request->user()->id]);

                $request->user()->tokens()->delete();
            }

            return response()->json([
                'success' => true,
                'message' => 'Sesión cerrada correctamente'
            ]);

        } catch (\Exception $e) {
            Log::error('Error en logout', ['error' => $e->getMessage()]);

            return response()->json([
                'success' => false,
                'message' => 'Error al cerrar sesión'
            ], 500);
        }
    }

 
    public function me(Request $request)
    {
        try {
            $user = $request->user();
            
            if (!$user) {
                return response()->json([
                    'success' => false,
                    'message' => 'Usuario no autenticado'
                ], 401);
            }

            return response()->json([
                'success' => true,
                'user' => [
                    'id' => $user->id,
                    'name' => $user->name,
                    'email' => $user->email,
                    'roles' => $user->getRoleNames(),
                    'permissions' => $user->getAllPermissions()->pluck('name')
                ]
            ]);

        } catch (\Exception $e) {
            Log::error('Error obteniendo usuario', ['error' => $e->getMessage()]);

            return response()->json([
                'success' => false,
                'message' => 'Error obteniendo información del usuario'
            ], 500);
        }
    }


    public function refresh(Request $request)
    {
        $user = $request->user();
        $user->tokens()->delete();
        
        $token = $user->createToken('api_token', ['*'], now()->addHours(12))->plainTextToken;

        return response()->json([
            'success' => true,
            'token' => $token,
            'token_type' => 'Bearer',
            'expires_in' => 12 * 60 * 60
        ]);
    }
}