<?php

namespace App\Services\ClassPreparation;

use App\Models\ClassPrepAdjustment;
use Illuminate\Support\Facades\DB;

class ClassPreparationAdjustmentWriterService
{
    public function saveAdjustments(string $classSectionId, string $schoolYear, array $adjustments, array $allowedItems): int
    {
        $allowed = array_fill_keys($allowedItems, true);

        return DB::transaction(function () use ($classSectionId, $schoolYear, $adjustments, $allowed) {
            $count = 0;

            foreach ($adjustments as $itemName => $adjustment) {
                $item = (string) $itemName;
                if ($item === '' || !isset($allowed[$item])) {
                    continue;
                }

                $row = ClassPrepAdjustment::query()
                    ->where('class_section_id', $classSectionId)
                    ->where('school_year', $schoolYear)
                    ->where('item_name', $item)
                    ->first();

                if ($row) {
                    $row->update([
                        'adjustment' => (int) $adjustment,
                        'adjustable' => 1,
                    ]);
                    $count++;
                    continue;
                }

                ClassPrepAdjustment::query()->create([
                    'class_section_id' => $classSectionId,
                    'item_name' => $item,
                    'adjustment' => (int) $adjustment,
                    'school_year' => $schoolYear,
                    'adjustable' => 1,
                ]);
                $count++;
            }

            return $count;
        });
    }
}
