<?php

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

class Template_Model extends MY_Model {

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

    public function get_template_list($limit, $offset, $search, $count) {
        $this->db->select('DT.*, D.name as department, G.name as group, T.name as test_name');
        $this->db->from('diagnostic_templates AS DT');
        $this->db->join('diagnostic_departments AS D', 'D.id = DT.department_id', 'left');
        $this->db->join('diagnostic_groups AS G', 'G.id = DT.group_id', 'left');
        $this->db->join('diagnostic_tests AS T', 'T.id = DT.test_id', 'left');
        if ($search) {
            $this->db->like('DT.name', $search);
            $this->db->or_like('DT.template', $search, 'both');
            $this->db->or_like('D.name', $search, 'both');
            $this->db->or_like('T.name', $search, 'both');
        }
        $this->db->order_by('DT.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_template($id) {
        $this->db->select('DT.*, D.name as department');
        $this->db->from('diagnostic_templates AS DT');
        $this->db->join('diagnostic_departments AS D', 'D.id = DT.department_id', 'left');
        $this->db->where('DT.id', $id);
        return $this->db->get()->row();
    }
}
