<?php

namespace App\Http\Controllers\Auth;

use App\Models\User;
use App\Models\Verify_accounts;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Kreait\Laravel\Firebase\Facades\Firebase;

class AuthController extends Controller
{
    public function login(Request $request)
    {
        $request->validate([
            'email'    => 'required|string|email',
            'password' => 'required|string',
        ]);

        if (!Auth::attempt($request->only('email', 'password'))) {
            return response()->json(['message' => 'Unauthorized'], 401);
        }

        $user        = $request->user();
        $tokenResult = $user->createToken('Personal Access Token');

        if ($request->remember_me) {
            $tokenResult->token->expires_at = Carbon::now()->addWeeks(1);
            $tokenResult->token->save();
        }

        return response()->json([
            'access_token'  => $tokenResult->accessToken,
            'token_type'    => 'Bearer',
            'expires_at'    => Carbon::parse($tokenResult->token->expires_at)->toDateTimeString(),
            'userid'        => $user->id,
            'role'          => $user->role_id,
            'verified'      => $user->phone_verified_at,
            'reported'      => $user->reported,
            'profile_photo' => $user->profile_photo,
        ]);
    }

    public function firebase(Request $request)
    {
        $request->validate(['firebase_token' => 'required|string']);

        try {
            $verifiedToken = Firebase::auth()->verifyIdToken($request->firebase_token);
        } catch (\Throwable $e) {
            return response()->json(['message' => 'Token de Firebase inválido'], 401);
        }

        $uid     = $verifiedToken->claims()->get('sub');
        $email   = $verifiedToken->claims()->get('email');
        $name    = $verifiedToken->claims()->get('name') ?? 'Usuario';
        $picture = $verifiedToken->claims()->get('picture');

        // Buscar por firebase uid primero, luego por email para hacer merge si ya existía cuenta
        $user = User::where('social_id', 'firebase|' . $uid)->first();

        if (!$user && $email) {
            $user = User::where('email', $email)->first();
        }

        if ($user) {
            $changed = false;
            if (!$user->social_id) {
                $user->social_id = 'firebase|' . $uid;
                $changed = true;
            }
            if ($picture && $user->profile_photo !== $picture) {
                $user->profile_photo = $picture;
                $changed = true;
            }
            if ($changed) $user->save();
        } else {
            $user = User::create([
                'name'          => $name,
                'email'         => $email,
                'social_id'     => 'firebase|' . $uid,
                'role_id'       => 1,
                'password'      => null,
                'profile_photo' => $picture,
            ]);
        }

        $tokenResult = $user->createToken('Firebase Token');

        return response()->json([
            'access_token'  => $tokenResult->accessToken,
            'token_type'    => 'Bearer',
            'expires_at'    => Carbon::parse($tokenResult->token->expires_at)->toDateTimeString(),
            'userid'        => $user->id,
            'role'          => $user->role_id,
            'verified'      => $user->phone_verified_at,
            'reported'      => $user->reported,
            'profile_photo' => $user->profile_photo,
        ]);
    }

    public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name'     => 'required|string|regex:/(^[a-zA-Z\s ÑñÁáÉéÍíÓóÚúÜü]+$)+/',
            'email'    => 'required|string|email|unique:users',
            'phone'    => 'required|numeric',
            'password' => 'required|string',
            'secret'   => 'required|string',
        ], [
            'email.unique' => 'Correo electrónico ya registrado',
        ]);

        if ($validator->fails()) {
            return response()->json(['message' => $validator->messages()->first()], 422);
        }

        if ($request->secret !== config('app.pass')) {
            return response()->json(['message' => 'Unauthorized request'], 401);
        }

        $user = User::create([
            'name'     => $request->name,
            'email'    => $request->email,
            'phone'    => $request->phone,
            'password' => bcrypt($request->password),
            'role_id'  => 1,
        ]);

        return response()->json(['message' => 'Successfully created user!'], 201);
    }

    public function logout(Request $request)
    {
        $request->user()->currentAccessToken()->revoke();

        return response()->json(['message' => 'Successfully logged out']);
    }

    public function user(Request $request)
    {
        return response()->json($request->user());
    }

    public function verify(Request $request)
    {
        $user = $request->user();
        $user->phone              = $request->phone;
        $user->phone_verified_at  = now();
        $user->save();

        return response()->json(['message' => 'Successfully updated']);
    }

    public function checkemail($token)
    {
        $verifyUser = Verify_accounts::where('token', $token)->firstOrFail();

        User::create([
            'name'     => $verifyUser->name,
            'email'    => $verifyUser->email,
            'password' => $verifyUser->password,
            'role_id'  => 1,
        ]);

        Verify_accounts::destroy($verifyUser->id);
    }
}
