<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;

class WebAuthController extends Controller
{
    /**
     * Handle web-based login using session authentication
     */
    public function sessionLogin(LoginRequest $request)
    {
        $data = $request->validated();
        $identifier = $data['identifier'];
        $password = $data['password'];

        // Find user by email or username
        $user = User::where('email', $identifier)
            ->orWhere('username', $identifier)
            ->first();

        if (!$user || !Hash::check($password, $user->password)) {
            throw ValidationException::withMessages([
                'identifier' => ['Email/username atau password yang diberikan salah.'],
            ]);
        }

        // Login using session guard (creates session cookies)
        Auth::guard('web')->login($user, false);
        $request->session()->regenerate();

        if ($request->expectsJson()) {
            return response()->json([
                'success' => true,
                'message' => 'Login berhasil',
                'user' => [
                    'id' => $user->id,
                    'name' => $user->name,
                    'email' => $user->email,
                    'username' => $user->username,
                ],
            ]);
        }

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

    /**
     * Handle web-based logout (clears session cookies)
     */
    public function sessionLogout(Request $request)
    {
        $user = Auth::user();

        // Logout from session
        Auth::guard('web')->logout();

        // Clear remember token if exists
        if ($user) {
            $user->setRememberToken(Str::random(60));
            $user->save();
        }

        // Invalidate session and regenerate CSRF token
        $request->session()->invalidate();
        $request->session()->regenerateToken();

        // Clear authentication cookies
        Cookie::queue(Cookie::forget(Auth::getRecallerName()));
        Cookie::queue(Cookie::forget(config('session.cookie')));
        Cookie::queue(Cookie::forget('XSRF-TOKEN'));

        if ($request->expectsJson()) {
            return response()->json([
                'success' => true,
                'message' => 'Logout berhasil'
            ]);
        }

        return redirect()->route('login.index')->with('message', 'Anda telah berhasil logout');
    }
}
