<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\LoginHistory;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\View\View;

class LoginHistoryController extends Controller
{
    public function index(Request $request): View
    {
        $query = LoginHistory::query()->with('user')->orderByDesc('created_at');

        if ($request->filled('success')) {
            $query->where('success', $request->boolean('success'));
        }

        if ($request->filled('user_id')) {
            $query->where('user_id', (int) $request->input('user_id'));
        }

        if ($request->filled('identifier')) {
            $term = '%'.addcslashes($request->input('identifier'), '%_\\').'%';
            $query->where('identifier', 'like', $term);
        }

        if ($request->filled('from')) {
            $query->whereDate('created_at', '>=', $request->date('from')->format('Y-m-d'));
        }

        if ($request->filled('to')) {
            $query->whereDate('created_at', '<=', $request->date('to')->format('Y-m-d'));
        }

        $histories = $query->paginate(50)->withQueryString();
        $users = User::query()->orderBy('name')->get(['id', 'name', 'email']);

        return view('admin.login-history.index', compact('histories', 'users'));
    }
}
