<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Master_pendidikan_model extends CI_Model {

    protected $table = 'master_pendidikan';

    public function get_all($aktif_only = false) {
        if ($aktif_only) {
            $this->db->where('status', 1);
        }
        $this->db->order_by('urutan', 'ASC');
        $this->db->order_by('nama', 'ASC');
        return $this->db->get($this->table)->result();
    }

    public function get_by_id($id) {
        return $this->db->get_where($this->table, ['id' => $id])->row();
    }

    public function get_dropdown() {
        $this->db->where('status', 1);
        $this->db->order_by('urutan', 'ASC');
        $rows = $this->db->get($this->table)->result();
        $options = [];
        foreach ($rows as $r) {
            $options[$r->nama] = $r->nama;
        }
        return $options;
    }

    public function insert($data) {
        $data['created_at'] = date('Y-m-d H:i:s');
        $data['updated_at'] = date('Y-m-d H:i:s');
        $this->db->insert($this->table, $data);
        return $this->db->insert_id();
    }

    public function update($id, $data) {
        $data['updated_at'] = date('Y-m-d H:i:s');
        $this->db->where('id', $id);
        return $this->db->update($this->table, $data);
    }

    public function delete($id) {
        $this->db->where('id', $id);
        return $this->db->delete($this->table);
    }

    public function toggle_status($id) {
        $row = $this->get_by_id($id);
        if ($row) {
            $new_status = ($row->status == 1) ? 0 : 1;
            return $this->update($id, ['status' => $new_status]);
        }
        return false;
    }

    public function count_all() {
        return $this->db->count_all($this->table);
    }
}
