<?php

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

use App\Models\EventLog;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\Routing\ResponseFactory;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Response;
use Mtc\Plugins\Clinic\Src\Logger;
use Mtc\Plugins\Clinic\Src\Models\PatientFile;
use Symfony\Component\HttpFoundation\BinaryFileResponse;

/**
 * Class EventLogController
 */
class EventLogController extends ClinicController
{

    /**
     * Load entries
     *
     * @param $id
     * @return JsonResponse
     */
    public function load($id): JsonResponse
    {
        return response()
            ->json([
                'events' => EventLog::query()
                    ->with('actor')
                    ->with('loggable')
                    ->where('member_id', $id)
                    ->orderByDesc('created_at')
                    ->get()
                    ->map(function (EventLog $event) {
                        $event->datetime = $event->created_at
                            ->format('d/m/Y H:i');
                        $event->normalise();
                        return $event;
                    }),
                'types' => Logger::$types,
                'imageExtensions' => PatientFile::IMAGE_EXTENSIONS,
            ]);
    }

    /**
     * Download file based on event details
     *
     * @param $id
     * @return Application|ResponseFactory|Response|BinaryFileResponse
     */
    public function getFile($id)
    {
        /** @var EventLog $logEvent */
        $logEvent = EventLog::query()
            ->where('subject', Logger::FILE)
            ->find($id);

        if (empty($logEvent)) {
            return response('Not Found', 404);
        }

        return PatientFile::downloadFile($logEvent->details);
    }
}
