<?php

namespace App\Models;

use CodeIgniter\Model;

class LetterTeacherModel extends Model
{
    protected $table            = 'letter_teachers';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'array';
    protected $useSoftDeletes   = false;
    protected $allowedFields    = [
        'letter_log_id',
        'teacher_id',
        'teacher_name',
        'teacher_nip',
        'teacher_golongan',
        'teacher_jabatan',
        'sort_order',
    ];

    protected $useTimestamps = false;

    /**
     * Ambil semua guru untuk satu surat, diurutkan
     */
    public function getByLetterLog(int $letterLogId): array
    {
        return $this->where('letter_log_id', $letterLogId)
                    ->orderBy('sort_order', 'ASC')
                    ->findAll();
    }

    /**
     * Simpan bulk — hapus lama lalu insert baru
     */
    public function saveForLetter(int $letterLogId, array $teachers): void
    {
        $this->where('letter_log_id', $letterLogId)->delete();

        $rows = [];
        foreach ($teachers as $i => $t) {
            $rows[] = [
                'letter_log_id'    => $letterLogId,
                'teacher_id'       => $t['teacher_id']       ?? null,
                'teacher_name'     => $t['teacher_name']      ?? '',
                'teacher_nip'      => $t['teacher_nip']       ?? null,
                'teacher_golongan' => $t['teacher_golongan']  ?? null,
                'teacher_jabatan'  => $t['teacher_jabatan']   ?? null,
                'sort_order'       => $i + 1,
            ];
        }

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