<?php

namespace Modules\MedPortal\Http\Controllers;

use Illuminate\Http\Request;
use Modules\MedPortal\Entities\MportalQuestionnaire;
use Modules\MedPortal\Entities\MportalQuestionnaireResponse;
use Modules\MedPortal\Services\QuestionnaireService;
use Modules\MedPortal\Support\ClinicBridge;

/**
 * Questionnaire results (staff side, SIFA Phase 8). List responses with scores +
 * severity; PHQ-9 flags highlighted. "Send a questionnaire" creates an empty
 * response row a patient can fill. Guarded by mportal.questionnaires.manage.
 */
class QuestionnaireController extends MedPortalBaseController
{
    public function index(QuestionnaireService $svc)
    {
        $this->guard('mportal.questionnaires.manage');

        $businessId = $this->businessId();

        $responses = MportalQuestionnaireResponse::forBusiness($businessId)
            ->with('questionnaire')
            ->orderByDesc('id')
            ->limit(200)
            ->get();

        $patientNames = ClinicBridge::patientNames(
            $businessId,
            $responses->pluck('patient_id')->unique()->map(fn ($id) => (int) $id)->all()
        );

        return view('medportal::questionnaires.index', [
            'responses'     => $responses,
            'patientNames'  => $patientNames,
            'svc'           => $svc,
            'flagThreshold' => QuestionnaireService::PHQ9_FLAG_THRESHOLD,
        ]);
    }

    /** "Send a questionnaire" picker. */
    public function create()
    {
        $this->guard('mportal.questionnaires.manage');

        $businessId = $this->businessId();

        return view('medportal::questionnaires.send', [
            'patients'       => ClinicBridge::patientOptions($businessId),
            'questionnaires' => MportalQuestionnaire::availableTo($businessId)
                ->where('is_active', true)->orderBy('title')->pluck('title', 'id')->all(),
        ]);
    }

    /** Create the empty response row (the "send"). */
    public function send(Request $request)
    {
        $this->guard('mportal.questionnaires.manage');

        $data = $this->validate($request, [
            'patient_id'       => 'required|integer',
            'questionnaire_id' => 'required|integer',
        ]);

        try {
            $businessId = $this->businessId();

            // Validate the questionnaire is visible to this business.
            $q = MportalQuestionnaire::availableTo($businessId)->find($data['questionnaire_id']);
            if (! $q) {
                return $this->fail(__('medportal::lang.questionnaire_not_found'));
            }

            MportalQuestionnaireResponse::create([
                'business_id'      => $businessId,
                'patient_id'       => (int) $data['patient_id'],
                'questionnaire_id' => (int) $q->id,
                'answers'          => null,
                'assigned_by'      => $this->userId(),
                'completed_at'     => null,
            ]);

            return $this->ok(__('medportal::lang.questionnaire_sent'));
        } catch (\Throwable $e) {
            \Log::emergency($e->getMessage());

            return $this->fail();
        }
    }

    /** View a completed response's answers (modal). */
    public function show($id)
    {
        $this->guard('mportal.questionnaires.manage');

        $businessId = $this->businessId();
        $response = MportalQuestionnaireResponse::forBusiness($businessId)
            ->with('questionnaire')
            ->findOrFail($id);

        return view('medportal::questionnaires.detail', [
            'response'    => $response,
            'patientName' => ClinicBridge::patientName($businessId, (int) $response->patient_id),
        ]);
    }
}
