<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Http;
use Illuminate\View\View;

class AuthenticatedSessionController extends Controller
{
    /**
     * Display the login view.
     */
    public function create(): View
{
    return view('auth.auth', [
        'activeTab' => 'login'
    ]);
}
    /**
     * Handle an incoming authentication request.
     */
    public function store(LoginRequest $request): RedirectResponse
{
    // --- Cloudflare Turnstile Verification ---
    $token  = $request->input('cf-turnstile-response');
    $secret = config('services.turnstile.secret');

    if (!$token) {
        return back()->withErrors([
            'cf-turnstile' => 'Selesaikan Verifikasi Terlebih Dahulu !',
        ])->withInput();
    }

    $result = Http::asForm()
        ->timeout(15)
        ->post('https://challenges.cloudflare.com/turnstile/v0/siteverify', [
            'secret'   => $secret,
            'response' => $token,
        ])
        ->json();

    if (!($result['success'] ?? false)) {
        return back()->withErrors([
            'cf-turnstile' => 'Verifikasi keamanan gagal. Silakan coba lagi.',
        ])->withInput();
    }

    // --- Login Process ---
    $request->authenticate();

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

    \Log::info('LOGIN_SUCCESS', [
        'user'       => Auth::user()?->email,
        'session_id' => session()->getId(),
        'ip'         => $request->ip(),
        'path'       => $request->path(),
    ]);

    // Tentukan home berdasarkan halaman login
    $home = str_starts_with($request->path(), 'apk/')
        ? '/apk/dashboard'
        : '/dashboard';

    /**
     * Jangan redirect ke endpoint non UI
     */
    $intended = $request->session()->get('url.intended');

    if ($intended) {

        $path = parse_url($intended, PHP_URL_PATH) ?? '';

        $blockedPrefixes = [
            '/ajax',
            '/api',
        ];

        $blockedExact = [
            '/admin',
        ];

        foreach ($blockedPrefixes as $prefix) {

            if (str_starts_with($path, $prefix)) {

                $request->session()->forget('url.intended');

                return redirect($home);
            }
        }

        foreach ($blockedExact as $exact) {

            if (
                $path === $exact ||
                str_starts_with($path, $exact . '/')
            ) {

                $request->session()->forget('url.intended');

                return redirect($home);
            }
        }
    }

    return redirect()->intended($home);
}

    /**
     * Destroy an authenticated session.
     */
    public function destroy(Request $request): RedirectResponse
{
    $isApk = str_contains(
        url()->previous(),
        '/apk/'
    );

    Auth::guard('web')->logout();

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

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

    return redirect(
        $isApk
            ? '/apk/login'
            : '/login'
    );
}
}