<?php

namespace App\Http\Controllers\Api\Attendance;

use App\Http\Controllers\Controller;
use App\Http\Requests\Attendance\SaveAdminAttendanceRequest;
use App\Http\Requests\Attendance\SaveStaffAttendanceCellRequest;
use App\Http\Resources\Attendance\AdminAttendanceResource;
use App\Http\Resources\Attendance\StaffMonthResource;
use App\Services\Attendance\StaffAttendanceService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Throwable;

class StaffAttendanceApiController extends Controller
{
    public function __construct(
        protected StaffAttendanceService $staffAttendanceService
    ) {}

    public function monthData(Request $request): StaffMonthResource
    {
        return new StaffMonthResource(
            $this->staffAttendanceService->monthData(
                (string)$request->query('semester'),
                (string)$request->query('school_year')
            )
        );
    }

    public function admins(Request $request): AdminAttendanceResource
    {
        return new AdminAttendanceResource(
            $this->staffAttendanceService->adminsAttendanceData(
                (string)$request->query('date'),
                (string)$request->query('semester'),
                (string)$request->query('school_year')
            )
        );
    }

    public function saveAdmins(SaveAdminAttendanceRequest $request): JsonResponse
    {
        try {
            return response()->json(
                $this->staffAttendanceService->saveAdmins(auth()->user(), $request->validated())
            );
        } catch (Throwable $e) {
            return response()->json(['message' => $e->getMessage()], 422);
        }
    }

    public function saveCell(SaveStaffAttendanceCellRequest $request): JsonResponse
    {
        try {
            return response()->json(
                $this->staffAttendanceService->saveCell(auth()->user(), $request->validated())
            );
        } catch (Throwable $e) {
            return response()->json(['message' => $e->getMessage()], 422);
        }
    }

    public function monthCsv(Request $request): StreamedResponse
    {
        return $this->staffAttendanceService->monthCsv(
            (string)$request->query('semester'),
            (string)$request->query('school_year'),
            (string)$request->query('scope')
        );
    }
}