<?php

namespace App\Models;

use CodeIgniter\Model;

class Penilaian_model extends Model
{
    var $table = 'penilaian';
    public function __construct()
    {
        parent::__construct();
        $this->allowedFields = $this->db->getFieldNames('penilaian');
    }

    // public function get_all_penilaian()
    // {
    //     $query = $this->db->table($this->table)
    //         ->get();
    //     return $query->getResult();
    // }
    public function get_all_penilaian()
    {

        $query = $this->db->table('siswa')
            ->select('siswa.id as id_siswa,siswa.nama,siswa.rombel,siswa.nis')
            ->orderBy('siswa.rombel', 'ASC')
            ->orderBy('siswa.nama', 'ASC')
            ->get();

        $result = $query->getResult();
        $siswaArray = array();
        foreach ($result as &$row) {
            $subquery = $this->db->table('penilaian')
                ->select('penilaian.kode_mapel, penilaian.nilai')
                ->where('penilaian.nis', $row->nis)
                ->get()
                ->getResult();
            $row->penilaian = $subquery;
            $siswaArray[] = $row;
        }
        $querypembelajaran = $this->db->table('matapelajaran')
            ->select('matapelajaran.kode as kode_mapel, matapelajaran.nama_matapelajaran')
            ->where('matapelajaran.status', 'aktif')
            ->orderBy('matapelajaran.no_urut', 'asc')
            ->get()
            ->getResult();


        return ['pembelajaran' => $querypembelajaran, 'siswa' => $siswaArray];
    }
    public function get_wali()
    {
        $query = $this->db->table('users')
            ->where('role', 'guru')
            ->get();
        return $query->getResult();
    }

    public function get_by_id($id)
    {
        $query =  $this->db->table($this->table)
            ->where('id', $id)
            ->get();
        return $query->getRow();
    }
    public function penilaian_add($data)
    {
        $query = $this->db->table($this->table)->insert($data);
        return $this->db->insertID();
    }
    public function update_status($where)
    {

        $cekdata = $this->db->table($this->table)
            ->update(['status' => 'tidak'], $where);
        return $cekdata;
    }
    public function update_setting($data)
    {
        $update = $this->db->table('settings')
            ->update(['penilaian' => $data], ['id' => 1]);
        return $update;
    }

    public function penilaian_update($where, $data)
    {
        $this->db->table($this->table)->update($data, $where);
        return $this->db->affectedRows();
    }

    public function delete_by_id($id)
    {
        $this->db->table($this->table)->delete(array('id' => $id));
    }
}
