<?php

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

/* * *****************Visitor.php**********************************
 * @product name    : Hospital Management System
 * @type            : Class
 * @class name      : Visitor
 * @description     : Manage visitor.
 * @author          : South Bangla IT Zone Team
 * @url             : http://hms.sbitzone.com
 * @support         : rabibd.it@gmail.com
 * @copyright       : South Bangla IT Zone Team
 * ********************************************************** */

class Visitor extends MY_Controller {

    public $data = array();

    function __construct() {
        parent::__construct();
        $this->load->model('Visitor_Model', 'visitor', true);
    }

    /*****************Function index**********************************
     * @type            : Function
     * @function name   : index
     * @description     : Load "Visitor List" user interface
     *
     * @param           : null
     * @return          : null
     * ********************************************************** */
    public function index() {

        check_permission(VIEW);
      
        $search = $this->input->get('search');
      	$create_date = $this->input->get('date');
      	$profession = $this->input->get('profession');
		$pregnancy = $this->input->get('pregnancy');
      	$treatment = $this->input->get('treatment');
      	$card = $this->input->get('card');
      	$package = $this->input->get('package');
      	$land = $this->input->get('land');
      	$operation = $this->input->get('operation');
      	$test = $this->input->get('test');
      	$created_by = $this->input->get('created_by');
     
     
     
     
      
            if (isset($create_date) && !empty($create_date)) {
                $exp = explode('-', $create_date);
                $create_form_date = date('Y-m-d', strtotime($exp[0]));
                $create_to_date = date('Y-m-d', strtotime($exp[1]));
            } else {
                $create_form_date = null;
                $create_to_date = null;
            }
        $config = array();
        $config = get_pagination(ADMIN_PER_PAGE);
 
        if (isset($create_date) && !empty($create_date)) {
            $config['base_url'] = site_url('frontoffice/visitor/?search='.$search.'&date='.$create_date.'&profession='.$profession.'&pregnancy='.$pregnancy.'&treatment='.$treatment.'&card='.$card.'&package='.$package.'&land='.$land.'&operation='.$operation.'&test='.$test.'&created_by='.$created_by);
        } else {
            $config['base_url'] = current_url();
        }
        if ($this->input->get('page')) {
            $sgm = (int) trim($this->input->get('page'));
            $offset = $config['per_page'] * ($sgm - 1);
        } else {
            $offset = 0;
        }
      
     

        $config['total_rows'] = $this->visitor->get_visitor_list($config['per_page'], $offset, $search, $create_form_date, $create_to_date, $profession, $pregnancy, $treatment, $card, $package, $land, $operation, $test, $created_by, $count = TRUE);
        $this->pagination->initialize($config);
        $this->data['visitors'] = $this->visitor->get_visitor_list($config['per_page'], $offset, $search, $create_form_date, $create_to_date, $profession, $pregnancy, $treatment, $card, $package, $land, $operation, $test, $created_by, $count = FALSE);
		
        $this->data['sl_count'] = ($this->input->get('page') == 0 ? 1 : (($this->input->get('page') - 1) * $config["per_page"] + 1));
        $this->data['search'] = $search;
        $this->data['date'] = $create_date;
        $this->data['profession'] = $profession;
      	$this->data['pregnancy'] = $pregnancy;
      	$this->data['treatment'] = $treatment;
      	$this->data['card'] = $card;
      	$this->data['package'] = $package;
      	$this->data['land'] = $land;
      	$this->data['operation'] = $operation;
      	$this->data['test'] = $test;
      	$this->data['created_by'] = $created_by;
      	$this->data['employees'] = $this->visitor->get_employee_list();

        $this->data['list'] = TRUE;
        $this->layout->title($this->lang->line('manage_visitor') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('visitor/index', $this->data);
    }

    /*****************Function add**********************************
     * @type            : Function
     * @function name   : add
     * @description     : Load "Add new Visitor" user interface
     *                    and process to store "visitors" into database
     * @param           : null
     * @return          : null
     * ********************************************************** */
    public function add() {

        check_permission(ADD);
        if ($_POST) {
        
            $this->_prepare_visitor_validation();
            if ($this->form_validation->run() === TRUE) {
                $data = $this->_get_posted_visitor_data();
                $insert_id = $this->visitor->insert('visitors', $data);
                if ($insert_id) {
                    create_log('Has been created a Visitor : ' . $data['name']);
                    success($this->lang->line('insert_success'));
                    redirect('frontoffice/visitor');
                } else {
                    error($this->lang->line('insert_failed'));
                    redirect('frontoffice/visitor/add');
                }
            } else {
                $this->data = $_POST;
            }
        }
      	$this->data['visitor_purposes'] = $this->visitor->get_list('visitor_purposes', array('status' => 1), '', '', '', 'sort_by', 'ASC');
      	$this->data['unions'] = $this->visitor->get_list('unions', array('status' => 1), '', '', '', 'sort_by', 'ASC');
        $this->data['villages'] = $this->visitor->get_list('villages', array('status' => 1), '', '', '', 'sort_by', 'ASC');
        $this->data['add'] = TRUE;
        $this->layout->title($this->lang->line('add') . ' ' . $this->lang->line('visitor') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('visitor/add', $this->data);
    }

    /*****************Function edit**********************************
     * @type            : Function
     * @function name   : edit
     * @description     : Load Update "Visitor" user interface
     *                    with populate "Visitor" value
     *                    and process to update "visitors" into database
     * @param           : $id integer value
     * @return          : null
     * ********************************************************** */
    public function edit($id = null) {

        check_permission(EDIT);
        if ($_POST) {
            $this->_prepare_visitor_validation();
            if ($this->form_validation->run() === TRUE) {
                $data = $this->_get_posted_visitor_data();
                $updated = $this->visitor->update('visitors', $data, array('id' => $this->input->post('id')));
                if ($updated) {
                    create_log('Has been updated a Visitor : ' . $data['name']);
                    success($this->lang->line('update_success'));
                    redirect('frontoffice/visitor');
                } else {
                    error($this->lang->line('update_failed'));
                    redirect('frontoffice/visitor/edit/' . $this->input->post('id'));
                }
            } else {
                $this->data['visitor'] = $this->visitor->get_single('visitors', array('id' => $this->input->post('id')));
            }
        } else {
            if ($id) {
                $this->data['visitor'] = $this->visitor->get_single('visitors', array('id' => $id));
                if (!$this->data['visitor']) {
                    redirect('frontoffice/visitor');
                }
            }
        }
        $this->data['visitor_purposes'] = $this->visitor->get_list('visitor_purposes', array('status' => 1), '', '', '', 'sort_by', 'ASC');
      	$this->data['unions'] = $this->visitor->get_list('unions', array('status' => 1), '', '', '', 'sort_by', 'ASC');
        $this->data['villages'] = $this->visitor->get_list('villages', array('status' => 1), '', '', '', 'sort_by', 'ASC');
        $this->data['edit'] = TRUE;
        $this->layout->title($this->lang->line('edit') . ' ' . $this->lang->line('visitor') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('visitor/edit', $this->data);
    }

    /*****************Function _prepare_visitor_validation**********************************
     * @type            : Function
     * @function name   : _prepare_visitor_validation
     * @description     : Process "Visitor" user input data validation
     *
     * @param           : null
     * @return          : null
     * ********************************************************** */
    private function _prepare_visitor_validation() {
        $this->load->library('form_validation');
        $this->form_validation->set_error_delimiters('<div class="error-message" style="color: red;">', '</div>');
        $this->form_validation->set_rules('phone', $this->lang->line('phone'), 'trim|required');
        $this->form_validation->set_rules('date', $this->lang->line('date'), 'trim|required');
    }

    /*****************Function _get_posted_visitor_data**********************************
     * @type            : Function
     * @function name   : _get_posted_visitor_data
     * @description     : Prepare "Visitor" user input data to save into database
     *
     * @param           : null
     * @return          : $data array(); value
     * ********************************************************** */
    private function _get_posted_visitor_data() {

        $items = array();
        $items[] = 'purpose_id';
        $items[] = 'union_id';
        $items[] = 'village_id';
        $items[] = 'profession';
        $items[] = 'name';
        $items[] = 'name_info';
        $items[] = 'family_member';
        $items[] = 'p_number';
        $items[] = 'phone';
      	$items[] = 'yes_no1';
      	$items[] = 'comment1';
      	$items[] = 'yes_no2';
      	$items[] = 'comment2';
      	$items[] = 'yes_no3';
      	$items[] = 'yes_no4';
      	$items[] = 'comment4';
      	$items[] = 'yes_no5';
      	$items[] = 'yes_no6';
      	$items[] = 'comment6';
      	$items[] = 'yes_no7';
      	$items[] = 'comment7';
      	$items[] = 'yes_no8';
      	$items[] = 'yes_no9';
        $items[] = 'p_name';
        $items[] = 'p_type';
        $items[] = 'p_department';
        $items[] = 'p_mobile';
        $items[] = 'p_serial';
        $items[] = 'note';
        $data = elements($items, $_POST);

        $data['date_fo'] = $this->input->post('date_fo') ? date('Y-m-d', strtotime($this->input->post('date_fo'))) : date('Y-m-d');
        $data['date'] = $this->input->post('date') ? date('Y-m-d', strtotime($this->input->post('date'))) : date('Y-m-d');

        if ($this->input->post('id')) {
            $data['modified_at'] = date('Y-m-d H:i:s');
            $data['modified_by'] = logged_in_user_id();
        } else {
            $data['status'] = 1;
            $data['created_at'] = date('Y-m-d H:i:s');
            $data['created_by'] = logged_in_user_id();
        }

        if ($_FILES['attachment']['name']) {
            $data['attachment'] = $this->_upload_attachment();
        }

        return $data;
    }

    /*     * ***************Function _upload_attachment**********************************
     * @type            : Function
     * @function name   : _upload_attachment
     * @description     : Process to upload visitor attachment into server
     *                     and return attachment file name
     * @param           : null
     * @return          : $return_attachment string value
     * ********************************************************** */

    private function _upload_attachment() {

        $prev_attachment = $this->input->post('prev_attachment');
        $attachment = $_FILES['attachment']['name'];
        $attachment_type = $_FILES['attachment']['type'];
        $return_attachment = '';

        if ($attachment != "") {
            if (
                $attachment_type == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ||
                $attachment_type == 'application/msword' || $attachment_type == 'text/plain' ||
                $attachment_type == 'application/vnd.ms-office' || $attachment_type == 'application/pdf' ||
                $attachment_type == 'image/jpeg' || $attachment_type == 'image/pjpeg' ||
                $attachment_type == 'image/jpg' || $attachment_type == 'image/png' ||
                $attachment_type == 'image/x-png' || $attachment_type == 'image/gif'
            ) {

                $destination = 'assets/uploads/attachment/';

                $file_type = explode(".", $attachment);
                $extension = strtolower($file_type[count($file_type) - 1]);
                $attachment_path = 'attachment-' . time() . '-sbiz.' . $extension;

                move_uploaded_file($_FILES['attachment']['tmp_name'], $destination . $attachment_path);

                // need to unlink previous photo
                if ($prev_attachment != "") {
                    if (file_exists($destination . $prev_attachment)) {
                        @unlink($destination . $prev_attachment);
                    }
                }

                $return_attachment = $attachment_path;
            }
        } else {
            $return_attachment = $prev_attachment;
        }

        return $return_attachment;
    }

    /*****************Function delete**********************************
     * @type            : Function
     * @function name   : delete
     * @description     : delete "Visitor" data from database
     *
     * @param           : $id integer value
     * @return          : null
     * ********************************************************** */
    public function delete($id = null) {

        check_permission(DELETE);

        if (!is_numeric($id)) {
            error($this->lang->line('unexpected_error'));
            redirect('frontoffice/visitor');
        }

        $visitor = $this->visitor->get_single('visitors', array('id' => $id));

        if ($this->visitor->delete('visitors', array('id' => $id))) {
            // delete attachment
            $destination = 'assets/uploads/';
            if (file_exists($destination . '/attachment/' . $visitor->attachment)) {
                @unlink($destination . '/attachment/' . $visitor->attachment);
            }
            create_log('Has been deleted a Visitor : ' . $visitor->name);
            success($this->lang->line('delete_success'));
        } else {
            error($this->lang->line('delete_failed'));
        }
        redirect('frontoffice/visitor');
    }
}
