<?php

namespace App\Http\Controllers;

use Auth;
use Laravel\Socialite\Facades\Socialite;
use Exception;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Hash;

class OauthController extends Controller
{
    public function redirectToProvider()
    {
        return Socialite::driver('google')->redirect();
    }
    public function handleProviderCallback(Request $request)
    {
        try {
            $ipAddress = $request->ip();

            $user = Socialite::driver('google')->user();
    
            $finduser = User::where('gauth_id', $user->id)->first();
    
            if ($finduser) {
                if(get_setting('maintenance_status') == 'on') {
                    if($finduser->role != 'Superadmin') {
                        Auth::logout();
                        return redirect('/login')->withErrors(['error' => 'Website is under Maintenance, only Admins can login.']);
                    }
                }
                if ($finduser->banned == 1) {
                    Auth::logout();
                    return redirect('/login')->withErrors(['error' => 'Access denied: Account Banned.']);
                }
                Auth::login($finduser);
                create_notification('Login Successful', "Logged in successfully from IP: $ipAddress", 'system');
                return redirect('/dashboard');
            }
    
            $existingUser = User::where('email', $user->email)->first();
    
            if ($existingUser) {
                if(get_setting('maintenance_status') == 'on') {
                    if($existingUser->role != 'Superadmin') {
                        Auth::logout();
                        return redirect('/login')->withErrors(['error' => 'Website is under Maintenance, only Admins can login.']);
                    }
                }
                if ($existingUser->banned == 1) {
                    Auth::logout();
                    return redirect('/login')->withErrors(['error' => 'Access denied: Account Banned.']);
                }
                $existingUser->update([
                    'gauth_id' => $user->id,
                    'gauth_type' => 'google',
                ]);
    
                Auth::login($existingUser);
                create_notification('Login Successful', "Logged in successfully from IP: $ipAddress", 'system');
                return redirect('/dashboard');
            }
            if(get_setting('maintenance_status') == 'on') {
                Auth::logout();
                return redirect('/login')->withErrors(['error' => 'Website is under Maintenance, only Admins can login.']);
            }
            $referrerId = session('referrer') ? User::where('id', session('referrer'))->value('id') : null;
            
            $password = Str::random(16);
            $newUser = User::create([
                'name' => $user->name,
                'email' => $user->email,
                'password' => Hash::make($password),
                'gauth_id' => $user->id,
                'gauth_type' => 'google',
                'email_verified_at' => now()->timestamp,
                'role' => 'Member',
                'balance' => 0.000000,
                'deposited' => 0.000000,
                'available_deposit' => 0.000000,
                'total_earned' => 0.000000,
                'today_earned' => 0.000000,
                'ip_address' => $ipAddress,
                'last_login_ip' => $ipAddress,
                'country' => 'Unknown',
                'last_active' => now()->timestamp,
                'referred_by' => $referrerId ?? 0,
            ]);
    
            session()->forget('referrer');
    
            Auth::login($newUser);
            return redirect('/dashboard');
    
        } catch (Exception $e) {
            return redirect('/login')->with('error', 'Gagal login: ' . $e->getMessage());
        }
    }

}