<?php

namespace App\Services\Attendance;

use Illuminate\Support\Facades\DB;

class AttendanceSummaryRebuildService
{
    public function rebuild(): array
    {
        DB::table('attendance_record')->truncate();

        $rows = DB::table('attendance_data')
            ->orderBy('student_id')
            ->orderBy('school_year')
            ->orderBy('semester')
            ->get()
            ->map(fn ($row) => (array) $row)
            ->all();

        if (empty($rows)) {
            return ['inserted' => 0];
        }

        $summary = [];
        foreach ($rows as $row) {
            $studentId = (int) ($row['student_id'] ?? 0);
            $schoolYear = (string) ($row['school_year'] ?? '');
            $semester = (string) ($row['semester'] ?? '');
            $status = strtolower((string) ($row['status'] ?? ''));

            $key = $studentId . '-' . $schoolYear . '-' . $semester;
            if (!isset($summary[$key])) {
                $summary[$key] = [
                    'student_id' => $studentId,
                    'school_year' => $schoolYear,
                    'semester' => $semester,
                    'class_section_id' => $row['class_section_id'] ?? null,
                    'school_id' => $row['school_id'] ?? null,
                    'total_presence' => 0,
                    'total_absence' => 0,
                    'total_late' => 0,
                    'total_attendance' => 0,
                    'created_at' => utc_now(),
                    'updated_at' => utc_now(),
                ];
            }

            $summary[$key]['total_attendance']++;
            if ($status === 'present') {
                $summary[$key]['total_presence']++;
            } elseif ($status === 'absent') {
                $summary[$key]['total_absence']++;
            } elseif ($status === 'late') {
                $summary[$key]['total_late']++;
            }
        }

        DB::table('attendance_record')->insert(array_values($summary));

        return ['inserted' => count($summary)];
    }
}
