<?php

namespace App\Models;

use CodeIgniter\Model;

class Siswa_model extends Model
{
    var $table = 'siswa';
    public function __construct()
    {
        parent::__construct();
        //$this->load->database();
        $db = \Config\Database::connect();
        $builder = $db->table('siswa');
    }

    public function get_all_siswa($tahunpelajaran)
    {
        $query = $this->db->table('siswa')
            ->select('siswa.*,rombel.nama_rombel')
            ->join('rombel_siswa', 'siswa.id = rombel_siswa.id_siswa', 'left')
            ->join('rombel', "rombel.id = rombel_siswa.id_rombel and rombel.tahunpelajaran='$tahunpelajaran'", 'left')

            ->groupBy('siswa.id')
            ->get();
        return $query->getResult();
    }
    public function get_all_rombel($tahunpelajaran)
    {
        $subQuery = $this->db->table('rombel_siswa')
            ->select('id_siswa')
            ->join('rombel', 'rombel.id = rombel_siswa.id_rombel')
            ->where('rombel.tahunpelajaran', $tahunpelajaran);

        $query = $this->db->table('siswa')
            ->select('id, nama, nis, rombel')
            ->whereNotIn('id', $subQuery)
            ->get();

        return $query->getResult();
    }
    public function get_rombel($jenis)
    {
        //       $query = $this->db->table('siswa');
        $query = $this->db->table('rombel')
            ->where('jenis', $jenis)
            ->get();
        return $query->getResult();
    }
    public function get_siswa_rombel($rombel)
    {

        $query = $this->db->table('siswa')
            ->where('rombel', $rombel)
            ->get();
        return $query->getResult();
    }
    public function get_by_id($id)
    {
        $sql = 'select * from siswa where id =' . $id;
        $query =  $this->db->query($sql);
        return $query->getRow();
    }

    public function siswa_add($data)
    {

        $query = $this->db->table($this->table)->insert($data);

        return $this->db->insertID();
    }

    public function siswa_update($where, $data)
    {
        $this->db->table($this->table)->update($data, $where);
        //        print_r($this->db->getLastQuery());
        return $this->db->affectedRows();
    }

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

    public function cek_by_nis($nis)
    {
        return $this->db->table($this->table)->where(['nis' => $nis])->get()->getNumRows();
    }
}
