<?php

namespace App\Models;

use CodeIgniter\Model;

class AssessmentClassSettingModel extends Model
{
    protected $table            = 'assessment_class_settings';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'array';
    protected $useSoftDeletes   = false;
    protected $allowedFields    = [
        'assessment_id', 'classroom_id', 'subject_id', 'teacher_id',
        'kktp',
        'bobot_pg', 'bobot_bs', 'bobot_isian', 'bobot_essay',
        'kunci_pg', 'kunci_bs',
        'bobot_filled',
    ];

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

    /**
     * Ambil setting untuk 1 assessment + 1 kelas + 1 mapel
     */
    public function getSetting($assessmentId, $classroomId, $subjectId)
    {
        return $this->where('assessment_id', $assessmentId)
                    ->where('classroom_id', $classroomId)
                    ->where('subject_id', $subjectId)
                    ->first();
    }

    /**
     * Simpan atau update setting (upsert)
     */
    public function saveSetting($assessmentId, $classroomId, $subjectId, $data)
    {
        $existing = $this->getSetting($assessmentId, $classroomId, $subjectId);

        $data['assessment_id'] = $assessmentId;
        $data['classroom_id']  = $classroomId;
        $data['subject_id']    = $subjectId;

        // Cek apakah bobot sudah diisi dan total = 100
        $totalBobot = ($data['bobot_pg'] ?? 0)
                    + ($data['bobot_bs'] ?? 0)
                    + ($data['bobot_isian'] ?? 0)
                    + ($data['bobot_essay'] ?? 0);

        $data['bobot_filled'] = ($totalBobot === 100) ? 1 : 0;

        if ($existing) {
            return $this->update($existing['id'], $data);
        }

        return $this->insert($data);
    }

    /**
     * Hitung jumlah soal dari string kunci jawaban
     */
    public function countSoal($kunci)
    {
        if (empty($kunci)) return 0;
        // Hapus whitespace kecuali spasi (spasi = jawaban kosong, tetap dihitung)
        $clean = preg_replace('/[\r\n\t]/', '', $kunci);
        return strlen($clean);
    }

    /**
     * Koreksi jawaban PG atau BS
     * Spasi pada jawaban siswa = berbeda dengan kunci (salah)
     * Notif kalau jumlah karakter beda
     */
    public function koreksiJawaban($kunci, $jawabanSiswa)
    {
        $kunciArr   = str_split($kunci);
        $jawabanArr = str_split($jawabanSiswa);
        $totalSoal  = count($kunciArr);
        $totalJawab = count($jawabanArr);

        $benar = 0;
        for ($i = 0; $i < $totalSoal; $i++) {
            $k = strtoupper($kunciArr[$i]);
            $j = isset($jawabanArr[$i]) ? strtoupper($jawabanArr[$i]) : '';
            // Spasi dianggap beda dengan kunci apapun
            if ($j === $k) {
                $benar++;
            }
        }

        $skor  = $totalSoal > 0 ? round(($benar / $totalSoal) * 100, 2) : 0;
        $notif = null;

        if ($totalJawab < $totalSoal) {
            $notif = 'Jawaban kurang ' . ($totalSoal - $totalJawab) . ' soal';
        } elseif ($totalJawab > $totalSoal) {
            $notif = 'Jawaban lebih ' . ($totalJawab - $totalSoal) . ' soal';
        }

        return [
            'benar'       => $benar,
            'total_soal'  => $totalSoal,
            'total_jawab' => $totalJawab,
            'skor'        => $skor,
            'notif'       => $notif,
        ];
    }

    /**
     * Hitung nilai akhir dengan bobot (ROUNDUP)
     */
    public function hitungNilaiAkhir($setting, $skorPg, $skorBs, $skorIsian, $skorEssay)
    {
        $nilai = (($skorPg    * $setting['bobot_pg'])
                + ($skorBs    * $setting['bobot_bs'])
                + ($skorIsian * $setting['bobot_isian'])
                + ($skorEssay * $setting['bobot_essay']))
               / 100;

        // Desimal 2 angka, bukan dibulatkan ke atas
        return round($nilai, 2);
    }
}