<?php

namespace App\Models;

use CodeIgniter\Model;

class SubjectTargetModel extends Model
{
    protected $table = 'subject_target_hours';
    protected $primaryKey = 'id';
    protected $useAutoIncrement = true;
    protected $returnType = 'array';
    protected $useSoftDeletes = false;
    protected $protectFields = true;
    protected $allowedFields = ['subject_id', 'grade_id', 'target_hours'];

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

    // Ambil semua target dengan join nama mapel dan tingkat
    public function getAllWithNames()
    {
        return $this->db->table('subject_target_hours sth')
            ->select('sth.*, ss.name as subject_name, g.name as grade_name, g.order as grade_order')
            ->join('school_subjects ss', 'ss.id = sth.subject_id')
            ->join('grades g', 'g.id = sth.grade_id')
            ->orderBy('ss.name')
            ->orderBy('g.order')
            ->get()
            ->getResultArray();
    }

    // Ambil target per mapel
    public function getBySubject($subjectId)
    {
        return $this->where('subject_id', $subjectId)
            ->orderBy('grade_id')
            ->findAll();
    }

    // Ambil target per tingkat
    public function getByGrade($gradeId)
    {
        return $this->where('grade_id', $gradeId)
            ->orderBy('subject_id')
            ->findAll();
    }

    // Update atau insert target
    public function setTarget($subjectId, $gradeId, $targetHours)
    {
        $existing = $this->where('subject_id', $subjectId)
            ->where('grade_id', $gradeId)
            ->first();

        if ($existing) {
            return $this->update($existing['id'], ['target_hours' => $targetHours]);
        } else {
            return $this->insert([
                'subject_id' => $subjectId,
                'grade_id' => $gradeId,
                'target_hours' => $targetHours,
            ]);
        }
    }

    // Hitung total target per mapel
    public function getTotalBySubject($subjectId)
    {
        $result = $this->select('SUM(target_hours) as total')
            ->where('subject_id', $subjectId)
            ->get()
            ->getRowArray();
        return (int)($result['total'] ?? 0);
    }
}