<?php

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

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

class Web extends CI_Controller {

    public $data = array();
    public $global_setting = array();
    public $sections = array();

    function __construct() {
        parent::__construct();
        $this->load->model('Web_Model', 'web', true);
        $this->global_setting = $this->db->get_where('global_setting', array('status' => 1))->row();
        $this->sections = $this->db->get_where('sections', array('status' => 1))->row();
        //print_r($this->global_setting);
        $this->data['main_menus'] = $this->web->get_main_menu_list();
        $this->data['footer_menu_title1'] = $this->web->get_single('menus', array('location' => 'footer_menu_1'));
        $this->data['footer_menu_title2'] = $this->web->get_single('menus', array('location' => 'footer_menu_2'));
        $this->data['footer_menus'] = $this->web->get_footer_menu_list();
        $this->data['meta'] = $this->web->get_page_list($this->uri->segment(2, 0));
        
         if ($this->global_setting) {
            date_default_timezone_set($this->global_setting->time_zone);
        }
    }

    public function index() {
        $this->data['sliders'] = $this->web->get_list('sliders', array('type' => 'frontend', 'is_view_on_web' => 1), '', '', '', 'sort_by', 'ASC');
        $this->data['services'] = $this->web->get_list('services', array('is_view_on_web' => 1, 'is_view_on_home' => 1, 'status' => 1, 'type' => 'service'), '', '9', '', 'sort_by', 'ASC');
        $this->data['why_choose_us'] = $this->web->get_list('services', array('is_view_on_web' => 1, 'status' => 1, 'type' => 'why_choose_us'), '', '6', '', 'sort_by', 'ASC');
        $this->data['departments'] = $this->web->get_list('departments', array('is_view_on_web' => 1, 'status' => 1, 'type' => 'doctor'), '', '9', '', 'sort_by', 'ASC');
        $this->data['app_departments'] = $this->web->get_list('departments', array('is_view_on_web' => 1, 'status' => 1, 'type' => 'doctor'), '', '', '', 'sort_by', 'ASC');
        $this->data['app_doctors'] = $this->web->get_list('employees', array('is_view_on_web' => 1, 'status' => 1, 'commission_type' => 'mbbs'), '', '', '', 'sort_by', 'ASC');
        $this->data['doctors'] = $this->web->get_list('employees', array('is_view_on_web' => 1, 'is_view_on_home' => 1, 'status' => 1, 'commission_type' => 'mbbs'), '', '8', '', 'sort_by', 'ASC');
        $this->data['testimonials'] = $this->web->get_list('testimonials', array('is_view_on_web' => 1), '', '9', '', 'id', 'DESC');
        $this->data['photos'] = $this->web->get_list('photos', array('is_view_on_web' => 1), '', '12', '', 'id', 'DESC');
        $this->data['news'] = $this->web->get_list('news', array('is_view_on_web' => 1), '', '3', '', 'id', 'DESC');
        $this->layout->title($this->lang->line('home') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('index', $this->data);
    }

    public function page($id) {
        $this->data['page'] = $this->web->get_page_list($id);

        $this->layout->title($this->data['page']->title . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('page', $this->data);
    }

    public function appointment_doctor() {
        $department_id = $this->input->post('department_id');
        $doctors = $this->web->get_mbbs_doctor_list($department_id);

        $str = '<option value="0">' . $this->lang->line('select') . ' ' . $this->lang->line('doctor') . '</option>';
        $select = 'selected="selected"';
        if (!empty($doctors)) {
            foreach ($doctors as $obj) {
                $selected = isset($doctor_id) == $obj->user_id ? $select : '';
                $str .= '<option value="' . $obj->user_id . '" ' . $selected . '>' . $obj->name . '</option>';
            }
        }
        echo $str;
    }

    public function search_patient($patient_unique_id) {
        $search = $this->web->get_single('patients', array('patient_unique_id' => $patient_unique_id));
        echo json_encode($search);
    }

    public function appointment($department_id = null, $doctor_id = null) {

        if ($_POST) {
            $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'), 'trim');
            $this->form_validation->set_rules('doctor_id', $this->lang->line('doctor'), 'trim|required');
            $this->form_validation->set_rules('name', $this->lang->line('name'), 'trim|required');
            $this->form_validation->set_rules('gender', $this->lang->line('gender'), 'trim|required');
            $this->form_validation->set_rules('phone', $this->lang->line('phone'), 'trim|required');
            $this->form_validation->set_rules('address', $this->lang->line('address'), 'trim|required');

            if ($this->form_validation->run() === TRUE) {
                $data['patient_id'] = $this->input->post('user_id') ?? null;
                $data['doctor_id'] = $this->input->post('doctor_id');
                $data['serial_no'] = get_custom_serial_number('appointments', $this->input->post('doctor_id'), date('Y-m-d', strtotime($this->input->post('date'))));
                $data['appointment_no'] = get_custom_appointment_number($data['serial_no']);
                $data['date'] = $this->input->post('date') ? date('Y-m-d', strtotime($this->input->post('date'))) : NULL;
                $data['name'] = $this->input->post('name');
                $data['phone'] = $this->input->post('phone');
                $data['gender'] = $this->input->post('gender');
                $data['address'] = $this->input->post('address');
                $data['note'] = $this->input->post('note');
                $data['appointment_status'] = 1;
                $data['source'] = 1;
                $data['is_opd'] = 0;
                $data['is_ipd'] = 0;
                $data['status'] = 1;
                $data['created_at'] = date('Y-m-d H:i:s');
                $data['created_by'] = null;

                $insert_id = $this->web->insert('appointments', $data);
                if ($insert_id) {
                    create_log('Has been created a appointment : ' . $data['name']);
                    success($this->lang->line('insert_success'));
                    redirect('appointment/success/' . $insert_id);
                } else {
                    error($this->lang->line('insert_failed'));
                    redirect('appointment');
                }
            } else {
                $this->data = $_POST;
            }
        }

        $this->data['department_id'] = $this->input->get('department_id');
        $this->data['doctor_id'] = $this->input->get('doctor_id');

        $this->data['departments'] = $this->web->get_list('departments', array('type' => 'doctor', 'status' => 1, 'is_view_on_web' => 1), '', '', '', 'sort_by', 'ASC');
        $this->data['doctors'] = $this->web->get_doctor_list();
        $this->layout->title($this->lang->line('appointment') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('appointment/index', $this->data);
    }

    public function appointment_success($id) {
        if ($id > 0) {
            $this->data['appointment'] = $this->web->get_single_appointment($id);
            $this->layout->title($this->lang->line('appointment') . ' | ' . $this->global_setting->brand_title);
            $this->layout->view('appointment/success', $this->data);
        } else {
            redirect('', 'refresh');
        }
    }

    public function appointment_print() {
        $id = $this->input->post('id');
        if ($id > 0) {
            $this->data['appointment'] = $this->web->get_single_appointment($id);
            $this->load->view('appointment/print', $this->data);
        } else {
            redirect('', 'refresh');
        }
    }

    public function appointment_pdf($id) {
        if ($id > 0) {
            $this->data['appointment'] = $this->web->get_single_appointment($id);
            $this->load->library('pdf');
            $mpdf = new \Mpdf\Mpdf([
                'mode' => 'utf-8',
                'orientation' => 'P'
            ]);
            $html =  $this->load->view('appointment/pdf', $this->data, true);
            $mpdf->WriteHTML($html);
            $mpdf->Output('appointment_' . rand() . '.pdf', 'D');
        } else {
            redirect('', 'refresh');
        }
    }

    public function doctors() {
        if ($_POST) {
            $this->data['doctors'] = $this->web->get_doctor_search($this->input->post('department_id'), $this->input->post('keyword'));
            $this->data['department_id'] = $this->input->post('department_id');
            $this->data['keyword'] = $this->input->post('keyword');
        }
        $this->data['departments'] = $this->web->get_list('departments', array('type' => 'doctor', 'status' => 1, 'is_view_on_web' => 1), '', '', '', 'sort_by', 'ASC');
        $this->layout->title($this->lang->line('doctor') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('doctor/index', $this->data);
    }

    public function doctor($id) {
        if ($id > 0) {
            $this->data['doctor'] = $this->web->get_single_doctor($id);
            $this->data['social'] = $this->web->get_single_social_info($id);
            $doctor = $this->session->userdata('site_lang') == 'bengali' ? $this->data['doctor']->bn_name : $this->data['doctor']->name;
            $this->layout->title($doctor . ' | ' . $this->global_setting->brand_title);
            $this->layout->view('doctor/single', $this->data);
        } else {
            redirect('', 'refresh');
        }
    }

    public function departments() {
        $this->data['departments'] = $this->web->get_list('departments', array('type' => 'doctor', 'status' => 1, 'is_view_on_web' => 1), '', '', '', 'sort_by', 'ASC');
        $this->layout->title($this->lang->line('department') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('department/index', $this->data);
    }

    public function department_doctor($id) {
        if ($id > 0) {
            $this->data['doctors'] = $this->web->get_department_doctor_list($id);
            $this->data['department'] = $this->web->get_single('departments', array('type' => 'doctor', 'status' => 1, 'is_view_on_web' => 1, 'id' => $id));
            $department = $this->session->userdata('site_lang') == 'bengali' ? $this->data['department']->bn_name : $this->data['department']->name;
            $this->layout->title($department . ' | ' . $this->global_setting->brand_title);
            $this->layout->view('department/doctor', $this->data);
        } else {
            redirect('', 'refresh');
        }
    }

    public function services() {
        $this->data['services'] = $this->web->get_list('services', array('status' => 1, 'is_view_on_web' => 1), '', '', '', 'sort_by', 'ASC');
        $this->layout->title($this->lang->line('our') . ' ' . $this->lang->line('service') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('service/index', $this->data);
    }

    public function service($id) {
        $this->data['services'] = $this->web->get_list('services', array('status' => 1, 'is_view_on_web' => 1), '', '', '', 'sort_by', 'ASC');
        $this->data['testimonials'] = $this->web->get_list('testimonials', array('is_view_on_web' => 1), '', '3', '', 'id', 'DESC');
        $this->data['service'] = $this->web->get_single('services', array('id' => $id));
        $service = $this->session->userdata('site_lang') == 'bengali' ? $this->data['service']->bn_title : $this->data['service']->title;
        $this->layout->title($service . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('service/single', $this->data);
    }

    public function news() {

        $config = array();
        $config = get_pagination(9);
        $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->web->get_news_list($config['per_page'], $offset, $count = TRUE);
        $this->pagination->initialize($config);
        $this->data['news'] = $this->web->get_news_list($config['per_page'], $offset, $count = FALSE);
        $this->data['sl_count'] = ($this->input->get('page') == 0 ? 1 : (($this->input->get('page') - 1) * $config["per_page"] + 1));

        $this->layout->title($this->lang->line('our') . ' ' . $this->lang->line('news') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('news/index', $this->data);
    }

    public function news_single($id) {
        $this->data['news'] = $this->web->get_list('news', array('status' => 1, 'is_view_on_web' => 1), '', '5', '', 'id', 'DESC');
        $this->data['news_single'] = $this->web->get_single('news', array('id' => $id));
        $this->layout->title($this->data['news_single']->title . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('news/single', $this->data);
    }

    public function photos() {
        $this->data['photos'] = $this->web->get_photo_gallery_list();
        $this->layout->title($this->lang->line('photo') . ' ' . $this->lang->line('gallery') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('gallery/photo', $this->data);
    }

    public function photo_gallery($id) {
        $this->data['gallery'] = $this->web->get_single('galleries', array('status' => 1, 'is_view_on_web' => 1, 'id' => $id));
        $this->data['photos'] = $this->web->get_single_photo_gallery_list($id);
        $this->layout->title($this->lang->line('photo') . ' ' . $this->lang->line('gallery') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('gallery/photo-gallery', $this->data);
    }

    public function videos() {
        $this->data['videos'] = $this->web->get_video_gallery_list();
        $this->layout->title($this->lang->line('video') . ' ' . $this->lang->line('gallery') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('gallery/video', $this->data);
    }

    public function video_gallery($id) {
        $this->data['gallery'] = $this->web->get_single('galleries', array('status' => 1, 'is_view_on_web' => 1, 'id' => $id));
        $this->data['videos'] = $this->web->get_single_video_gallery_list($id);
        $this->layout->title($this->lang->line('video') . ' ' . $this->lang->line('gallery') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('gallery/video-gallery', $this->data);
    }

    public function contact() {
        if ($_POST) {
            $this->load->library('form_validation');
            $this->form_validation->set_error_delimiters('<div class="error-message" style="color: red;">', '</div>');
            $this->form_validation->set_rules('name', $this->lang->line('name'), 'trim|required');
            $this->form_validation->set_rules('phone', $this->lang->line('phone'), 'trim|required');
            $this->form_validation->set_rules('email', $this->lang->line('email'), 'trim|required|valid_email');
            $this->form_validation->set_rules('subject', $this->lang->line('subject'), 'trim|required');
            $this->form_validation->set_rules('message', $this->lang->line('message'), 'trim|required');

            if ($this->form_validation->run() === TRUE) {
                $data['name'] = $this->input->post('name');
                $data['phone'] = $this->input->post('phone');
                $data['email'] = $this->input->post('email');
                $data['subject'] = $this->input->post('subject');
                $data['message'] = $this->input->post('message');
                $data['ip_address'] = $_SERVER['REMOTE_ADDR'];;
                $data['browser'] = $this->agent->is_browser() ? $this->agent->browser() . ' ' . $this->agent->version() : null;
                $data['platform'] = $this->agent->platform() ?? null;;
                $data['device'] = $this->agent->is_mobile() ? $this->agent->mobile() : null;
                $data['robot'] = $this->agent->is_robot() ? $this->agent->robot() : null;
                $data['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
                $data['status'] = 1;
                $data['created_at'] = date('Y-m-d H:i:s');
                $data['created_by'] = null;

                $insert_id = $this->web->insert('contacts', $data);
                if ($insert_id) {
                    $this->_send_email();
                    create_log('Has been created a contact us form : ' . $data['name']);
                    success($this->lang->line('email_send_success'));
                    redirect($_SERVER['HTTP_REFERER']);
                } else {
                    error($this->lang->line('email_send_failed'));
                    redirect('contact');
                }
            } else {
                $this->data = $_POST;
            }
        }

        $this->layout->title($this->lang->line('contact') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('contact', $this->data);
    }

    /*     * ***************Function _send_email**********************************
     * @type            : Function
     * @function name   : _send_email
     * @description     : this function used to send email for contact us
     * @param           : $data array();
     * @return          : null
     * ********************************************************** */

    private function _send_email() {
        if ($this->input->post('email')) {
            $email_setting = $this->db->get_where('email_settings', array('status' => 1))->row();
            if (!empty($email_setting) && $email_setting->mail_protocol == 'smtp') {
                $config['protocol']     = 'smtp';
                $config['smtp_host']    = $email_setting->smtp_host;
                $config['smtp_port']    = $email_setting->smtp_port;
                $config['smtp_timeout'] = $email_setting->smtp_timeout ? $email_setting->smtp_timeout  : 5;
                $config['smtp_user']    = $email_setting->smtp_user;
                $config['smtp_pass']    = $email_setting->smtp_pass;
                $config['smtp_crypto']  = $email_setting->smtp_crypto ? $email_setting->smtp_crypto  : 'tls';
                $config['mailtype'] = $email_setting->mail_type ? $email_setting->mail_type  : 'html';
                $config['charset']  = $email_setting->char_set ? $email_setting->char_set  : 'iso-8859-1';
                $config['priority']  = $email_setting->priority ? $email_setting->priority  : '3';
            } elseif (!empty($email_setting) && $email_setting->mail_protocol != 'smtp') {
                $config['protocol'] = $email_setting->mail_protocol;
                $config['mailpath'] = '/usr/sbin/' . $email_setting->mail_protocol;
                $config['mailtype'] = $email_setting->mail_type ? $email_setting->mail_type  : 'html';
                $config['charset']  = $email_setting->char_set ? $email_setting->char_set  : 'iso-8859-1';
                $config['priority']  = $email_setting->priority ? $email_setting->priority  : '3';
            } else { // default
                $config['protocol'] = 'sendmail';
                $config['mailpath'] = '/usr/sbin/sendmail';
            }

            $config['wordwrap'] = TRUE;
            $config['newline']  = "\r\n";

            $this->load->library('email');
            $this->email->initialize($config);
            $from_email = $this->input->post('email');
            $from_name  = $this->input->post('name');
            $system_name = $this->db->get_where('global_setting', array('status' => 1))->row();

            if (!empty($email_setting)) {
                $to_email = $email_setting->from_address;
            } elseif (!empty($system_name)) {
                $to_email = $system_name->email;
            }

            $this->email->from($from_email, $from_name);
            $this->email->to($to_email);
            $subject = 'Contact email from support user ' . $system_name->brand_title;
            $this->email->subject($subject);

            $message = 'Hi ' .  $system_name->brand_title;
            $message .= '<br/><br/>';
            $message .= 'Contact mail from ' .  $system_name->brand_title . '<br/>';
            $message .= '<br/><br/>';
            $message .= 'Name : ' . $this->input->post('name');
            $message .= '<br/>';
            $message .= 'Phone : ' . $this->input->post('phone');
            $message .= '<br/>';
            $message .= 'Email : ' . $this->input->post('email');
            $message .= '<br/>';
            $message .= 'Subject : ' . $this->input->post('subject');
            $message .= '<br/>';
            $message .= 'Message: ' . $this->input->post('message');
            $message .= '<br/><br/>';
            $message .= 'Thank you<br/>';
            $message .= $this->input->post('name');

            $this->email->message($message);

            if (!empty($email_setting) && $email_setting->mail_protocol == 'smtp') {
                return $this->email->send();
            } else {
                $headers = "MIME-Version: 1.0\r\n";
                $headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
                $headers .= "From:  $from_name < $from_email >\r\n";
                $headers .= "Reply-To:  $from_name < $from_email >\r\n";
                return mail($to_email, $subject, $message, $headers);
            }
        }
    }
}
