<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Str;
use App\Models\User;
use App\Models\Divisi;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{
    public function showLogin()
    {
        return view('auth.login');
    }

    public function login(Request $req)
    {
        // Validasi dasar
        $validated = $req->validate([
            'email' => 'required|email',
            'password' => 'required',
            'g-recaptcha-response' => 'required',
        ]);

        $throttleKey = Str::lower($req->input('email')).'|'.$req->ip();

        // Batasi percobaan (mis. 5 percobaan)
        if (RateLimiter::tooManyAttempts($throttleKey, 5)) {
            $seconds = RateLimiter::availableIn($throttleKey);
            return back()->withErrors([
                'email' => "Terlalu banyak percobaan. Coba lagi dalam {$seconds} detik."
            ])->withInput();
        }

        // Verifikasi reCAPTCHA ke Google
        $recaptchaResponse = $req->input('g-recaptcha-response');
        $secret = config('services.recaptcha.secret');

        try {
            $verify = Http::asForm()->post('https://www.google.com/recaptcha/api/siteverify', [
                'secret' => $secret,
                'response' => $recaptchaResponse,
                'remoteip' => $req->ip(),
            ]);
        } catch (\Throwable $e) {
            // Jika http request gagal
            RateLimiter::hit($throttleKey, 60);
            return back()->withErrors([
                'email' => 'Gagal memverifikasi reCAPTCHA. Coba lagi.'
            ])->withInput();
        }

        $recapResult = $verify->json();

        if (!isset($recapResult['success']) || $recapResult['success'] !== true) {
            // reCAPTCHA gagal -> hit rate limiter
            RateLimiter::hit($throttleKey, 60);
            return back()->withErrors([
                'email' => 'Verifikasi reCAPTCHA gagal. Silakan centang kotak "Saya bukan robot".'
            ])->withInput();
        }

        // Coba autentikasi
        if (Auth::attempt(['email' => $validated['email'], 'password' => $validated['password']], $req->filled('remember'))) {
            RateLimiter::clear($throttleKey);
            $req->session()->regenerate();
            $req->session()->put('show_verification_login_notice', true);

            if (Auth::user()->mustChangePassword()) {
                return redirect()->route('password.force.edit');
            }

            return redirect()->intended(route('dashboard'));
        }

        // Gagal autentikasi -> tambahkan percobaan
        RateLimiter::hit($throttleKey, 60);

        return back()->withErrors([
            'email' => 'Email atau password yang Anda masukkan salah.'
        ])->withInput();
    }

    public function showRegister()
    {
        $divisis = Divisi::all();
        return view('auth.register', compact('divisis'));
    }

    public function register(Request $req)
    {
        $req->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users,email',
            'password' => 'required|confirmed|min:6',
        ]);

        $user = User::create([
            'name' => $req->name,
            'email' => $req->email,
            'password' => Hash::make($req->password),
            'password_changed_at' => now(),
            'divisi_id' => $req->divisi_id ?? null,
            'role' => 'user',
            'phone' => $req->phone ?? null,
        ]);

        Auth::login($user);
        return redirect()->route('dashboard');
    }

    public function logout(Request $req)
    {
        Auth::logout();
        $req->session()->invalidate();
        $req->session()->regenerateToken();
        return redirect()->route('login');
    }
}
