<?php

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

class patient_model extends CI_Model {

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

    /* This function create patient patient. */

    function create() {

        $this->db->set('pi_name', $this->input->post('pi_name'));
        $this->db->set('pi_date_reg', strtotime($this->input->post('pi_date_reg')));
        $this->db->set('pi_mother', $this->input->post('pi_mother'));
        $this->db->set('pi_father', $this->input->post('pi_father'));
        $this->db->set('pi_family', $this->input->post('pi_family'));
        $this->db->set('pi_passport', $this->input->post('pi_passport'));
        $this->db->set('pi_borndate', strtotime($this->input->post('pi_borndate')));
        $this->db->set('pi_bornplace', $this->input->post('pi_bornplace'));
        $this->db->set('pi_gender', $this->input->post('pi_gender'));
        $this->db->set('pi_turk_address', $this->input->post('pi_turk_address'));
        $this->db->set('pi_syr_address', $this->input->post('pi_syr_address'));
        $this->db->set('pi_turk_phone', $this->input->post('pi_turk_phone'));
        $this->db->set('pi_syr_phone', $this->input->post('pi_syr_phone'));
        $this->db->set('pi_relative_name', $this->input->post('pi_relative_name'));
        $this->db->set('pi_relative_type', $this->input->post('pi_relative_type'));
        $this->db->set('pi_relative_address', $this->input->post('pi_relative_address'));
        $this->db->set('pi_relative_phone', $this->input->post('pi_relative_phone'));
        $this->db->set('pi_ocurdesc', $this->input->post('pi_ocurdesc'));
        $this->db->set('pi_ocurdate', strtotime($this->input->post('pi_ocurdate')));
        $this->db->set('pi_ocurplace', $this->input->post('pi_ocurplace'));
        $this->db->set('pi_steps', $this->input->post('pi_steps'));
        $this->db->set('pi_current_sit', $this->input->post('pi_current_sit'));
        $this->db->set('pi_importance', $this->input->post('pi_importance'));
        $this->db->set('pi_importance_date', strtotime($this->input->post('pi_importance_date')));
        $this->db->set('pi_med_team', $this->input->post('pi_med_team'));
        $this->db->set('pi_guide_team', $this->input->post('pi_guide_team'));
        $this->db->set('pi_housing_date', $this->input->post('pi_housing_date'));
        $this->db->set('pi_housing_follow', $this->input->post('pi_housing_follow'));
        $this->db->set('pi_branch_id', $this->input->post('pi_branch_id'));
        $this->db->set('pi_num', $this->input->post('pi_num'));
        $this->db->set('pi_num2', $this->input->post('pi_num2'));

        $this->db->set('pi_created', time());
        $this->db->insert('d_patient');
        $id = $this->db->insert_id();
        $this->_update_page_assoc($id);
        return TRUE;
    }

    /*  This function get all patient in database sort by order asc. */

