<?php

namespace Modules\MedPortal\Http\Controllers;

use Modules\MedPortal\Entities\MportalDependent;
use Modules\MedPortal\Entities\MportalQuestionnaireResponse;
use Modules\MedPortal\Services\MessagingService;
use Modules\MedPortal\Services\QuestionnaireService;
use Modules\MedPortal\Services\RecordAccessService;
use Modules\MedPortal\Support\ClinicBridge;

/**
 * Staff-side portal dashboard (SIFA Phase 8). Counts of portal patients,
 * records pending release, unread message threads, and recent questionnaire
 * flags (PHQ-9 >= 15 highlighted). Guarded by mportal.manage.
 */
class DashboardController extends MedPortalBaseController
{
    public function index(RecordAccessService $access, MessagingService $messaging, QuestionnaireService $questionnaires)
    {
        $this->guard('mportal.manage');

        $businessId = $this->businessId();

        // Recent completed questionnaire responses (flag PHQ-9 >= 15).
        $recentResponses = MportalQuestionnaireResponse::forBusiness($businessId)
            ->completed()
            ->with('questionnaire')
            ->orderByDesc('completed_at')
            ->limit(10)
            ->get();

        $flaggedCount = $recentResponses->filter(fn ($r) => $questionnaires->isFlagged($r))->count();

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

        return view('medportal::dashboard', [
            'hasClinic'         => ClinicBridge::hasClinic(),
            'portalPatients'    => ClinicBridge::patientCount($businessId),
            'dependents'        => MportalDependent::forBusiness($businessId)->count(),
            'pendingReleases'   => $access->pendingReleaseCount($businessId),
            'unreadThreads'     => $messaging->unreadThreadCount($businessId),
            'recentResponses'   => $recentResponses,
            'flaggedCount'      => $flaggedCount,
            'flagThreshold'     => QuestionnaireService::PHQ9_FLAG_THRESHOLD,
            'patientNames'      => $patientNames,
            'questionnaireSvc'  => $questionnaires,
        ]);
    }
}
