<?php

namespace App\Models;

use CodeIgniter\Model;

class SubjectModel extends Model
{
    protected $table            = 'subjects';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'array';
    protected $useSoftDeletes   = true;
    protected $allowedFields    = ['code', 'name', 'level', 'phase', 'group', 'is_core', 'description'];

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

    // Ambil mapel berdasarkan level jenjang sekolah (untuk setting mapel sekolah)
    public function getByLevel($level)
    {
        return $this->where('level', $level)
                    ->orWhere('level', 'ALL')
                    ->orderBy('group', 'ASC')
                    ->orderBy('name', 'ASC')
                    ->findAll();
    }

    // Ambil mapel berdasarkan level + group (untuk tampilan berkelompok)
    public function getGroupedByLevel($level)
    {
        $subjects = $this->getByLevel($level);
        
        $grouped = [];
        foreach ($subjects as $subject) {
            $group = $subject['group'] ?? 'Lainnya';
            if (!isset($grouped[$group])) {
                $grouped[$group] = [];
            }
            $grouped[$group][] = $subject;
        }
        
        return $grouped;
    }
}