<?php

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

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

class Template extends MY_Controller {

    public $data = array();

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

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

        $search = $this->input->get('search');
        $test_id = $this->input->get('test_id');

        // Get tests list
        $this->data['tests'] = $this->template->get_list('diagnostic_tests', array('status' => 1), '', '', '', 'sort_by', 'ASC');

        $config = array();
        $config = get_pagination(ADMIN_PER_PAGE);
        if ($search || $test_id) {
            $config['base_url'] = site_url('diagnostic/template/?search=' . $search . '&test_id=' . $test_id);
        } 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->template->get_template_list($config['per_page'], $offset, $search, $test_id, $count = TRUE);
        $this->pagination->initialize($config);
        $this->data['templates'] = $this->template->get_template_list($config['per_page'], $offset, $search, $test_id, $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['test_id'] = $test_id;
        $this->data['list'] = TRUE;
        $this->layout->title($this->lang->line('diagnostic') . ' ' . $this->lang->line('template') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('template/index', $this->data);
    }

    /*****************Function add**********************************
     * @type            : Function
     * @function name   : add
     * @description     : Load "Add new Template" user interface
     *                    and process to store "templates" into database
     * @param           : null
     * @return          : null
     * ********************************************************** */
    public function add() {
        check_permission(ADD);
        
        if ($_POST) {
            $this->_prepare_template_validation();
            if ($this->form_validation->run() === TRUE) {
                $data = $this->_get_posted_template_data();
                
                $insert_id = $this->template->insert('diagnostic_tests_template', $data);
                
                if ($insert_id) {
                    create_log('Has been created a Template : ' . $data['investigation']);
                    success($this->lang->line('insert_success'));
                    redirect('diagnostic/template');
                } else {
                    error($this->lang->line('insert_failed'));
                    redirect('diagnostic/template/add');
                }
            } else {
                $this->data = $_POST;
            }
        }
        
        $this->data['departments'] = $this->template->get_list('diagnostic_departments', array('status' => 1), '', '', '', 'sort_by', 'ASC');
        $this->data['units'] = $this->template->get_unit_list();
        $this->data['add'] = TRUE;
        $this->layout->title($this->lang->line('add') . ' ' . $this->lang->line('template') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('template/add', $this->data);
    }

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

        // Debug logging
        if ($_POST) {
            log_message('debug', 'POST Data: ' . json_encode($_POST));
        }

        // Initialize template data
        $this->data['template'] = null;

        if ($_POST) {
            $this->_prepare_template_validation();
            if ($this->form_validation->run() === TRUE) {
                $data = $this->_get_posted_template_data();
                $template_id = $this->input->post('id');
                
                // Add modified information
                $data['modified_at'] = date('Y-m-d H:i:s');
                $data['modified_by'] = logged_in_user_id();
                
                // Update using model's update method
                $where = array('id' => $template_id);
                $updated = $this->template->update('diagnostic_tests_template', $data, $where);
                
                if ($updated) {
                    create_log('Has been updated a Template : ' . $data['investigation']);
                    success($this->lang->line('update_success'));
                    redirect('diagnostic/template');
                } else {
                    error($this->lang->line('update_failed'));
                    redirect('diagnostic/template/edit/' . $template_id);
                }
            } else {
                // Log validation errors
                log_message('debug', 'Form Validation Errors: ' . validation_errors());
                $template_id = $this->input->post('id');
                if ($template_id) {
                    $this->data['template'] = $this->template->get_single('diagnostic_tests_template', array('id' => $template_id));
                }
            }
        } else {
            if ($id) {
                $this->data['template'] = $this->template->get_single('diagnostic_tests_template', array('id' => $id));
                if (!$this->data['template']) {
                    error($this->lang->line('unexpected_error'));
                    redirect('diagnostic/template');
                }
            }
        }

        // Get departments list
        $this->data['departments'] = $this->template->get_list('diagnostic_departments', array('status' => 1), '', '', '', 'sort_by', 'ASC');
        
        // Get groups list
        $this->data['groups'] = $this->template->get_list('diagnostic_groups', array('status' => 1), '', '', '', 'sort_by', 'ASC');
        
        // Get units list
        $this->data['units'] = $this->template->get_unit_list();
        
        // Get tests list based on department_id if template exists
        if (isset($this->data['template']) && !empty($this->data['template'])) {
            $this->data['tests'] = $this->template->get_list('diagnostic_tests', 
                array('status' => 1, 'department_id' => $this->data['template']->department_id), 
                '', '', '', 'sort_by', 'ASC');
        } else {
            $this->data['tests'] = array();
        }

        $this->data['edit'] = TRUE;
        $this->layout->title($this->lang->line('edit') . ' ' . $this->lang->line('normal_value') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('template/edit', $this->data);
    }

    /*     * ***************Function get_single_template**********************************
     * @type            : Function
     * @function name   : get_single_template
     * @description     : "Load single template information" from database                  
     *                    to the user interface   
     * @param           : null
     * @return          : null 
     * ********************************************************** */

    public function get_single_template() {
        $id = $this->input->post('id');
        $this->data['template'] = $this->template->get_single_template($id);
        echo $this->load->view('diagnostic/template/view', $this->data);
    }

    /*****************Function _prepare_template_validation**********************************
     * @type            : Function
     * @function name   : _prepare_template_validation
     * @description     : Process "Template" user input data validation
     *
     * @param           : null
     * @return          : null
     * ********************************************************** */
    private function _prepare_template_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('department_id', $this->lang->line('department') . ' ' . $this->lang->line('investigation'), 'trim|required');
        $this->form_validation->set_rules('test_id', $this->lang->line('test') . ' ' . $this->lang->line('investigation'), 'trim|required');
        $this->form_validation->set_rules('investigation', $this->lang->line('investigation'), 'trim|required');
        $this->form_validation->set_rules('sort_by', $this->lang->line('sort_by'), 'trim|required|numeric');
        $this->form_validation->set_rules('normal_value', $this->lang->line('normal_value'), 'trim');
    }

    /*****************Function _get_posted_template_data**********************************
     * @type            : Function
     * @function name   : _get_posted_template_data
     * @description     : Prepare "Template" user input data to save into database
     *
     * @param           : null
     * @return          : $data array(); value
     * ********************************************************** */
    private function _get_posted_template_data() {
        $items = array();
        $items[] = 'department_id';
        $items[] = 'group_id';
        $items[] = 'test_id';
        $items[] = 'investigation';
        $items[] = 'sort_by';
        $items[] = 'normal_value';
        $items[] = 'status';
        $items[] = 'unit_id';

        $data = elements($items, $_POST);

        // Sanitize and validate each field
        foreach ($data as $key => &$value) {
            if ($value === '') {
                unset($data[$key]);
                continue;
            }
            
            switch ($key) {
                case 'department_id':
                case 'group_id':
                case 'test_id':
                case 'unit_id':
                case 'sort_by':
                    $value = (int)$value;
                    break;
                case 'investigation':
                    $value = strip_tags($value);
                    break;
                case 'normal_value':
                    // Allow specific HTML tags for rich text
                    $value = strip_tags($value, '<p><br><strong><em><ul><ol><li><table><tr><td><th>');
                    break;
                case 'status':
                    $value = (int)$value;
                    $value = ($value == 1) ? 1 : 0;
                    break;
            }
        }

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

        // Debug log the sanitized data
        log_message('debug', 'Sanitized Data: ' . json_encode($data));

        return $data;
    }

    /*     * ***************Function delete**********************************
     * @type            : Function
     * @function name   : delete
     * @description     : delete "Template" data from database
     *                     and unlink template photo and Resume from server
     * @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('diagnostic/template');
        }

        $template = $this->template->get_single('diagnostic_tests_template', array('id' => $id));
        if (!empty($template)) {
            $this->template->delete('diagnostic_tests_template', array('id' => $id));
            create_log('Has been deleted a Template : ' . $template->investigation);
            success($this->lang->line('delete_success'));
        } else {
            error($this->lang->line('delete_failed'));
        }
        redirect('diagnostic/template');
    }

    public function test_option() {
        check_permission(VIEW);

        if ($_POST) {
            $this->_prepare_test_option_validation();
            if ($this->form_validation->run() === TRUE) {
                $data = $this->_get_posted_test_option_data();
                
                $insert_id = $this->template->insert('diagnostic_tests_option', $data);
                
                if ($insert_id) {
                    create_log('Has been created a Test Option : ' . $data['option_name']);
                    success($this->lang->line('insert_success'));
                    redirect('diagnostic/template/test_option');
                } else {
                    error($this->lang->line('insert_failed'));
                    redirect('diagnostic/template/test_option');
                }
            } else {
                $this->data = $_POST;
            }
        }

        $this->data['tests'] = $this->template->get_list('diagnostic_tests', array('status' => 1));
        $this->data['templates'] = $this->template->get_list('diagnostic_tests_template', array('status' => 1));
        
        $this->data['add'] = TRUE;
        $this->layout->title($this->lang->line('add') . ' ' . $this->lang->line('test_option') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('template/test_option', $this->data);
    }

    private function _prepare_test_option_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('test_id', $this->lang->line('test'), 'trim|required');
        $this->form_validation->set_rules('template_id', $this->lang->line('template'), 'trim|required');
        $this->form_validation->set_rules('option_name', $this->lang->line('option_name'), 'trim|required');
    }

    private function _get_posted_test_option_data() {
        $items = array();
        $items[] = 'test_id';
        $items[] = 'template_id';
        $items[] = 'option_name';
        $items[] = 'status';

        $data = elements($items, $_POST);

        $data['created_at'] = date('Y-m-d H:i:s');
        $data['created_by'] = logged_in_user_id();

        return $data;
    }

    public function option() {
        check_permission(VIEW);

        $this->data['options'] = $this->template->get_option_list();
        $this->data['list'] = TRUE;
        $this->layout->title($this->lang->line('test_option') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('template/option/index', $this->data);
    }

    public function option_add() {
        check_permission(ADD);

        if ($_POST) {
            $this->_prepare_test_option_validation();
            if ($this->form_validation->run() === TRUE) {
                $data = $this->_get_posted_test_option_data();
                
                $insert_id = $this->template->insert('diagnostic_tests_option', $data);
                
                if ($insert_id) {
                    create_log('Has been created a Test Option : ' . $data['option_name']);
                    success($this->lang->line('insert_success'));
                    redirect('diagnostic/template/option');
                } else {
                    error($this->lang->line('insert_failed'));
                    redirect('diagnostic/template/option_add');
                }
            } else {
                $this->data = $_POST;
            }
        }

        $this->data['tests'] = $this->template->get_list('diagnostic_tests', array('status' => 1));
        $this->data['templates'] = $this->template->get_list('diagnostic_tests_template', array('status' => 1));
        
        $this->data['add'] = TRUE;
        $this->layout->title($this->lang->line('add') . ' ' . $this->lang->line('test_option') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('template/option/test_option', $this->data);
    }

    public function option_edit($id = null) {
        check_permission(EDIT);

        if ($_POST) {
            $this->_prepare_test_option_validation();
            if ($this->form_validation->run() === TRUE) {
                $data = $this->_get_posted_test_option_data();
                $data['modified_at'] = date('Y-m-d H:i:s');
                $data['modified_by'] = logged_in_user_id();
                
                if ($this->template->update('diagnostic_tests_option', $data, array('id' => $this->input->post('id')))) {
                    create_log('Has been updated a Test Option : ' . $data['option_name']);
                    success($this->lang->line('update_success'));
                    redirect('diagnostic/template/option');
                } else {
                    error($this->lang->line('update_failed'));
                    redirect('diagnostic/template/option_edit/' . $this->input->post('id'));
                }
            } else {
                $this->data = $_POST;
            }
        }

        if ($id) {
            $this->data['option'] = $this->template->get_single('diagnostic_tests_option', array('id' => $id));
            if (!$this->data['option']) {
                redirect('diagnostic/template/option');
            }
        }

        $this->data['tests'] = $this->template->get_list('diagnostic_tests', array('status' => 1));
        $this->data['templates'] = $this->template->get_list('diagnostic_tests_template', array('status' => 1));
        
        $this->data['edit'] = TRUE;
        $this->layout->title($this->lang->line('edit') . ' ' . $this->lang->line('test_option') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('template/option/test_option', $this->data);
    }

    public function option_delete($id = null) {
        check_permission(DELETE);
        
        if ($id) {
            $option = $this->template->get_single('diagnostic_tests_option', array('id' => $id));
            if ($option) {
                $this->template->delete('diagnostic_tests_option', array('id' => $id));
                create_log('Has been deleted a Test Option : ' . $option->option_name);
                success($this->lang->line('delete_success'));
            } else {
                error($this->lang->line('delete_failed'));
            }
        }
        redirect('diagnostic/template/option');
    }

    public function get_test_templates() {
        $test_id = $this->input->post('test_id');
        
        $templates = $this->template->get_list('diagnostic_tests_template', array('test_id' => $test_id, 'status' => 1));
        
        $str = '<option value="">' . $this->lang->line('select') . '</option>';
        if (!empty($templates)) {
            foreach ($templates as $obj) {
                $str .= '<option value="' . $obj->id . '">' . $obj->investigation . '</option>';
            }
        }
        
        echo $str;
    }

    public function unit() {
        check_permission(VIEW);

        $this->data['units'] = $this->template->get_unit_list();
        $this->data['title'] = $this->lang->line('unit');
        $this->data['module_name'] = 'diagnostic';
        $this->data['page_name'] = 'template/unit/index';
        $this->data['page_title'] = $this->lang->line('unit');
        $this->layout->title($this->lang->line('unit') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('template/unit/index', $this->data);
    }

    public function unit_add() {
        check_permission(ADD);

        if ($_POST) {
            $this->_prepare_unit_validation();
            if ($this->form_validation->run() === TRUE) {
                $data = $this->_get_posted_unit_data();
                $insert_id = $this->template->insert('diagnostic_tests_unit', $data);
                if ($insert_id) {
                    success($this->lang->line('insert_success'));
                    redirect('diagnostic/template/unit');
                } else {
                    error($this->lang->line('insert_failed'));
                    redirect('diagnostic/template/unit_add');
                }
            }
        }

        $this->data['title'] = $this->lang->line('add') . ' ' . $this->lang->line('unit');
        $this->data['module_name'] = 'diagnostic';
        $this->data['page_name'] = 'template/unit/add';
        $this->data['page_title'] = $this->lang->line('add') . ' ' . $this->lang->line('unit');
        $this->layout->title($this->lang->line('add') . ' ' . $this->lang->line('unit') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('template/unit/add', $this->data);
    }

    private function _prepare_unit_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('unit_name', $this->lang->line('unit_name'), 'trim|required|callback_unit_name');
    }

    private function _get_posted_unit_data() {
        $items = array();
        $items['unit_name'] = $this->input->post('unit_name');
        $items['status'] = $this->input->post('status') ? 1 : 0;
        $items['created_at'] = date('Y-m-d H:i:s');
        $items['created_by'] = logged_in_user_id();
        return $items;
    }

    public function unit_name() {
        if ($this->input->post('id') == '') {
            $unit = $this->template->duplicate_check('unit_name', $this->input->post('unit_name'), 'diagnostic_tests_unit');
            if ($unit) {
                $this->form_validation->set_message('unit_name', $this->lang->line('already_exist'));
                return FALSE;
            } else {
                return TRUE;
            }
        } else if ($this->input->post('id') != '') {
            $unit = $this->template->duplicate_check('unit_name', $this->input->post('unit_name'), 'diagnostic_tests_unit', $this->input->post('id'));
            if ($unit) {
                $this->form_validation->set_message('unit_name', $this->lang->line('already_exist'));
                return FALSE;
            } else {
                return TRUE;
            }
        }
    }

    public function unit_edit($id = null) {
        if (!has_permission(EDIT, 'diagnostic', 'template')) {
            error($this->lang->line('permission_denied'));
            redirect('diagnostic/template/unit');
        }

        if ($_POST) {
            $this->_prepare_unit_validation();
            if ($this->form_validation->run() === TRUE) {
                $data = array(
                    'unit_name' => $this->input->post('unit_name'),
                    'status' => $this->input->post('status') ? 1 : 0,
                    'modified_at' => date('Y-m-d H:i:s'),
                    'modified_by' => logged_in_user_id()
                );

                // Debug information
                log_message('debug', 'Update Data: ' . json_encode($data));
                log_message('debug', 'Unit ID: ' . $this->input->post('id'));

                // Check if unit exists before update
                $existing_unit = $this->template->get_single_unit($this->input->post('id'));
                if (!$existing_unit) {
                    error($this->lang->line('update_failed') . ' - Unit not found');
                    redirect('diagnostic/template/unit');
                }

                $success = $this->template->update('diagnostic_tests_unit', $data, array('id' => $this->input->post('id')));
                
                // Get database error if update fails
                if (!$success) {
                    $db_error = $this->db->error();
                    log_message('error', 'Database Error: ' . json_encode($db_error));
                    log_message('error', 'Last Query: ' . $this->db->last_query());
                }

                if ($success) {
                    // Log successful update
                    log_message('debug', 'Unit updated successfully. ID: ' . $this->input->post('id'));
                    success($this->lang->line('update_success'));
                    redirect('diagnostic/template/unit');
                } else {
                    error($this->lang->line('update_failed'));
                    redirect('diagnostic/template/unit_edit/' . $this->input->post('id'));
                }
            } else {
                // Log validation errors
                log_message('debug', 'Validation Errors: ' . json_encode($this->form_validation->error_array()));
                $this->data['unit'] = $this->template->get_single_unit($this->input->post('id'));
            }
        } else if ($id) {
            $this->data['unit'] = $this->template->get_single_unit($id);
            if (!$this->data['unit']) {
                redirect('diagnostic/template/unit');
            }
        }

        if (!isset($this->data['unit'])) {
            redirect('diagnostic/template/unit');
        }

        $this->data['title'] = $this->global_setting->brand_title . ' | ' . $this->lang->line('edit') . ' ' . $this->lang->line('unit');
        $this->layout->view('template/unit/edit', $this->data);
    }

    public function unit_delete($id = null) {
        check_permission(DELETE);
        
        if ($id) {
            $success = $this->template->delete('diagnostic_tests_unit', array('id' => $id));
            if ($success) {
                success($this->lang->line('delete_success'));
            } else {
                error($this->lang->line('delete_failed'));
            }
        }
        redirect('diagnostic/template/unit');
    }
}
