<?php

namespace App\Models;

use CodeIgniter\Model;

class MissingScoreOverrideModel extends Model
{
    protected $table = 'missing_score_overrides';
    protected $primaryKey = 'id';
    protected $returnType = 'array';
    protected $useTimestamps = true;
    protected $allowedFields = [
        'student_id',
        'class_section_id',
        'semester',
        'school_year',
        'item_type',
        'item_index',
        'is_allowed',
        'updated_by',
        'created_at',
        'updated_at',
    ];

    public function getOverridesMap(int $classSectionId, string $semester, string $schoolYear, string $itemType): array
    {
        if ($classSectionId <= 0 || $semester === '' || $schoolYear === '' || $itemType === '') {
            return [];
        }

        $rows = $this->select('student_id, item_index')
            ->where('class_section_id', $classSectionId)
            ->where('semester', $semester)
            ->where('school_year', $schoolYear)
            ->where('item_type', $itemType)
            ->where('is_allowed', 1)
            ->findAll();

        $map = [];
        foreach ($rows as $row) {
            $sid = (int) ($row['student_id'] ?? 0);
            $idx = isset($row['item_index']) ? (int) $row['item_index'] : 0;
            if ($sid > 0) {
                $map[$sid][$idx] = true;
            }
        }
        return $map;
    }

    public function replaceOverrides(
        int $classSectionId,
        string $semester,
        string $schoolYear,
        string $itemType,
        array $studentIds,
        ?array $itemIndexes,
        array $checkedItems,
        ?int $updatedBy,
        bool $nullIndex = false
    ): void {
        if ($classSectionId <= 0 || $semester === '' || $schoolYear === '' || $itemType === '') {
            return;
        }

        $builder = $this->builder();
        $builder->where('class_section_id', $classSectionId)
            ->where('semester', $semester)
            ->where('school_year', $schoolYear)
            ->where('item_type', $itemType);

        if (!empty($studentIds)) {
            $builder->whereIn('student_id', array_map('intval', $studentIds));
        }

        if ($itemIndexes !== null) {
            if (!empty($itemIndexes)) {
                $builder->whereIn('item_index', array_map('intval', $itemIndexes));
            } else {
                return;
            }
        } elseif ($nullIndex) {
            $builder->where('item_index', null);
        }

        $builder->delete();

        if (empty($checkedItems)) {
            return;
        }

        $now = utc_now();
        $rows = [];
        foreach ($checkedItems as $item) {
            $sid = (int) ($item['student_id'] ?? 0);
            if ($sid <= 0) {
                continue;
            }
            $rows[] = [
                'student_id' => $sid,
                'class_section_id' => $classSectionId,
                'semester' => $semester,
                'school_year' => $schoolYear,
                'item_type' => $itemType,
                'item_index' => $item['item_index'] ?? null,
                'is_allowed' => 1,
                'updated_by' => $updatedBy,
                'created_at' => $now,
                'updated_at' => $now,
            ];
        }

        if (!empty($rows)) {
            $this->insertBatch($rows);
        }
    }
}
