<?php

namespace App\Http\Controllers\Admin\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class OturumController extends Controller
{
    public function showLoginForm()
    {
        return view('admin.auth.login');
    }

    public function login(Request $request)
    {
        $request->validate([
            'kullanici_adi' => ['required', 'string'],
            'password' => ['required'],
        ]);

        $kurumId = $request->attributes->get('kurum_id') ?? 1;
        
        $credentials = [
            'kullanici_adi' => $request->kullanici_adi,
            'password' => $request->password,
            'kurum_id' => $kurumId,
            'aktif' => true,
        ];

        if (Auth::guard('admin')->attempt($credentials, $request->boolean('remember'))) {
            $request->session()->regenerate();
            return redirect()->intended(route('admin.dashboard'));
        }

        return back()->withErrors([
            'kullanici_adi' => 'Girilen bilgilerle eşleşen bir yönetici bulunamadı.',
        ])->onlyInput('kullanici_adi');
    }

    public function logout(Request $request)
    {
        Auth::guard('admin')->logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();
        return redirect()->route('admin.giris');
    }
}
