<?php

namespace App\Http\Controllers;

use App\Domain\Attendance\Models\AttendanceRecord;
use App\Domain\Participant\Models\Participant;
use App\Domain\Training\Models\Enrollment;

class CertificateController extends Controller
{
    /**
     * An attendance certificate for one participant on one enrollment.
     *
     * Both ids arrive on the URL and used to be bound independently, so the
     * enrollment was checked against neither the participant nor the branch:
     * any enrollment id in the academy printed under any player's name. The
     * enrollment is re-resolved through the participant's own relation instead,
     * which ties the certificate to the person it names — and, because both
     * models now carry BranchScope, to the branch the request is in.
     */
    public function attendance(Participant $participant, Enrollment $enrollment)
    {
        $this->authorize('participants.view');

        $enrollment = $participant->enrollments()
            ->whereKey($enrollment->getKey())
            ->firstOrFail();

        $enrollment->load('trainingGroup.program');

        // Built on the model rather than DB::table(): a raw builder carries
        // neither the academy scope nor the branch one, so the totals printed
        // on the certificate could be summed over another tenant's sessions.
        $records = AttendanceRecord::query()
            ->where('subject_type', Participant::class)
            ->where('subject_id', $participant->id)
            ->whereHas('session', fn ($q) => $q->where('training_group_id', $enrollment->training_group_id));

        $total = (clone $records)->count();
        $attended = (clone $records)->positive()->count();

        $stats = (object) ['total' => $total, 'attended' => $attended];
        $rate = $total > 0 ? (int) round(($attended / $total) * 100) : 0;

        return view('print.certificate', compact('participant', 'enrollment', 'stats', 'rate'));
    }
}
