<?php

namespace App\Services\ClassPreparation;

use App\Models\ClassPreparationLog;

class ClassPreparationLogService
{
    public function getLatestLog(string $classSectionId, string $schoolYear): ?ClassPreparationLog
    {
        return ClassPreparationLog::query()
            ->where('class_section_id', $classSectionId)
            ->where('school_year', $schoolYear)
            ->orderBy('created_at', 'DESC')
            ->first();
    }

    public function hasPrepChanged(array $new, array $old): bool
    {
        ksort($new);
        ksort($old);

        return json_encode($new) !== json_encode($old);
    }

    public function createLog(string $classSectionId, string $className, string $schoolYear, array $items, string $createdAt): bool
    {
        try {
            ClassPreparationLog::query()->create([
                'class_section_id' => $classSectionId,
                'class_section' => $className,
                'school_year' => $schoolYear,
                'prep_data' => json_encode($items),
                'created_at' => $createdAt,
            ]);
            return true;
        } catch (\Throwable $e) {
            return false;
        }
    }
}
