<?php

namespace App\Http\Controllers\Staff;

use App\Domain\ACL\Permission;
use App\Http\Controllers\HashidControllerBase;
use App\Models\Study;
use App\Services\AuditTrail\Activity;

class StudiesController extends HashidControllerBase
{
    public function details()
    {
        $this->decodeKeys();
        $study = Study::with(['details'])->findOrFail($this->key);
        audit()
            ->did(Activity::Study_Metadata_View)
            ->on($study)
            ->log();

        // return view('staff.studies.details', compact('study'));
        return response()->json($study);
    }

    public function show()
    {
        $this->decodeKeys();
        $study = Study::with(['details'])->findOrFail($this->key);
        $fmtD = 'M d, Y';
        // $fmtDT = 'M d, Y h:i A D';
        $fmtDT = 'F j, Y h:i A (l)';
        if (! is_null($study->patient_birthdate)) {
            $age = sprintf('%sY <span class="text-muted ms-2">%s</span>', $study->patient_birthdate->age, $study->patient_birthdate->format($fmtD));
        } else {
            $age = '';
        }
        $data = [
            'Patient Name' => $study->patient_name,
            'Patient Id' => $study->patient_id,
            'Sex' => sprintf('<i class="me-2 fa-light %s"></i> %s', $study->gender_icon, $study->gender_name),
            'Age' => $age,
            'Accession #' => $study->accession_number,
            'Modality' => $study->modality,
            'Study Date' => $study->study_date->format($fmtDT),
            'Receive Date' => $study->received_at->format($fmtDT),
            'Description' => $study->study_description,
            'Body Part' => $study->body_part_examined,
            'Priority' => $study->priority->name,
            'Institution' => $study->institution_name,
            'Images #' => $study->image_count,
            'Series #' => $study->series_count,
            'D/L Size' => human_filesize($study->disk_size, 1),
        ];
        $properties = collect($study->details->properties);
        $data['Manufacturer'] = $properties->get('manufacturer');
        $data['Model'] = $properties->get('manufacturer_model_name');
        $data['S/W Version'] = $properties->get('software_versions');
        $data['Station'] = $properties->get('station_name');
        $data['Operator'] = $properties->get('operators_name');

        return view('staff.studies.show-details', compact('data', 'study'));
    }

    public function attachments()
    {
        $this->decodeKeys();
        $study = Study::findOrFail($this->key);
        $allow_delete = auth()->user()->may(Permission::AttachmentUpload);

        return view('staff.history.partials._uploaded-studies-list', compact('study', 'allow_delete'));
    }
}