<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\KuesionerLearningStyle;
use App\Models\KuesionerMetakognitif;
use Illuminate\Support\Facades\Log;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Auth;

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());
        }
    }

    public function loginGuest()
    {
        try {
            $user = User::where('email', 'guest@mail.com')->first();

            if (!$user) {
                throw new \Exception('Pengguna guest tidak ditemukan.');
                $user = User::create([
                    'email' => 'guest@mail.com',
                    'nama_lengkap' => 'Guest User',
                    'foto_profil' => null,
                ]);
            }

            Auth::login($user, true);
            Log::info('Guest 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('Guest Login Failed', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);

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

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

    public function loadDataKuesioner2()
    {
        $kuesionerls = KuesionerLearningStyle::where('email', Auth::user()->email)->first();
        $kuesionermeta = KuesionerMetakognitif::where('category', Auth::user()->category_meta)->first();
        return view('main.page.kuesioner.kuesioner', compact('kuesionerls', 'kuesionermeta'));
    }


    public function updateProfile(Request $request)
    {
        try {
            $validated = $request->validate([
                'nama_lengkap' => 'required|string|max:65',
                'nim' => 'required|string|max:20',
                'semester' => 'required|integer|min:1|max:14',
                'angkatan' => 'required|integer|min:2000|max:'.date('Y'),
                'foto_profil' => 'nullable|image|mimes:jpeg,png|max:15360',
            ]);

            $user = Auth::user();
            if (!$user) {
                throw new \Exception('Pengguna tidak ditemukan atau belum login');
            }

            $updateData = [
                'nama_lengkap' => $validated['nama_lengkap'],
                'nim' => $validated['nim'],
                'semester' => $validated['semester'],
                'angkatan' => $validated['angkatan'],
            ];

            if ($request->hasFile('foto_profil')) {
                // Hapus foto profil lama jika ada dan bukan dari Google
                if ($user->foto_profil && !str_contains($user->foto_profil, 'googleusercontent.com')) {
                    Storage::disk('public')->delete($user->foto_profil);
                }

                // Simpan foto baru
                $path = $request->file('foto_profil')->store('profile_photos', 'public');
                $updateData['foto_profil'] = $path;
            }

            // Perbarui data pengguna
            $user->update($updateData);

            Log::info('User Profile Updated', [
                'user_id' => $user->id_user,
                'email' => $user->email,
                'updated_data' => $updateData,
            ]);

            return redirect()->back()->with('success', 'Profil berhasil diperbarui');

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

            return redirect()->back()->with('error', 'Gagal memperbarui profil: ' . $e->getMessage());
        }
    }

    public function deleteProfilePhoto(Request $request)
    {
        try {
            $user = Auth::user();

            if (!$user) {
                throw new \Exception('Pengguna tidak ditemukan atau belum login');
            }

            // Hapus foto profil dari storage jika bukan dari Google
            if ($user->foto_profil && !str_contains($user->foto_profil, 'googleusercontent.com')) {
                Storage::disk('public')->delete($user->foto_profil);
            }

            $user->update(['foto_profil' => null]);

            Log::info('User Profile Photo Deleted', [
                'user_id' => $user->id_user,
                'email' => $user->email,
            ]);

            return redirect()->back()->with('success', 'Foto profil berhasil dihapus');

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

            return redirect()->back()->with('error', 'Gagal menghapus foto profil: ' . $e->getMessage());
        }
    }
}