<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Income_Model extends MY_Model
{

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

    public function get_employee_list()
    {
        $this->db->select('E.*');
        $this->db->from('employees AS E');
        $this->db->join('users AS U', 'U.id = E.user_id', 'left');
        $this->db->where('E.status', '1');
        if ($this->session->userdata('role_id') == SUPER_ADMIN) {
            $this->db->where_in('U.role_id', array(SUPER_ADMIN, ADMIN, ACCOUNTANT, RECEPTIONIST));
        } else {
            $this->db->where_in('U.role_id', array(ADMIN, ACCOUNTANT, RECEPTIONIST, MARKETING));
        }
        $this->db->order_by('E.id ', 'DESC');
        return $this->db->get()->result();
    }

    public function get_income_list($limit, $offset, $keyword, $form_date, $to_date, $income_head_id, $type, $payment_method, $created_by, $count)
    {
        $this->db->select('I.*, IH.name as income_head');
        $this->db->from('incomes AS I');
        $this->db->join('income_heads AS IH', 'IH.id = I.income_head_id', 'left');
        if ($keyword) {
            $this->db->like('E.custom_invoice_id', $keyword);
            $this->db->or_like('I.name', $keyword);
            $this->db->or_like('I.invoice_no', $keyword);
            $this->db->or_like('I.bank_name', $keyword);
            $this->db->or_like('I.cheque_no', $keyword);
            $this->db->or_like('IH.name', $keyword);
        }
        if ($form_date && $to_date) {
            $this->db->where("DATE(I.date) BETWEEN '$form_date' AND '$to_date'");
        }
        if ($income_head_id) {
            $this->db->where('I.income_head_id', $income_head_id);
        }
        if ($type) {
            $this->db->where('I.type', $type);
        }
        if ($payment_method) {
            $this->db->where('I.payment_method', $payment_method);
        }
        if ($created_by) {
            $this->db->where('I.created_by', $created_by);
        }
        $this->db->order_by('I.id', 'DESC');
        if ($count) {
            return $this->db->count_all_results();
        } else {
            $this->db->limit($limit, $offset);
            $query = $this->db->get();

            if ($query->num_rows() > 0) {
                return $query->result();
            }
        }
        return array();
    }


    public function get_single_income($id)
    {
        $this->db->select('I.*, IH.name as income_head, C.name as created_by, M.name as modified_by');
        $this->db->from('incomes AS I');
        $this->db->join('income_heads AS IH', 'IH.id = I.income_head_id', 'left');
        $this->db->join('employees AS C', 'C.user_id = I.created_by', 'left');
        $this->db->join('employees AS M', 'M.user_id = I.modified_by', 'left');
        $this->db->where('I.id', $id);
        return $this->db->get()->row();
    }
}
