<?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\View\View;

class AuthenticatedSessionController extends Controller
{
    /**
     * Display the login view.
     */
    public function create(): View
    {
        return view('auth.login');
    }

    /**
     * Handle an incoming authentication request.
     */
    public function store(LoginRequest $request): RedirectResponse
    {
        $request->authenticate();

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

        $user = Auth::user();
        
        // Cek apakah user aktif
        if (!$user->is_active) {
            Auth::logout();
            return back()->withErrors([
                'email' => 'Akun Anda telah dinonaktifkan. Silakan hubungi administrator.',
            ]);
        }
        
        // Update last login
        $user->updateLastLogin();
        
        // Cek apakah user wajib mengganti password
        if ($user->must_change_password) {
            return redirect()->route('password.force-change')
                ->with('warning', 'Anda wajib mengganti password sebelum melanjutkan. Password Anda telah direset oleh administrator.');
        }
        
        // Cek apakah ada produk yang disimpan sebelum login
        if (session()->has('buy_now_product_id')) {
            $productId = session('buy_now_product_id');
            session()->forget('buy_now_product_id');
            return redirect()->route('checkout.form', $productId);
        }

        // Redirect berdasarkan role
        switch ($user->user_type) {
            case 'admin':
                return redirect()->intended(route('admin.dashboard'));
            case 'supervisor':
                return redirect()->intended(route('supervisor.dashboard'));
            case 'teknisi':
                return redirect()->intended(route('teknisi.dashboard'));
            case 'user':
            default:
                return redirect()->intended(route('index', absolute: false));
        }
    }

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

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

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

        return redirect('/');
    }
}
