<?php

namespace App\Services;

use App\Enums\AttendanceStatusEnum;
use App\Enums\SessionStatusEnum;
use App\Models\CoachSession;
use App\Models\SessionAttendance;

class SessionAttendanceService extends BaseService
{
    /**
     * List attendance records for a session with member details.
     */
    public function getAttendance(CoachSession $session): \Illuminate\Database\Eloquent\Collection
    {
        return $session->attendances()->with('member')->get();
    }

    /**
     * Bulk mark/update attendance for a session.
     * Expects an array of: [['member_id' => int, 'status' => int], ...]
     */
    public function bulkMarkAttendance(CoachSession $session, array $attendances): void
    {
        $this->transaction(function () use ($session, $attendances) {
            foreach ($attendances as $entry) {
                SessionAttendance::updateOrCreate(
                    [
                        'coach_session_id' => $session->id,
                        'member_id'        => $entry['member_id'],
                    ],
                    [
                        'status' => $entry['status'],
                    ]
                );
            }

            // Update registered count
            $session->update([
                'registered_count' => $session->attendances()->count(),
            ]);

            // Auto-update session status to IN_PROGRESS if it was UPCOMING
            if ($session->status === SessionStatusEnum::UPCOMING->value) {
                $session->update(['status' => SessionStatusEnum::IN_PROGRESS->value]);
            }
        });
    }

    /**
     * Get attendance summary counts for a session.
     */
    public function getAttendanceSummary(CoachSession $session): array
    {
        return [
            'present' => $session->attendances()->where('status', AttendanceStatusEnum::PRESENT->value)->count(),
            'absent'  => $session->attendances()->where('status', AttendanceStatusEnum::ABSENT->value)->count(),
            'pending' => $session->attendances()->where('status', AttendanceStatusEnum::PENDING->value)->count(),
        ];
    }
}
