<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Setting;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;
use Laravel\Socialite\Facades\Socialite;
use Illuminate\Support\Facades\Http;
use PragmaRX\Google2FA\Google2FA;

class AuthController extends Controller
{
    private function configureSMTP()
    {
        if (Setting::val('smtp_host')) {
            config([
                'mail.default' => 'smtp',
                'mail.mailers.smtp.host' => Setting::val('smtp_host'),
                'mail.mailers.smtp.port' => Setting::val('smtp_port'),
                'mail.mailers.smtp.username' => Setting::val('smtp_username'),
                'mail.mailers.smtp.password' => Setting::val('smtp_password'),
                'mail.mailers.smtp.encryption' => Setting::val('smtp_encryption'),
                'mail.from.address' => Setting::val('mail_from_address'),
                'mail.from.name' => Setting::val('site_name', 'Support'),
            ]);
        }
    }

    public function showLogin() { return view('auth.login'); }
    public function showRegister() { return view('auth.register'); }

    private function verifyCaptcha($token)
    {
        $secret = Setting::val('recaptcha_secret_key');
        if(!$secret) return true; 
        
        $response = Http::asForm()->post('https://www.google.com/recaptcha/api/siteverify', [
            'secret' => $secret,
            'response' => $token,
        ]);
        return $response->json()['success'] ?? false;
    }

    public function loginPost(Request $request)
    {
        $request->validate(['email' => 'required', 'password' => 'required']);

        if(Setting::val('enable_captcha') == 'yes') {
            if(!$request->has('g-recaptcha-response') || !$this->verifyCaptcha($request->input('g-recaptcha-response'))) {
                return back()->with('error', 'Captcha verification failed!');
            }
        }

        $fieldType = filter_var($request->email, FILTER_VALIDATE_EMAIL) ? 'email' : 'username';

        if (Auth::attempt([$fieldType => $request->email, 'password' => $request->password, 'status' => 'active'], $request->has('remember'))) {
            $user = Auth::user();

            if ($user->two_factor_enabled) {
                session(['2fa_pending_user_id' => $user->id]);
                Auth::logout();
                return redirect()->route('2fa.verify');
            }

            return redirect()->route('dashboard')->with('success', 'সফলভাবে লগিন হয়েছে!');
        }

        return back()->with('error', 'ইমেইল/ইউজারনেম, পাসওয়ার্ড ভুল অথবা একাউন্ট সাসপেন্ড করা হয়েছে!')->withInput();
    }

    public function registerPost(Request $request)
    {
        $request->validate([
            'username' => 'required|unique:users,username|alpha_dash',
            'email' => 'required|email|unique:users,email',
            'phone' => 'required',
            'password' => 'required|min:6',
        ]);

        if(Setting::val('enable_captcha') == 'yes') {
            if(!$request->has('g-recaptcha-response') || !$this->verifyCaptcha($request->input('g-recaptcha-response'))) {
                return back()->with('error', 'Captcha verification failed!');
            }
        }

        $referral_code = strtoupper(substr(md5(uniqid(mt_rand(), true)), 0, 8));
        $verification_token = Str::random(60);
        $needs_verification = (Setting::val('enable_email_verify') == 'yes');

        $user = User::create([
            'username' => $request->username,
            'email' => $request->email,
            'phone' => $request->phone,
            'password' => Hash::make($request->password),
            'balance' => 0.00,
            'status' => 'active',
            'referral_code' => $referral_code,
            'email_verified_at' => $needs_verification ? null : now(),
            'remember_token' => $verification_token
        ]);

        if($needs_verification) {
            $this->configureSMTP();
            $verifyLink = route('verification.verify', $verification_token);
            try {
                Mail::html("<h3>Welcome to " . Setting::val('site_name') . "!</h3><br><p>Please click the link below to verify your email address:</p><br><a href='{$verifyLink}' style='background:blue;color:white;padding:10px 20px;text-decoration:none;'>Verify Email</a>", function($msg) use ($user) {
                    $msg->to($user->email)->subject('Verify your email address');
                });
            } catch (\Exception $e) {}
            
            return redirect()->route('login')->with('success', 'একাউন্ট তৈরি হয়েছে! দয়া করে আপনার ইমেইল চেক করে ভেরিফাই করুন।');
        }

        Auth::login($user);
        return redirect()->route('dashboard')->with('success', 'একাউন্ট সফলভাবে তৈরি হয়েছে!');
    }

