<?php

namespace App\Http\Controllers;

use App\Http\Requests\StorePatientMediaRequest;
use App\Models\Client;
use App\Models\Patient;
use App\Models\PatientMedia;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Storage;

class PatientMediaController extends Controller
{
    protected function assertPatient(Client $client, Patient $patient): void
    {
        abort_unless($patient->client_id === $client->id, 404);
    }

    public function store(StorePatientMediaRequest $request, Client $client, Patient $patient): RedirectResponse
    {
        $this->assertPatient($client, $patient);
        $this->authorize('create', PatientMedia::class);

        $title = $request->input('title');
        foreach ($request->file('files', []) as $file) {
            $path = $file->store("patient-media/{$patient->id}", 'public');
            $patient->mediaFiles()->create([
                'uploaded_by' => $request->user()->id,
                'path' => $path,
                'original_name' => $file->getClientOriginalName(),
                'mime' => $file->getClientMimeType(),
                'size' => $file->getSize(),
                'title' => $title,
            ]);
        }

        return redirect()->route('clients.patients.show', [$client, $patient])
            ->with('success', __('Archivos subidos correctamente.'));
    }

    public function destroy(Client $client, Patient $patient, PatientMedia $patientMedia): RedirectResponse
    {
        $this->assertPatient($client, $patient);
        abort_unless($patientMedia->patient_id === $patient->id, 404);
        $this->authorize('delete', $patientMedia);

        Storage::disk('public')->delete($patientMedia->path);
        $patientMedia->delete();

        return redirect()->route('clients.patients.show', [$client, $patient])
            ->with('success', __('Archivo eliminado.'));
    }
}
