<?php

namespace App\Http\Controllers;

use App\Models\AttendanceUser;
use App\Models\AttendanceUserRequest;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class AttendanceUserConfirmController extends Controller
{
    public function store(Request $request): JsonResponse
    {
        $token = $request->header('X-Attendance-Token', $request->input('token'));
        $expected = app_setting('attendance_token');

        if (! $expected || $token !== $expected) {
            return response()->json(['message' => 'Unauthorized.'], 401);
        }

        $data = $request->validate([
            'request_id' => ['required', 'integer'],
            'pin' => ['required', 'string', 'max:50'],
            'name' => ['required', 'string', 'max:255'],
            'status' => ['required', 'string', 'in:success,failed'],
            'message' => ['nullable', 'string', 'max:255'],
        ]);

        $requestModel = AttendanceUserRequest::find($data['request_id']);
        if (! $requestModel) {
            return response()->json(['message' => 'Request not found.'], 404);
        }

        if ($data['status'] === 'success') {
            AttendanceUser::updateOrCreate(
                ['pin' => $data['pin']],
                ['name' => $data['name']]
            );
        }

        $requestModel->update([
            'status' => $data['status'],
            'message' => $data['message'] ?? null,
        ]);

        return response()->json(['message' => 'OK']);
    }
}
