<?php

namespace Modules\MedDocuments\Http\Controllers;

use Illuminate\Http\Request;
use Modules\MedDocuments\Entities\MeddocAccessLog;
use Modules\MedDocuments\Entities\MeddocDocument;
use Yajra\DataTables\Facades\DataTables;

/**
 * Access-audit index (spec §8: "audit trail of every view/download/print").
 * Read-only, filterable by document, action, user and date range.
 */
class AccessAuditController extends MedDocBaseController
{
    public function index()
    {
        $this->guard('meddoc.audit.view');

        return view('meddocuments::audit.index', [
            'actions' => MeddocAccessLog::ACTIONS,
        ]);
    }

    public function data(Request $request)
    {
        $this->guard('meddoc.audit.view');

        $q = MeddocAccessLog::query()
            ->where('meddoc_access_logs.business_id', $this->businessId())
            ->leftJoin('meddoc_documents', 'meddoc_documents.id', '=', 'meddoc_access_logs.document_id')
            ->leftJoin('users', 'users.id', '=', 'meddoc_access_logs.user_id')
            ->select([
                'meddoc_access_logs.id',
                'meddoc_access_logs.document_id',
                'meddoc_access_logs.version_id',
                'meddoc_access_logs.action',
                'meddoc_access_logs.ip',
                'meddoc_access_logs.user_agent',
                'meddoc_access_logs.created_at',
                'meddoc_documents.title as document_title',
                \DB::raw("TRIM(CONCAT(COALESCE(users.first_name,''),' ',COALESCE(users.last_name,''))) as user_name"),
            ]);

        if ($request->filled('document_id')) {
            $q->where('meddoc_access_logs.document_id', $request->get('document_id'));
        }
        if ($request->filled('action')) {
            $q->where('meddoc_access_logs.action', $request->get('action'));
        }
        if ($request->filled('date_from')) {
            $q->whereDate('meddoc_access_logs.created_at', '>=', $request->get('date_from'));
        }
        if ($request->filled('date_to')) {
            $q->whereDate('meddoc_access_logs.created_at', '<=', $request->get('date_to'));
        }

        return DataTables::of($q)
            ->editColumn('created_at', fn ($r) => optional($r->created_at)->format('Y-m-d H:i:s'))
            ->editColumn('document_title', fn ($r) => e($r->document_title ?? ('#' . $r->document_id)))
            ->addColumn('actor', fn ($r) => $r->user_name ? e($r->user_name) : '<em class="text-muted">' . __('meddocuments::lang.public_share') . '</em>')
            ->editColumn('action', fn ($r) => '<span class="label label-info">' . e($r->action) . '</span>')
            ->editColumn('user_agent', fn ($r) => '<small>' . e(\Str::limit($r->user_agent, 60)) . '</small>')
            ->rawColumns(['actor', 'action', 'user_agent'])
            ->orderColumn('created_at', 'meddoc_access_logs.created_at $1')
            ->make(true);
    }
}
