<?php

namespace App\Services\Attendance;

use App\Models\AttendanceRecord;

class AttendanceRecordSyncService
{
    public function __construct(
        protected AttendanceRecord $attendanceRecord
    ) {}

    public function updateAttendanceRecord(
        int $studentId,
        string $schoolId,
        string $newStatus,
        string $semester,
        string $schoolYear,
        ?string $oldStatus,
        ?int $modifiedBy = null
    ): void {
        $record = AttendanceRecord::query()
            ->where('student_id', $studentId)
            ->where('semester', $semester)
            ->where('school_year', $schoolYear)
            ->first();

        if (!$record) {
            return;
        }

        $newStatus = strtolower($newStatus);
        $oldStatus = strtolower((string)$oldStatus);

        $presence = (int)($record->total_presence ?? 0);
        $absence = (int)($record->total_absence ?? 0);
        $late = (int)($record->total_late ?? 0);

        if ($oldStatus === 'present') {
            $presence--;
        } elseif ($oldStatus === 'absent') {
            $absence--;
        } elseif ($oldStatus === 'late') {
            $late--;
        }

        if ($newStatus === 'present') {
            $presence++;
        } elseif ($newStatus === 'absent') {
            $absence++;
        } elseif ($newStatus === 'late') {
            $late++;
        }

        $record->update([
            'total_presence' => max(0, $presence),
            'total_absence' => max(0, $absence),
            'total_late' => max(0, $late),
            'updated_at' => now(),
            'modified_by' => $modifiedBy,
        ]);
    }

    public function addNewAttendanceRecord(
        int $classSectionId,
        int $studentId,
        string $schoolId,
        string $status,
        string $semester,
        string $schoolYear,
        ?int $modifiedBy = null
    ): void {
        $status = strtolower($status);

        $record = AttendanceRecord::query()
            ->where('student_id', $studentId)
            ->where('semester', $semester)
            ->where('school_year', $schoolYear)
            ->first();

        if ($record) {
            $record->update([
                'total_presence' => (int)($record->total_presence ?? 0) + ($status === 'present' ? 1 : 0),
                'total_absence' => (int)($record->total_absence ?? 0) + ($status === 'absent' ? 1 : 0),
                'total_late' => (int)($record->total_late ?? 0) + ($status === 'late' ? 1 : 0),
                'total_attendance' => (int)($record->total_attendance ?? 0) + 1,
                'updated_at' => now(),
                'modified_by' => $modifiedBy,
            ]);
            return;
        }

        AttendanceRecord::query()->create([
            'class_section_id' => $classSectionId,
            'student_id' => $studentId,
            'school_id' => $schoolId,
            'semester' => $semester,
            'school_year' => $schoolYear,
            'created_at' => now(),
            'updated_at' => now(),
            'modified_by' => $modifiedBy,
            'total_presence' => $status === 'present' ? 1 : 0,
            'total_absence' => $status === 'absent' ? 1 : 0,
            'total_late' => $status === 'late' ? 1 : 0,
            'total_attendance' => 1,
        ]);
    }

    public function upsertAttendanceRecordTotals(
        int $studentId,
        string $classSectionId,
        string $schoolId,
        string $semester,
        string $schoolYear,
        int $totalPresence,
        int $totalLate,
        int $totalAbsence,
        int $totalAttendance,
        ?int $modifiedBy = null
    ): bool {
        if ($semester === '' || $schoolYear === '') {
            return false;
        }

        $record = AttendanceRecord::query()
            ->where('student_id', $studentId)
            ->where('semester', $semester)
            ->where('school_year', $schoolYear)
            ->first();

        $payload = [
            'total_presence' => max(0, $totalPresence),
            'total_late' => max(0, $totalLate),
            'total_absence' => max(0, $totalAbsence),
            'total_attendance' => max(0, $totalAttendance),
            'updated_at' => now(),
            'modified_by' => $modifiedBy,
        ];

        if ($record) {
            return $record->update($payload);
        }

        $payload['class_section_id'] = (int)$classSectionId;
        $payload['student_id'] = $studentId;
        $payload['school_id'] = $schoolId;
        $payload['semester'] = $semester;
        $payload['school_year'] = $schoolYear;
        $payload['created_at'] = now();

        return (bool)AttendanceRecord::query()->create($payload);
    }
}