<?php

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

class Supplier_Model extends MY_Model {

    function __construct() {
        parent::__construct();
    }
    public function get_supplier_list($limit, $offset, $search, $count) {
        $this->db->select('S.*');
        $this->db->from('suppliers AS S');
        if ($search) {
            $this->db->like('S.phone', $search, 'both');
            $this->db->or_like('S.name', $search, 'both');
            $this->db->or_like('S.note', $search, 'both');
        }
        $this->db->order_by('S.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();
    }

    function get_single_supplier($id) {
        $this->db->select('S.*, C.name as created_by, E.name as modified_by');
        $this->db->from('suppliers AS S');
        $this->db->join('employees AS C', 'C.user_id = S.created_by', 'left');
        $this->db->join('employees AS E', 'E.user_id = S.modified_by', 'left');
        $this->db->where('S.id', $id);
        return $this->db->get()->row();
    }

    function duplicate_check($name, $id = null) {
        if ($id) {
            $this->db->where_not_in('id', $id);
        }
        $this->db->where('name', $name);
        return $this->db->get('suppliers')->num_rows();
    }
}
