<?php

namespace App\Models;

use CodeIgniter\Model;

class AssessmentDetailScoreModel extends Model
{
    protected $table            = 'assessment_detail_scores';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'array';
    protected $useSoftDeletes   = false;
    protected $allowedFields    = [
        'score_id', 'jenis', 'nomor_soal', 'skor',
    ];

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

    /**
     * Ambil detail skor per nomor soal
     */
    public function getDetail($scoreId, $jenis)
    {
        return $this->where('score_id', $scoreId)
                    ->where('jenis', $jenis)
                    ->orderBy('nomor_soal', 'ASC')
                    ->findAll();
    }

    /**
     * Hitung skor max per nomor soal
     * Misal: 4 soal → max per soal = 100/4 = 25
     * Misal: 5 soal → max per soal = 100/5 = 20
     */
    public function getSkorMaxPerSoal($totalSoal)
    {
        if ($totalSoal <= 0) return 0;
        return round(100 / $totalSoal, 2);
    }

    /**
     * Simpan detail skor per nomor soal
     */
    public function saveDetails($scoreId, $jenis, $details)
    {
        // Hapus dulu yang lama
        $this->where('score_id', $scoreId)
             ->where('jenis', $jenis)
             ->delete();

        // Insert baru
        foreach ($details as $detail) {
            $this->insert([
                'score_id'   => $scoreId,
                'jenis'      => $jenis,
                'nomor_soal' => $detail['nomor_soal'],
                'skor'       => $detail['skor'] ?? 0,
            ]);
        }
    }

    /**
     * Hitung total skor dari detail per nomor.
     *
     * Karena skor per soal sudah dalam skala (100/totalSoal),
     * total cukup dijumlah saja, hasilnya otomatis max 100.
     *
     * Contoh: 4 soal, max per soal = 25
     *   Guru input: 25, 25, 20, 25 → total = 95  ✓
     *   Guru input: 25, 25, 25, 25 → total = 100 ✓
     *
     * Contoh: 2 soal, max per soal = 50
     *   Guru input: 50, 50 → total = 100 ✓
     *   Guru input: 40, 30 → total = 70  ✓
     */
    public function hitungTotalSkor($scoreId, $jenis, $totalSoal)
    {
        if ($totalSoal <= 0) return 0;

        $details = $this->getDetail($scoreId, $jenis);
        $total   = array_sum(array_column($details, 'skor'));

        // Pastikan tidak melebihi 100, kembalikan integer
        return min((int) round($total), 100);
    }
}