<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Laravel\Socialite\Facades\Socialite;
use App\Models\User;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use GuzzleHttp\Client;

class GoogleController extends Controller
{
    public function redirectToGoogle(Request $request)
    {
        $clientId = config('services.google.client_id');
        $redirectUri = config('services.google.redirect');
        $scopes = [
            'https://www.googleapis.com/auth/userinfo.email',
            'https://www.googleapis.com/auth/userinfo.profile',
            'openid',
        ];

        $query = http_build_query([
            'client_id' => $clientId,
            'redirect_uri' => $redirectUri,
            'response_type' => 'code',
            'scope' => implode(' ', $scopes),
            'access_type' => 'offline',
            'prompt' => 'select_account',
        ]);

        $authUrl = 'https://accounts.google.com/o/oauth2/v2/auth?' . $query;

        Log::info('Redirecting to Google', ['url' => $authUrl]);

        return redirect($authUrl);
    }

    public function handleGoogleCallback(Request $request)
    {
        try {
            if (!$request->has('code')) {
                throw new \Exception('Kode otorisasi tidak ditemukan');
            }

            $code = $request->input('code');
            Log::info('Google Callback Reached', ['code' => $code]);

            $client = new Client();
            $response = $client->post('https://oauth2.googleapis.com/token', [
                'form_params' => [
                    'code' => $code,
                    'client_id' => config('services.google.client_id'),
                    'client_secret' => config('services.google.client_secret'),
                    'redirect_uri' => config('services.google.redirect'),
                    'grant_type' => 'authorization_code',
                ],
                'verify' => false, // Hanya untuk pengujian, sebaiknya dihapus di produksi
            ]);

            $tokenData = json_decode($response->getBody()->getContents(), true);
            Log::info('Google Access Token Response', ['response' => $tokenData]);

            $response = $client->get('https://www.googleapis.com/oauth2/v2/userinfo', [
                'headers' => [
                    'Authorization' => 'Bearer ' . $tokenData['access_token'],
                ],
                'verify' => false, // Hanya untuk pengujian, sebaiknya dihapus di produksi
            ]);

            $userData = json_decode($response->getBody()->getContents(), true);
            Log::info('Google User Data', ['user_data' => $userData]);

            $user = User::updateOrCreate(
                ['email' => $userData['email']],
                [
                    'nama_lengkap' => $userData['name'],
                    'foto_profil' => $userData['picture'] ?? null
                ]
            );

            Auth::login($user, true);
            Log::info('User Authenticated', [
                'user_id' => $user->id_user,
                'email' => $user->email,
            ]);

            $kuesionerls = KuesionerLearningStyle::where('email', $user->email)->first();
            $kuesionermeta = KuesionerMetakognitif::where('category', $user->category_meta)->first();
            return view('main.page.beranda.beranda', compact('kuesionerls', 'kuesionermeta'));

        } catch (\Exception $e) {
            Log::error('Google Login Failed', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
                'request' => $request->all(),
            ]);

            return redirect()->route('login')->with('error', 'Login dengan Google gagal: ' . $e->getMessage());
        }
    }
}
