<?php

namespace App\Http\Controllers\Api\V1\Coach;

use App\Http\Controllers\Controller;
use App\Http\Resources\Api\SessionAttendanceResource;
use App\Models\Coach;
use App\Models\CoachSession;
use App\Services\SessionAttendanceService;
use App\Traits\ApiResponseTrait;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class AttendanceController extends Controller
{
    use ApiResponseTrait;

    public function __construct(
        protected SessionAttendanceService $attendanceService
    ) {}

    
    public function index(Request $request, int $id): JsonResponse
    {
        $coach = $request->user();

        if (! $coach instanceof Coach) {
            return $this->errorResponse(__('Unauthorized.'), 403);
        }

        $session = CoachSession::forCoach($coach->id)->find($id);

        if (! $session) {
            return $this->notFoundResponse();
        }

        $attendances = $this->attendanceService->getAttendance($session);
        $summary     = $this->attendanceService->getAttendanceSummary($session);

        return $this->ApiResponse([
            'session'     => [
                'id'           => $session->id,
                'session_date' => $session->session_date?->format('Y-m-d'),
                'start_time'   => $session->start_time ? substr($session->start_time, 0, 5) : null,
                'end_time'     => $session->end_time ? substr($session->end_time, 0, 5) : null,
                'status'       => $session->status,
                'status_label' => $session->statusLabel(),
                'registered_count' => $session->registered_count,
            ],
            'summary'     => $summary,
            'attendances' => SessionAttendanceResource::collection($attendances),
        ], __('Success'), 200);
    }


    public function store(Request $request, int $id): JsonResponse
    {
        $coach = $request->user();

        if (! $coach instanceof Coach) {
            return $this->errorResponse(__('Unauthorized.'), 403);
        }

        $session = CoachSession::forCoach($coach->id)->find($id);

        if (! $session) {
            return $this->notFoundResponse();
        }

        $validated = $request->validate([
            'attendances'            => ['required', 'array', 'min:1'],
            'attendances.*.member_id' => ['required', 'integer', 'exists:members,id'],
            'attendances.*.status'    => ['required', 'integer', 'in:1,2,3'],
        ]);

        $this->attendanceService->bulkMarkAttendance($session, $validated['attendances']);

        $session->refresh();
        $attendances = $this->attendanceService->getAttendance($session);
        $summary     = $this->attendanceService->getAttendanceSummary($session);

        return $this->ApiResponse([
            'summary'     => $summary,
            'attendances' => SessionAttendanceResource::collection($attendances),
        ], __('Attendance updated successfully'), 200);
    }
}
