<?php

namespace App\Http\Controllers;

use App\Models\AttendanceUser;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class AttendanceUserSyncController 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);
        }

        $users = $request->input('users', []);
        if (! is_array($users)) {
            return response()->json(['message' => 'Invalid payload.'], 422);
        }

        $rows = [];
        $now = now();
        foreach ($users as $user) {
            $pin = (string) ($user['pin'] ?? $user['PIN'] ?? '');
            if ($pin === '') {
                continue;
            }

            $rows[] = [
                'pin' => $pin,
                'name' => $user['name'] ?? $user['Name'] ?? null,
                'card' => $user['card'] ?? $user['Card'] ?? null,
                'privilege' => $user['privilege'] ?? $user['Privilege'] ?? null,
                'group' => $user['group'] ?? $user['Group'] ?? null,
                'raw' => json_encode($user),
                'created_at' => $now,
                'updated_at' => $now,
            ];
        }

        if ($rows === []) {
            return response()->json(['message' => 'No valid users.', 'count' => 0]);
        }

        DB::table('attendance_users')->upsert(
            $rows,
            ['pin'],
            ['name', 'card', 'privilege', 'group', 'raw', 'updated_at']
        );

        return response()->json(['message' => 'OK', 'count' => count($rows)]);
    }
}
