<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use App\Models\User;
use App\Repositories\Interfaces\Auth\SocialAuthRepositoryInterface;
use App\Traits\EmailHandlerTrait;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Laravel\Socialite\Facades\Socialite;
use Illuminate\Support\Facades\Config;
use ReCaptcha\ReCaptcha;

class AuthenticatedSessionController extends Controller
{
    use EmailHandlerTrait;

    protected $socialAuthRepo;

    public function __construct(SocialAuthRepositoryInterface $socialAuthRepo)
    {
        $this->socialAuthRepo = $socialAuthRepo;
    }

    /**
     * Display the login view.
     */
    public function create(Request $request)
    {
        if ($request->ajax()) {
            return view('auth.login');
        }
        return redirect('/');
    }

    public function google_config()
    {
        Config::set('services.google.client_id', get_config('google_client_id'));
        Config::set('services.google.client_secret', get_config('google_client_secret'));
        Config::set('services.google.redirect', route('auth.google.callback'));
    }
    public function facebook_config()
    {
        Config::set('services.facebook.client_id', get_config('facebook_client_id'));
        Config::set('services.facebook.client_secret', get_config('facebook_client_secret'));
        Config::set('services.facebook.redirect', route('auth.facebook.callback'));
    }

    /**
     * Handle an incoming authentication request.
     */
    public function store(LoginRequest $request)
    {
        if (get_config('is_recaptcha_activated')) {
            $secret = get_config('recaptcha_secret_key');
            if (!$secret) {
                return back()->withInput()->with('error_message', __('recaptcha_secret_missing'));
            }
            $recaptcha = new ReCaptcha($secret);
            $response = $recaptcha->verify($request->input('g-recaptcha-response'), $request->ip());
            if (!$response->isSuccess()) {
                return back()->withInput()->with('error_message', __('please_verify_that_you_are_not_a_robot'));
            }
        }
        $user = User::where('email', $request->email)->first();
        if (!$user) {
            return response()->json([
                'type' => 'email',
                'success' => false,
                'message' => 'User not found'
            ]);
        }
        if (!Hash::check($request->password, $user->password)) {
            return response()->json([
                'type' => 'password',
                'success' => false,
                'message' => "Password wrong"
            ]);
        }

        $request->authenticate();
        $request->session()->regenerate();

        return response()->json([
            'success' => true,
            'redirect_url' => route('admin.dashboard')
        ]);;
    }

    /**
     * Destroy an authenticated session.
     */
    public function destroy(Request $request): RedirectResponse
    {
        Auth::guard('web')->logout();

        $request->session()->invalidate();

        $request->session()->regenerateToken();

        return redirect('/');
    }
    public function redirectToGoogle()
    {
        $this->google_config();
        return Socialite::driver('google')->redirect();
    }

    public function handleGoogleCallback()
    {
        $this->google_config(); // ensure config loaded
        $googleUser = Socialite::driver('google')->stateless()->user();

        $user = $this->socialAuthRepo->findOrCreateUserFromSocialite($googleUser);

        Auth::login($user);

        return redirect()->route('admin.dashboard');
    }
    public function redirectToFacebook()
    {
        $this->facebook_config();
        return Socialite::driver('facebook')->redirect();
    }

    public function handleFacebookCallback()
    {
        $this->facebook_config();
        $facebookUser = Socialite::driver('facebook')->stateless()->user();

        $user = $this->socialAuthRepo->findOrCreateUserFromSocialite($facebookUser);

        Auth::login($user);

        return redirect()->route('admin.dashboard');
    }

    public function phone_auth_view()
    {
        return view('auth.phone-login');
    }
    public function verifyOtpModal()
    {
        return view('auth.verify_otp');
    }

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

        try {
            $this->sendOtpRequestToPhone($request->phone);

            return response()->json(['message' => 'OTP sent']);
        } catch (\Exception $e) {
            Log::error($e->getMessage());
            return response()->json([
                'error' => 'Failed to send OTP',
                'details' => $e->getMessage()
            ], 500);
        }
    }

    public function verifyOtpPost(Request $request)
    {
        $request->validate([
            'phone' => 'required|string',
            'otp' => 'required|string'
        ]);

        $result = $this->verifyOtp($request->phone, $request->otp);

        if ($result['code'] !== 200) {
            return response()->json([
                'error' => $result['message']
            ], 400);
        }

        $user = User::where('phone', $request->phone)->first();

        if ($user) {
            auth()->login($user);

            return response()->json([
                'success' => 'OTP verified successfully',
                'redirect' => route('admin.dashboard')
            ]);
        }

        return response()->json([
            'error' => 'User not found after OTP verification'
        ], 404);
    }
}
