<?php

namespace Mtc\Plugins\CmsAuditLog\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Mtc\Plugins\CmsAuditLog\Src\Models\AuditEntry;

class CmsAuditLogController extends Controller
{
    const PER_PAGE = 50;

    public function index(Request $request)
    {
        $query = AuditEntry::query()
            ->orderByDesc('id');

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

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

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

        if ($request->filled('date_from')) {
            $query->where('created_at', '>=', $request->input('date_from') . ' 00:00:00');
        }

        if ($request->filled('date_to')) {
            $query->where('created_at', '<=', $request->input('date_to') . ' 23:59:59');
        }

        $entries = $query->paginate(self::PER_PAGE)
            ->appends($request->query());

        // admin_user_name is encrypted at rest, so group in SQL by id only
        // and read each user's latest name through the decrypting cast
        $latest_entry_ids = AuditEntry::query()
            ->whereNotNull('admin_user_id')
            ->groupBy('admin_user_id')
            ->selectRaw('MAX(id) as id')
            ->pluck('id');

        $admin_users = AuditEntry::query()
            ->whereIn('id', $latest_entry_ids)
            ->get(['id', 'admin_user_id', 'admin_user_name'])
            ->sortBy('admin_user_name')
            ->values();

        return template('admin/cms_audit_log/index.twig', [
            'title' => 'CMS Change Log',
            'entries' => $entries,
            'actions' => AuditEntry::$actions,
            'admin_users' => $admin_users,
            'filters' => [
                'page_id' => $request->input('page_id'),
                'admin_user_id' => $request->input('admin_user_id'),
                'action' => $request->input('action'),
                'date_from' => $request->input('date_from'),
                'date_to' => $request->input('date_to'),
            ],
        ]);
    }
}
