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

class Expense_types_model extends CI_Model {

    public function __construct()
    {
        parent::__construct();
    }

    // ✅ Create new expense type
    public function create($options)
    {
        $this->db->insert('kns1_expense_types', $options);
        return $this->db->insert_id();
    }

    // ✅ Update expense type
    public function update($id, $options)
    {
        $this->db->where('id', $id);
        $this->db->update('kns1_expense_types', $options);
        return $id;
    }

    // ✅ Get all main expense types
    public function get_all($limit = NULL, $offset = NULL)
    {
        $this->db->order_by('id', 'DESC');
        $query = $this->db->get('kns1_expense_types', $limit, $offset);
        return $query->result();
    }

    // ✅ Get all sub expense types
    public function sub_get_all($limit = NULL, $offset = NULL)
    {
        $this->db->order_by('id', 'DESC');
        $query = $this->db->get('kns1_sub_expense_types', $limit, $offset);
        return $query->result();
    }

    // ✅ Get main expense type name by ID
    public function get_expense_type_name($id)
    {
        if (empty($id)) return 'Unknown';

        $this->db->select('expense_type');
        $query = $this->db->get_where('kns1_expense_types', ['id' => $id]);

        if ($query->num_rows() > 0) {
            return $query->row()->expense_type;
        }

        return 'Unknown';
    }

    // ✅ Get sub expense type name by ID
    public function get_sub_expense_type_name($id)
    {
        if (empty($id)) return 'Unknown';

        $this->db->select('sub_expense_type');
        $query = $this->db->get_where('kns1_sub_expense_types', ['id' => $id]);

        if ($query->num_rows() > 0) {
            return $query->row()->sub_expense_type;
        }

        return 'Unknown';
    }

    // ✅ Delete main expense type
    public function destroy($id)
    {
        $this->db->where('id', $id);
        $this->db->delete('kns1_expense_types');
        return $this->db->affected_rows();
    }
}
