<?php

namespace App\Http\Controllers\Auth;

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

class AuthenticatedSessionController extends Controller
{
    public function create()
    {
        return view('auth.login'); // Syndron login page
    }

    public function store(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
            'password' => 'required',
        ]);

        if (Auth::attempt($request->only('email','password'), $request->filled('remember'))) {
            $request->session()->regenerate();
            $user = Auth::user();

            if ($user->hasRole('cashier')) {
                return redirect()->route('pos.index');
            }

            return redirect()->route('dashboard'); // Admin/Manager
        }

        return back()->withErrors([
            'email' => 'The provided credentials do not match our records.',
        ]);
    }

    public function destroy(Request $request)
    {
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect()->route('login');
    }

    protected function authenticated(Request $request, $user)
{
    // Update last login info
    $user->update([
        'last_login_at' => now(),
        'last_login_ip' => $request->ip()
    ]);

    // Record login history
    \App\Models\LoginHistory::create([
        'user_id' => $user->id,
        'ip_address' => $request->ip(),
        'user_agent' => $request->header('User-Agent'),
        'login_at' => now(),
        'session_id' => session()->getId(),
        'success' => true
    ]);

    // Redirect based on role
    if ($user->hasRole('cashier')) {
        return redirect()->route('pos.index');
    }

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