    function get_patient($row) {
        $result = $this->db->query("SELECT 
    d_patient.*,
    d_branch.*
    FROM d_patient
    LEFT JOIN d_branch ON d_patient.pi_branch_id = d_branch.branch_id
    where pi_hide = '1'
    ORDER BY pi_num ASC
    LIMIT $row,10");

        return $result->result_array();
    }

    function get_branch_category($id) {
        $this->db->where('branch_id', $id);

        $result = $this->db->get('d_branch');
        return $result->result_array();
    }

    /*  This function get all categories of product_type from database sort by order asc. */

    function get_product_type_category() {
        $this->db->where('pt_hide', '1');

        $result = $this->db->get('d_product_type_category');
        return $result->result_array();
    }

    /**
     *
     * @param integer $book_id 
     * @param string $field_name the name of the field
     * @param string $value  the modified value
     */
    public function insert_one_field($book_id, $value) {
        $this->db->set("ph_name", $value);
        $this->db->set("ph_dept_photos_id", $book_id);
        $this->db->insert($this->table);
    }

    // get total number of users
    function getNumUsersAdmin() {
        $query = $this->db->query("select * from d_patient");
        return $query->num_rows();
    }

    /* This function delete patient from database. */

    function delete($id) {
        $this->db->set('pi_hide', '0');
        $this->db->where('pi_id', $id);
        $this->db->update('d_patient');
    }

    function is_valid_patient($id) {
        $this->db->where('pi_id', $id);
        $this->db->from('d_patient');
        if ($this->db->count_all_results() > 0) {
            return TRUE;
        } else {
            return FALSE;
        }
    }

    function is_valid_page($id) {
        $this->db->where('pi_id', $id);
        $this->db->from('d_patient');
        if ($this->db->count_all_results() > 0) {
            return TRUE;
        } else {
            return FALSE;
        }
    }

    function get_page($id) {
        $this->db->where('pi_id', $id);
        $result = $this->db->get('d_patient');
        if ($result->num_rows() > 0) {
            return $result->row_array();
        } else {
            return FALSE;
        }
    }

    function _get_next_page($direction, $order_by) {
        if ($direction == 'up') {
            $this->db->where("pi_ord < $order_by");
            $this->db->order_by('pi_ord', 'desc');
            $this->db->limit(1, 0);
        } else {
            $this->db->where("pi_ord > $order_by");
            $this->db->order_by('pi_ord', 'asc');
            $this->db->limit(1, 0);
        }
        $result = $this->db->get('d_patient');
        if ($result->num_rows() == 1) {
            return $result->row_array();
        } else {
            return FALSE;
        }
    }

    function sort($direction, $id) {
        $page = $this->get_page($id);
        $next_page = $this->_get_next_page($direction, $page['pi_ord']);
        if (is_array($next_page)) {
            $this->db->set('pi_ord', $next_page['pi_ord']);
            $this->db->where('pi_id', $page['pi_id']);
            $this->db->update('d_patient');

            $this->db->set('pi_ord', $page['pi_ord']);
            $this->db->where('pi_id', $next_page['pi_id']);
            $this->db->update('d_patient');
            return TRUE;
        } else {
            return FALSE;
        }
    }

    function _update_page_assoc($id) {
        $this->db->select_max('pi_ord');
        $result = $this->db->get('d_patient');
        $row = $result->row();
        $max_ord = $row->pi_ord + 1;
        $this->db->where('pi_id', $id);
        $this->db->set('pi_ord', $max_ord);
        $this->db->update('d_patient');
        return TRUE;
    }

    function activate($id) {
        $this->db->set('pi_hide', '1');
        $this->db->where('pi_id', $id);
        $this->db->update('d_patient');
    }

    function deactivate($id) {
        $this->db->set('pi_hide', '0');
        $this->db->where('pi_id', $id);
        $this->db->update('d_patient');
    }

    function update($id) {
        $this->db->where('pi_id', $id);
        $this->db->set('pi_name', $this->input->post('pi_name'));
        $this->db->set('pi_date_reg', strtotime($this->input->post('pi_date_reg')));
        $this->db->set('pi_mother', $this->input->post('pi_mother'));
        $this->db->set('pi_father', $this->input->post('pi_father'));
        $this->db->set('pi_family', $this->input->post('pi_family'));
        $this->db->set('pi_passport', $this->input->post('pi_passport'));
        $this->db->set('pi_borndate', strtotime($this->input->post('pi_borndate')));
        $this->db->set('pi_bornplace', $this->input->post('pi_bornplace'));
        $this->db->set('pi_branch_id', $this->input->post('pi_branch_id'));
        $this->db->set('pi_gender', $this->input->post('pi_gender'));
        $this->db->set('pi_turk_address', $this->input->post('pi_turk_address'));
        $this->db->set('pi_syr_address', $this->input->post('pi_syr_address'));
        $this->db->set('pi_turk_phone', $this->input->post('pi_turk_phone'));
        $this->db->set('pi_syr_phone', $this->input->post('pi_syr_phone'));
        $this->db->set('pi_relative_name', $this->input->post('pi_relative_name'));
        $this->db->set('pi_relative_type', $this->input->post('pi_relative_type'));
        $this->db->set('pi_relative_address', $this->input->post('pi_relative_address'));
        $this->db->set('pi_relative_phone', $this->input->post('pi_relative_phone'));
        $this->db->set('pi_ocurdesc', $this->input->post('pi_ocurdesc'));
        $this->db->set('pi_ocurdate', strtotime($this->input->post('pi_ocurdate')));
        $this->db->set('pi_ocurplace', $this->input->post('pi_ocurplace'));
        $this->db->set('pi_steps', $this->input->post('pi_steps'));
        $this->db->set('pi_current_sit', $this->input->post('pi_current_sit'));
        $this->db->set('pi_importance', $this->input->post('pi_importance'));
        $this->db->set('pi_importance_date', strtotime($this->input->post('pi_importance_date')));
        $this->db->set('pi_med_team', $this->input->post('pi_med_team'));
        $this->db->set('pi_guide_team', $this->input->post('pi_guide_team'));
        $this->db->set('pi_housing', $this->input->post('pi_housing'));
        $this->db->set('pi_housing_date', $this->input->post('pi_housing_date'));
        $this->db->set('pi_housing_follow', $this->input->post('pi_housing_follow'));
        $this->db->set('pi_num2', $this->input->post('pi_num2'));

        $this->db->update('d_patient');
        return TRUE;
    }

    function get_patient_one($id) {
        $result = $this->db->query("SELECT
  d_patient.*,
  d_branch.*
FROM d_patient
  LEFT JOIN d_branch
    ON d_patient.pi_branch_id = d_branch.branch_id
    WHERE d_patient.pi_id = $id  GROUP BY d_patient.pi_id
");

        return $result->row();
    }

    function operation() {
        if (!empty($_POST['check_nf'])) {
            $products = $_POST['check_nf'];
            for ($i = 0; $i <= count($products) - 1; $i++) {
                switch ($_POST['operation']) {
                    case "active":
                        $this->db->where('pi_id', $products[$i]);
                        $this->db->set('pi_hide', '1');
                        $this->db->update('d_patient');
                        $this->session->set_flashdata('success_msg', $this->lang->line('success_msg_active_all'));
                        break;

                    case "inactive":
                        $this->db->where('pi_id', $products[$i]);
                        $this->db->set('pi_hide', '0');
                        $this->db->update('d_patient');
                        $this->session->set_flashdata('success_msg', $this->lang->line('success_msg_inactive_all'));
                        break;

                    case "delete":
                        $this->db->where('pi_id', $products[$i]);
                        $result = $this->db->get('d_patient');
                        $r = $result->row();
                        $this->db->where('pi_id', $products[$i]);
                        $this->db->delete('d_patient');
                        $this->session->set_flashdata('success_msg', $this->lang->line('success_msg_del_all'));
                        break;
                }
            }
        }
//        if (isset($_POST['check_nf2'])) {
//            $products = $_POST['check_nf2'];
//            switch ($_POST['operation']) {
//                case "active":
//                    $this->db->set('pi_hide', '1');
//                    $this->db->update('d_patient');
//                    $this->session->set_flashdata('success_msg', $this->lang->line('success_msg_active_all'));
//                    break;
//                case "inactive":
//                    $this->db->set('pi_hide', '0');
//                    $this->db->update('d_patient');
//                    $this->session->set_flashdata('success_msg', $this->lang->line('success_msg_inactive_all'));
//                    break;
//                case "delete":
//                    $result = $this->db->get('d_patient');
//                    $r = $result->result_array();
//                    foreach ($r as $rm):
//                        if (file_exists(PUBPATH . "global/uploads/" . $rm['pi_img'])) {
//                            unlink(PUBPATH . "global/uploads/" . $rm['pi_img']);
//                        }
//                        $this->db->delete('d_patient');
//                    endforeach;
//                    $this->session->set_flashdata('success_msg', $this->lang->line('success_msg_del_all'));
//                    break;
//            }
//        }
    }

    function get_category() {
        $result = $this->db->get('d_product_type_category');
        return $result->result_array();
    }

    function get_all() {
        $result = $this->db->query("SELECT
  d_patient.*,
  d_branch.*
FROM d_patient
  INNER JOIN d_branch
    ON d_patient.pi_branch_id = d_branch.branch_id
    WHERE d_patient.pi_hide = '1'  GROUP BY d_patient.pi_id");
        return $result->result_array();
    }

    function get_max_id() {
        $result = $this->db->query('SELECT pi_id
                                    FROM d_patient
                                    ORDER BY pi_id DESC
                                    LIMIT 1');
        return $result->row();
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////
    //////////////frontend//////////////////////////////////////////////////////////


    function add_count($count, $id) {
        $this->db->where('pi_id', $id);
        $this->db->set('pi_count_visit', ($count + 1));
        $this->db->update('d_patient');
    }

    function _update_page_assoc2($id) {
        $this->db->select_max('cn_ord');
        $result = $this->db->get('d_comments_patient');
        $row = $result->row();
        $max_ord = $row->cn_ord + 1;
        $this->db->where('cn_id', $id);
        $this->db->set('cn_ord', $max_ord);
        $this->db->update('d_comments_patient');
        return TRUE;
    }

    /////////////////////////////////paging////////////////////////////
    function getUsersWhere($field, $param) {
        $this->db->where($field, $param);
        $query = $this->db->get('d_patient');
        // return result set as an associative array
        return $query->result_array();
    }

    function get_one($id) {
        $this->db->where("pi_id", $id);
        $query = $this->db->get('d_patient');
        // return result set as an associative array
        return $query->row();
    }

    // get 5 rows at a time
    function getUsers($row) {
        $this->db->order_by('pi_created', 'desc');
        $this->db->where('pi_hide', 1);
        $query = $this->db->get('d_patient', 5, $row);
        if ($query->num_rows() > 0) {
            // return result set as an associative array
            return $query->result_array();
        }
    }

    // get total number of users
    function getNumUsers() {
        $query = $this->db->query("select * from d_patient where pi_hide = '1'");
        return $query->num_rows();
    }

    // get total number of users
    function getNumbycat($pt_id) {
        $query = $this->db->query("select * from d_patient where pi_product_type_id = $pt_id and pi_hide = 1");
        return $query->num_rows();
    }

    //////////////////////////////////end paging///////////////////


    function get_patient_by_product($pt_id, $row) {
        $result = $this->db->query("
            SELECT  *
            FROM d_patient
            WHERE d_patient.pi_product_type_id = $pt_id
            and pi_hide = 1
        limit $row,10");
        return $result->result_array();
    }

    function search_all() {
        $pi_num = $this->input->post('pi_num');
        $pi_name = $this->input->post('pi_name');
        $pi_passport = $this->input->post('pi_passport');
        $pi_date_reg = $this->input->post('pi_date_reg');
        $pi_date_reg2 = $this->input->post('pi_date_reg2');
        $pi_branch_id = $this->input->post('pi_branch_id');
        $pi_gender = $this->input->post('pi_gender');
        $pi_importance = $this->input->post('pi_importance');
        $conditions = array();

        if ($pi_num !== '') {
            $conditions[] = 'pi_num LIKE "' . $pi_num . '"';
        }
        if ($pi_name) {
            $conditions[] = 'CONCAT(d_patient.pi_name, " ", d_patient.pi_father," ",d_patient.pi_family) = "' . $pi_name . '"';
        }
        if ($pi_passport !== '') {
            $conditions[] = 'pi_passport = "' . $pi_passport . '"';
        }

        if ($pi_date_reg !== '' AND $pi_date_reg2 !== '') {
            $conditions[] = "(pi_date_reg  BETWEEN '" . strtotime($pi_date_reg) . "' AND '" . strtotime($pi_date_reg2) . "')";
        }
        if ($pi_gender !== '') {
            $conditions[] = 'pi_gender = "' . $pi_gender . '"';
        }
        if ($pi_importance !== '') {
            $conditions[] = 'pi_importance = "' . $pi_importance . '"';
        }
        if ($pi_branch_id !== '') {
            $conditions[] = 'pi_branch_id = "' . $pi_branch_id . '"';
        }
        $conditions[] = 'pi_hide = "' . 1 . '"';


        $sqlStatement = 'SELECT
                    d_branch.*,
                    d_patient.*
                  FROM  d_patient
                    LEFT JOIN d_branch
                      ON d_branch.branch_id = d_patient.pi_branch_id WHERE ' . implode(' AND ', $conditions);
        $result = $this->db->query($sqlStatement);

        return $result->result_array();
    }

/////// auto filter search /////////////////

    public function listBarang() {
        $result = $this->db->select('d_patient.*,d_branch.*')
                ->limit($this->limit, $this->offset)
                ->join('d_branch', 'd_patient.pi_branch_id = d_branch.branch_id', 'left')
                ->get('d_patient');
        return $result->result_array();
    }

    public function listBarang_page($descp) {
        $result = $this->db->select('d_patient.*,d_branch.*')
                ->limit($this->limit, $this->offset)
                ->order_by('d_patient.pi_num', 'ASC')
                ->join('d_branch', 'd_patient.pi_branch_id = d_branch.branch_id', 'left')
                ->like('CONCAT(d_patient.pi_name, " ", d_patient.pi_father," ",d_patient.pi_family)', $descp)
                ->or_like('pi_id', $descp)
                ->get('d_patient', $this->limit, $this->offset);
        return $result->result_array();
    }

    public function numRec() {
        $query = $this->db->count_all("d_patient");
        return $query;
    }

    public function numRec_page($descp) {
        $result = $this->db->select('d_patient.*,d_branch.*')
                ->like('CONCAT(d_patient.pi_name, " ", d_patient.pi_father," ",d_patient.pi_family)', $descp)
                ->join('d_branch', 'd_patient.pi_branch_id = d_branch.branch_id', 'left')
                ->count_all_results('d_patient', $this->limit, $this->offset);
        return $result;
    }

/////////////     all json queries for iphone and android ///////////////////////////
//                      GROUP BY d_patient.pi_name
}
