<?php

namespace App\Http\Controllers;

use App\Domain\Participant\Models\Participant;
use App\Domain\Training\Models\Enrollment;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CertificateController extends Controller
{
    public function attendance(Participant $participant, Enrollment $enrollment)
    {
        $this->authorize('participants.view');

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

        $stats = DB::table('attendance_records')
            ->where('subject_type', 'participant')
            ->where('subject_id', $participant->id)
            ->join('training_sessions', 'training_sessions.id', '=', 'attendance_records.training_session_id')
            ->where('training_sessions.training_group_id', $enrollment->training_group_id)
            ->selectRaw("
                COUNT(*) as total,
                SUM(CASE WHEN attendance_records.status IN ('present','late','partial') THEN 1 ELSE 0 END) as attended
            ")
            ->first();

        $rate = $stats && $stats->total > 0 ? round(($stats->attended / $stats->total) * 100) : 0;

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