<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests\LoginRequest;
use Illuminate\Support\Facades\Auth;
use DB;

class LoginController extends Controller
{
    /**
     * Display login page.
     * 
     * @return Renderable
     */
    public function show()
    {
        return view('auth.login');
    } 

    public function login(LoginRequest $request)
    {
        
        $input = $request->only('username', 'password', 'email');

        $username = $input['username'] ?? $input['email'];

        // Cari user case-insensitive
        $user = \App\Models\User::whereRaw('LOWER(username) = ?', [strtolower($username)])
            ->orWhereRaw('LOWER(email) = ?', [strtolower($username)])
            ->first();

        if (!$user) {
            return redirect()->to('login')
                ->withErrors('Username atau email tidak ditemukan')->with('password', $input['password']);
        }

        // Validasi status user - harus Active
        if ($user->status !== 'Active') {
            return redirect()->to('login')
                ->withErrors('Akun Anda tidak aktif. Silakan hubungi administrator.')
                ->with('username', $username);
        }

        // Validasi single session - cek apakah user sudah login di device lain
        if ($user->hasActiveSession()) {
            $currentSessionId = session()->getId();
            
            // Jika session ID berbeda, berarti user sudah login di device lain
            if (!$user->isCurrentSession($currentSessionId)) {
                $lastLoginInfo = '';
                if ($user->last_login_at) {
                    $lastLoginInfo = ' Terakhir login: ' . $user->last_login_at->format('d M Y H:i') . 
                                   ' dari IP: ' . $user->last_login_ip;
                }
                
                return redirect()->to('login')
                    ->withErrors('Akun Anda sedang digunakan di device lain.' . $lastLoginInfo . ' Silakan logout terlebih dahulu atau hubungi administrator.')
                    ->with('username', $username);
            }
        }

        // Pastikan field yang benar dikirim ke Auth
        $credentials = [
            filter_var($username, FILTER_VALIDATE_EMAIL) ? 'email' : 'username' => filter_var($username, FILTER_VALIDATE_EMAIL) ? $user->email : $user->username,
            'password' => $input['password']
        ];

        if (!Auth::validate($credentials)) {
            return redirect()->to('login')
                ->withErrors('Password salah')->with('username', $username);
        }

        // Login user
        Auth::loginUsingId($user->id);
        
        // Update session info
        $user->updateSessionInfo(
            session()->getId(),
            $request->ip(),
            $request->userAgent()
        );
        
        return $this->authenticated($request, $user);
    }


    /**
     * Handle response after user authenticated
     * 
     * @param Request $request
     * @param Auth $user
     * 
     * @return \Illuminate\Http\Response
     */
    protected function authenticated(Request $request, $user)
    {
        return redirect()->intended();
    }
}
