<?php

namespace App\Models;

use CodeIgniter\Model;

class AscSubjectModel extends Model
{
    protected $table            = 'asc_subjects';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'array';
    protected $useSoftDeletes   = false;
    protected $allowedFields    = [
        'import_id', 'asc_id', 'name', 'short_code', 'school_subject_id'
    ];

    protected $useTimestamps = true;
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';

    // Ambil semua mapel milik satu import, urut abjad
    public function getByImport($importId)
    {
        return $this->where('import_id', $importId)
                    ->orderBy('name', 'ASC')
                    ->findAll();
    }

    // Ambil sebagai lookup array: asc_id => [name, short_code]
    // Berguna saat parse XML (resolve nama dari ID)
    public function getLookup($importId)
    {
        $rows   = $this->getByImport($importId);
        $lookup = [];

        foreach ($rows as $row) {
            $lookup[$row['asc_id']] = [
                'name'       => $row['name'],
                'short_code' => $row['short_code'],
            ];
        }

        return $lookup;
    }

    // Hapus semua mapel milik satu import (untuk re-import)
    public function deleteByImport($importId)
    {
        return $this->where('import_id', $importId)->delete();
    }
}