<?php

namespace Modules\MedNotify\Http\Controllers;

use Illuminate\Http\Request;
use Modules\MedNotify\Entities\MednotifyLog;
use Yajra\DataTables\Facades\DataTables;

/**
 * Delivery log — a business-scoped DataTable of every send attempt with
 * event / channel / status filters. Read-only audit surface.
 */
class LogController extends MedNotifyBaseController
{
    public function index(Request $request)
    {
        $this->guard('mednotify.log.view');

        if ($request->ajax()) {
            $query = MednotifyLog::where('business_id', $this->businessId())
                ->select(['id', 'event_key', 'channel', 'recipient_type', 'recipient_id', 'rendered_subject', 'status', 'error', 'sent_at', 'created_at']);

            if ($request->filled('event_key')) {
                $query->where('event_key', $request->get('event_key'));
            }
            if ($request->filled('channel')) {
                $query->where('channel', $request->get('channel'));
            }
            if ($request->filled('status')) {
                $query->where('status', $request->get('status'));
            }

            return DataTables::of($query)
                ->editColumn('status', function ($r) {
                    $map = [
                        'sent'     => 'label-success',
                        'failed'   => 'label-danger',
                        'skipped'  => 'label-default',
                        'digested' => 'label-info',
                        'queued'   => 'label-warning',
                    ];
                    $cls = $map[$r->status] ?? 'label-default';

                    return '<span class="label ' . $cls . '">' . __('mednotify::lang.status_' . $r->status) . '</span>';
                })
                ->editColumn('recipient_type', fn ($r) => __('mednotify::lang.recipient_' . $r->recipient_type) . ' #' . $r->recipient_id)
                ->editColumn('created_at', fn ($r) => optional($r->created_at)->format('Y-m-d H:i'))
                ->editColumn('rendered_subject', fn ($r) => e($r->rendered_subject ?: '—'))
                ->filterColumn('recipient_type', function ($q, $keyword) {
                    $q->where('recipient_id', 'like', "%{$keyword}%");
                })
                ->rawColumns(['status'])
                ->make(true);
        }

        return view('mednotify::log.index', [
            'channels' => $this->channels(),
            'statuses' => ['queued', 'sent', 'failed', 'digested', 'skipped'],
            'events'   => MednotifyLog::where('business_id', $this->businessId())
                ->distinct()->orderBy('event_key')->pluck('event_key'),
        ]);
    }
}
