<?php

declare(strict_types=1);

namespace App\Modules\Operation;

/**
 * DashboardService — Computes real-time statistics, attendance percentages,
 * and ratios for display on the wedding operations dashboard cards.
 *
 * No SQL database queries, no HTML generation.
 *
 * @package Inveetaire
 * @ref     PILOT-007
 */
class DashboardService
{
    /**
     * Compute rates and ratios from raw check-in aggregates.
     *
     * @param array $rawStats Raw stats array from OperationModel.
     * @return array Enriched statistics bundle.
     */
    public function compileDashboardStats(array $rawStats): array
    {
        $totalGuests = $rawStats['total_guests'];
        $rsvpYes = $rawStats['rsvp_yes_count'];
        $rsvpYesPax = $rawStats['rsvp_yes_pax'];
        $checkedInCount = $rawStats['checked_in_count'];
        $checkedInPax = $rawStats['checked_in_pax'];
        $totalInvitedPax = $rawStats['total_invited_pax'];

        // 1. Attendance percentage based on RSVP Yes (Confirmed) Count
        $attendancePercentage = 0.0;
        if ($rsvpYes > 0) {
            $attendancePercentage = round(($checkedInCount / $rsvpYes) * 100, 1);
        }

        // 2. Capacity filling rate (checked-in seats / total invited capacity)
        $capacityRate = 0.0;
        if ($totalInvitedPax > 0) {
            $capacityRate = round(($checkedInPax / $totalInvitedPax) * 100, 1);
        }

        // 3. RSVP Yes to Checked-In pax seat fill rate
        $seatFillRate = 0.0;
        if ($rsvpYesPax > 0) {
            $seatFillRate = round(($checkedInPax / $rsvpYesPax) * 100, 1);
        }

        // 4. Guest Attendance (Capped at 100%)
        $guestAttendancePercentage = 0.0;
        if ($totalGuests > 0) {
            $guestAttendancePercentage = min(100.0, round(($checkedInCount / $totalGuests) * 100, 1));
        }

        // 5. Pax Attendance (Capped at 100%)
        $paxAttendancePercentage = 0.0;
        if ($totalInvitedPax > 0) {
            $paxAttendancePercentage = min(100.0, round(($checkedInPax / $totalInvitedPax) * 100, 1));
        }

        return array_merge($rawStats, [
            'total_guest_count'           => $totalGuests,
            'checked_in_guest_count'      => $checkedInCount,
            'guest_attendance_percentage' => $guestAttendancePercentage,
            'total_invited_pax'           => $totalInvitedPax,
            'checked_in_pax'              => $checkedInPax,
            'pax_attendance_percentage'   => $paxAttendancePercentage,
            // Keep legacy compatibility
            'attendance_percentage'       => $attendancePercentage,
            'capacity_rate'               => $capacityRate,
            'seat_fill_rate'              => $seatFillRate
        ]);
    }
}