    public function redirectToGoogle()
    {
        if(Setting::val('enable_google_login') != 'yes') return back()->with('error', 'Google Login is disabled.');
        config(['services.google.client_id' => Setting::val('google_client_id'), 'services.google.client_secret' => Setting::val('google_client_secret'), 'services.google.redirect' => route('google.login') . '/callback']);
        return Socialite::driver('google')->redirect();
    }

    public function handleGoogleCallback()
    {
        try {
            config(['services.google.client_id' => Setting::val('google_client_id'), 'services.google.client_secret' => Setting::val('google_client_secret'), 'services.google.redirect' => route('google.login') . '/callback']);
            $googleUser = Socialite::driver('google')->user();
            $user = User::where('email', $googleUser->email)->first();

            if($user) {
                if ($user->two_factor_enabled) {
                    session(['2fa_pending_user_id' => $user->id]);
                    return redirect()->route('2fa.verify');
                }
                Auth::login($user);
                return redirect()->route('dashboard')->with('success', 'Logged in with Google!');
            } else {
                $newUser = User::create([
                    'username' => strtolower(str_replace(' ', '', $googleUser->name)) . rand(100, 999),
                    'email' => $googleUser->email,
                    'phone' => 'N/A',
                    'password' => Hash::make(Str::random(16)),
                    'balance' => 0.00,
                    'status' => 'active',
                    'referral_code' => strtoupper(substr(md5(uniqid(mt_rand(), true)), 0, 8)),
                    'email_verified_at' => now()
                ]);
                Auth::login($newUser);
                return redirect()->route('dashboard')->with('success', 'Account created with Google!');
            }
        } catch (\Exception $e) { return redirect()->route('login')->with('error', 'Google Login Failed!'); }
    }

    public function showForgotForm() { return view('auth.forgot-password'); }

    public function sendResetLink(Request $request)
    {
        $request->validate(['email' => 'required|email|exists:users,email']);
        $token = Str::random(60);
        
        DB::table('password_resets')->updateOrInsert(
            ['email' => $request->email],
            ['token' => Hash::make($token), 'created_at' => now()]
        );

        $this->configureSMTP();
        $resetLink = route('password.reset', $token) . "?email=" . $request->email;
        
        try {
            Mail::html("<h3>Password Reset Request</h3><br><p>Click the link below to reset your password:</p><br><a href='{$resetLink}' style='background:blue;color:white;padding:10px 20px;text-decoration:none;'>Reset Password</a>", function($msg) use ($request) {
                $msg->to($request->email)->subject('Password Reset Request');
            });
            return back()->with('status', 'We have emailed your password reset link!');
        } catch (\Exception $e) {
            return back()->with('error', 'Failed to send email. Check SMTP settings.');
        }
    }

    public function showResetForm($token) { return view('auth.reset-password', ['token' => $token]); }

    public function resetPassword(Request $request)
    {
        $request->validate(['email' => 'required|email|exists:users,email', 'password' => 'required|min:6|confirmed', 'token' => 'required']);
        $resetRecord = DB::table('password_resets')->where('email', $request->email)->first();

        if(!$resetRecord || !Hash::check($request->token, $resetRecord->token)) return back()->with('error', 'Invalid or expired token!');

        User::where('email', $request->email)->update(['password' => Hash::make($request->password)]);
        DB::table('password_resets')->where('email', $request->email)->delete();

        return redirect()->route('login')->with('success', 'Password reset successfully! You can now login.');
    }

    public function showVerifyEmail() { return view('auth.verify-email'); }
    
    public function verifyEmail($token)
    {
        $user = User::where('remember_token', $token)->first();
        if($user) {
            $user->email_verified_at = now();
            $user->remember_token = null;
            $user->save();
            Auth::login($user);
            return redirect()->route('dashboard')->with('success', 'Email verified successfully!');
        }
        return redirect()->route('login')->with('error', 'Invalid verification token!');
    }

    public function show2faForm() { 
        if(!session('2fa_pending_user_id')) return redirect()->route('login');
        return view('auth.2fa-verify'); 
    }

    public function verify2fa(Request $request)
    {
        $request->validate(['one_time_password' => 'required']);
        $userId = session('2fa_pending_user_id');
        if (!$userId) return redirect()->route('login');
        
        $user = User::find($userId);
        $google2fa = new Google2FA();
        
        if ($google2fa->verifyKey($user->two_factor_secret, $request->one_time_password)) {
            Auth::loginUsingId($userId);
            session()->forget('2fa_pending_user_id');
            return redirect()->route('dashboard')->with('success', 'লগিন সফল হয়েছে!');
        }
        return back()->with('error', 'Invalid 2FA Code!');
    }

    public function logout()
    {
        Auth::logout();
        session()->flush();
        return redirect()->route('login');
    }
}
