<?php

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

class Patient_Model extends MY_Model
{

    function __construct()
    {
        parent::__construct();
    }
    public function get_patient_list($limit, $offset, $search, $card_issue, $count)
    {
        $this->db->select('P.*');
        $this->db->from('patients AS P');
        if ($search) {
            $this->db->like('P.phone', $search);
            $this->db->or_like('P.patient_unique_id', $search);
            $this->db->or_like('P.name', $search);
            $this->db->or_like('P.bn_name', $search);
            $this->db->or_like('P.gender', $search);
            $this->db->or_like('P.religion', $search);
            $this->db->or_like('P.blood_group', $search);
            $this->db->or_like('P.marital_status', $search);
            $this->db->or_like('P.address', $search);
        }
        if ($card_issue == 'yes') {
            $this->db->where('P.card_issue_date !=', null);
        }
        if ($card_issue == 'no') {
            $this->db->where('P.card_issue_date =', null);
        }
        $this->db->order_by('P.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_patient($user_id)
    {
        $this->db->select('P.*, U.username, U.temp_password, U.device_id, U.sbiz_id, U.role_id, U.status, C.name as created_by, M.name as modified_by');
        $this->db->from('patients AS P');
        $this->db->join('users AS U', 'U.id = P.user_id', 'left');
        $this->db->join('roles AS R', 'R.id = U.role_id', 'left');
        $this->db->join('employees AS C', 'C.user_id = P.created_by', 'left');
        $this->db->join('employees AS M', 'M.user_id = P.modified_by', 'left');
        $this->db->where('P.user_id', $user_id);
        return $this->db->get()->row();
    }

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