<?php

namespace App\Models;

use CodeIgniter\Model;

class MateriModel extends Model
{
    protected $table = 'elearning_materi';
    protected $primaryKey = 'id';

    protected $useTimestamps = true;
    protected $allowedFields = [
        'subject_id',
        'kelas',
        'judul',
        'deskripsi',
        'tipe',
        'file_path',
        'view_count',
        'is_active',
        'created_by'
    ];

    // 🔥 QUERY JOIN PREMIUM
    public function getWithMapel()
    {
        return $this->select('
                elearning_materi.*,
                master_subject.nama_mapel
            ')
            ->join(
                'master_subject',
                'master_subject.id = elearning_materi.subject_id',
                'left'
            )
            ->orderBy('elearning_materi.created_at', 'DESC')
            ->findAll();
    }

    public function filterMateri($keyword = null, $mapel = null, $kelas = null)
    {
        $builder = $this->select('
            elearning_materi.*,
            master_subject.nama_mapel
        ')
            ->join('master_subject', 'master_subject.id = elearning_materi.subject_id', 'left')
            ->where('elearning_materi.is_active', 1);

        if ($keyword) {
            $builder->like('judul', $keyword);
        }

        if ($mapel) {
            $builder->where('subject_id', $mapel);
        }

        if ($kelas) {
            $builder->where('kelas', $kelas);
        }

        return $builder->orderBy('created_at', 'DESC')->findAll();
    }

}
