input('token'); if (empty($expectedToken) || $providedToken !== $expectedToken) { return response()->json([ 'success' => false, 'message' => 'Token tidak valid.', ], 401); } return response()->json([ 'success' => true, 'message' => 'Koneksi OK.', 'data' => [ 'app' => config('app.name', 'Aplikasi Ketertiban'), 'students' => Student::where('is_active', true)->count(), 'token_valid' => true, ], ]); } public function sync(Request $request) { $expectedToken = Setting::getValue('ejurnal_sync_token', ''); $providedToken = $request->input('token'); if (empty($expectedToken) || $providedToken !== $expectedToken) { Log::warning('Attendance sync: invalid token', [ 'ip' => $request->ip(), 'provided' => substr((string)$providedToken, 0, 10), ]); return response()->json([ 'success' => false, 'message' => 'Invalid or missing sync token.', ], 401); } $request->validate([ 'attendances' => 'required|array|min:1|max:500', 'attendances.*.source_student_id' => 'required|integer', 'attendances.*.date' => 'required|date', 'attendances.*.lesson_hour' => 'required|integer|min:1|max:10', 'attendances.*.status' => 'required|in:hadir,sakit,izin,alpha', 'attendances.*.notes' => 'nullable|string|max:255', ]); $attendances = $request->input('attendances'); $results = [ 'created' => 0, 'updated' => 0, 'skipped' => 0, 'errors' => [], 'violations' => 0, ]; $sourceIds = array_unique(array_column($attendances, 'source_student_id')); $students = Student::whereIn('source_id', $sourceIds) ->where('is_active', true) ->get(['id', 'source_id', 'class_name']); $studentMap = $students->pluck('id', 'source_id'); $classNameMap = $students->pluck('class_name', 'id'); $alphaCounts = []; $alphaDate = null; $allStudentIdsInPush = []; // track all students for cleanup foreach ($attendances as $item) { $sourceId = $item['source_student_id']; if (!isset($studentMap[$sourceId])) { $results['skipped']++; $results['errors'][] = "Student source_id={$sourceId} not found"; continue; } $localStudentId = $studentMap[$sourceId]; $allStudentIdsInPush[$localStudentId] = true; $statusMap = [ 'present' => 'hadir', 'sick' => 'sakit', 'permission' => 'izin', 'absent' => 'alpha', ]; $localStatus = $statusMap[$item['status']] ?? $item['status']; try { $attendance = Attendance::updateOrCreate( [ 'student_id' => $localStudentId, 'date' => $item['date'], 'lesson_hour' => $item['lesson_hour'], ], [ 'status' => $localStatus, 'class_name' => $classNameMap[$localStudentId] ?? null, 'notes' => $item['notes'] ?? null, 'recorded_by' => null, ] ); if ($attendance->wasRecentlyCreated) { $results['created']++; } else { $results['updated']++; } if ($localStatus === 'alpha') { $alphaCounts[$localStudentId] = ($alphaCounts[$localStudentId] ?? 0) + 1; $alphaDate = $item['date']; } } catch (\Exception $e) { $results['errors'][] = "student_id={$sourceId} jam={$item['lesson_hour']}: " . $e->getMessage(); $results['skipped']++; } } // Auto-generate / update / hapus violations untuk alpha siswa di push ini $alphaType = ViolationType::where('slug', 'alpha')->first(); if ($alphaType) { $violationService = app(\App\Services\ViolationService::class); foreach ($allStudentIdsInPush as $studentId => $_) { try { // Hitung total alpha di DB (akumulasi dari semua push, bukan cuma push ini) $totalAlpha = \App\Models\Attendance::where('student_id', $studentId) ->where('date', $alphaDate) ->where('status', 'alpha') ->count(); // Cari existing system-generated violation $existing = \App\Models\Violation::where('student_id', $studentId) ->where('violation_type_id', $alphaType->id) ->where('violation_date', $alphaDate) ->whereNull('recorded_by') ->first(); if ($totalAlpha > 0) { // Ada alpha → buat/update violation $points = max(1, (int) round(($alphaType->points / 10) * $totalAlpha)); $desc = "Alpha - Tidak hadir tanpa keterangan ({$totalAlpha} jam pelajaran)"; if ($existing) { $existing->update([ 'points' => $points, 'description' => $desc, 'notes' => 'Diperbarui otomatis dari sinkron E-Jurnal.', ]); } else { $violationService->recordViolation([ 'student_id' => $studentId, 'violation_type_id' => $alphaType->id, 'violation_date' => $alphaDate, 'points' => $points, 'description' => $desc, 'notes' => 'Dibuat otomatis dari sinkron E-Jurnal.', 'evidences' => [], ], null); } $results['violations']++; } elseif ($existing) { // Tidak ada alpha tapi ada violation lama → hapus (ganti status ke hadir) $existing->delete(); $results['violations']++; } } catch (\Exception $e) { $results['errors'][] = "Violation sync failed for student={$studentId}: " . $e->getMessage(); } } } else { $results['errors'][] = 'Violation type "Alpha" not found. Create a violation type with slug "alpha".'; } return response()->json([ 'success' => true, 'message' => "Sync completed: {$results['created']} created, {$results['updated']} updated, {$results['skipped']} skipped, {$results['violations']} violations.", 'results' => $results, ]); } }