<?php

namespace Modules\MedPortal\Http\Controllers;

use Illuminate\Http\Request;
use Modules\MedPortal\Entities\MportalRecordRelease;
use Modules\MedPortal\Services\RecordAccessService;
use Modules\MedPortal\Support\ClinicBridge;

/**
 * Record-release manager (SIFA Phase 8). Staff pick a patient and toggle release
 * per record type. RecordAccessService is the gate; this controller only drives
 * it. Guarded by mportal.records.release.
 */
class RecordReleaseController extends MedPortalBaseController
{
    public function index(Request $request, RecordAccessService $access)
    {
        $this->guard('mportal.records.release');

        $businessId = $this->businessId();
        $patients   = ClinicBridge::patientOptions($businessId);

        $selectedId = (int) $request->query('patient_id', array_key_first($patients) ?: 0);

        $visibility = $selectedId
            ? $access->visibleRecords($businessId, $selectedId)
            : [];

        // Existing override rows (for released_by/at display).
        $overrides = $selectedId
            ? MportalRecordRelease::forBusiness($businessId)->forPatient($selectedId)->get()->keyBy('record_type')
            : collect();

        return view('medportal::releases.index', [
            'hasClinic'    => ClinicBridge::hasClinic(),
            'patients'     => $patients,
            'selectedId'   => $selectedId,
            'selectedName' => $selectedId ? ClinicBridge::patientName($businessId, $selectedId) : null,
            'types'        => RecordAccessService::TYPES,
            'visibility'   => $visibility,
            'overrides'    => $overrides,
            'defaults'     => (array) config('medportal.release_defaults', []),
        ]);
    }

    public function toggle(Request $request, RecordAccessService $access)
    {
        $this->guard('mportal.records.release');

        $data = $this->validate($request, [
            'patient_id'  => 'required|integer',
            'record_type' => 'required|in:' . implode(',', MportalRecordRelease::RECORD_TYPES),
            'released'    => 'required|boolean',
        ]);

        try {
            $businessId = $this->businessId();
            $patientId  = (int) $data['patient_id'];
            $type       = $data['record_type'];

            if ($request->boolean('released')) {
                $access->release($businessId, $patientId, $type, $this->userId());
            } else {
                $access->unrelease($businessId, $patientId, $type, $this->userId());
            }

            return $this->ok(__('medportal::lang.release_saved'), [
                'visibility' => $access->visibleRecords($businessId, $patientId),
            ]);
        } catch (\Throwable $e) {
            \Log::emergency($e->getMessage());

            return $this->fail();
        }
    }
}
