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

/* ----------------------------------------------------------------------------
 * Easy!Appointments - Open Source Web Scheduler
 *
 * @package     EasyAppointments
 * @author      A.Tselegidis <alextselegidis@gmail.com>
 * @copyright   Copyright (c) 2013 - 2020, Alex Tselegidis
 * @license     https://opensource.org/licenses/GPL-3.0 - GPLv3
 * @link        https://easyappointments.org
 * @since       v1.0.0
 * ---------------------------------------------------------------------------- */

/**
 * Backend Controller
 *
 * @property CI_Session $session
 *
 * @package Controllers
 */
class Backend extends EA_Controller {
    /**
     * Class Constructor
     */
    public function __construct()
    {
        parent::__construct();

        $this->load->model('appointments_model');
        $this->load->model('providers_model');
        $this->load->model('services_model');
		$this->load->model('locations_model');
        $this->load->model('customers_model');
        $this->load->model('settings_model');
        $this->load->model('roles_model');
        $this->load->model('user_model');
        $this->load->model('secretaries_model');
        $this->load->model('admins_model');
		$this->load->model('reports_model');
		$this->load->model('files_model');
        $this->load->library('timezones');
        $this->load->library('migration');
		$this->load->library("pagination");
    }

    /**
     * Display the main backend page.
     *
     * This method displays the main backend page. All users login permission can view this page which displays a
     * calendar with the events of the selected provider or service. If a user has more privileges he will see more
     * menus at the top of the page.
     *
     * @param string $appointment_hash Appointment edit dialog will appear when the page loads (default '').
     *
     * @throws Exception
     */
    public function index($appointment_hash = '')
    {
        $this->session->set_userdata('dest_url', site_url('backend/index' . (! empty($appointment_hash) ? '/' . $appointment_hash : '')));

        if ( ! $this->has_privileges(PRIV_APPOINTMENTS))
        {
            return;
        }

        $calendar_view_query_param = $this->input->get('view');

        $user_id = $this->session->userdata('user_id');

        $user = $this->user_model->get_user($user_id);

        $view['base_url'] = config('base_url');
        $view['page_title'] = lang('calendar');
        $view['user_display_name'] = $this->user_model->get_user_display_name($this->session->userdata('user_id'));
        $view['active_menu'] = PRIV_APPOINTMENTS;
        $view['date_format'] = $this->settings_model->get_setting('date_format');
        $view['time_format'] = $this->settings_model->get_setting('time_format');
        $view['first_weekday'] = $this->settings_model->get_setting('first_weekday');
        $view['company_name'] = $this->settings_model->get_setting('company_name');
        $view['require_phone_number'] = $this->settings_model->get_setting('require_phone_number');
        $view['available_providers'] = $this->providers_model->get_available_providers();
        $view['customers'] = $this->customers_model->get_batch(array('parent_id' => '0'));
        $view['calendar_view'] = ! empty($calendar_view_query_param) ? $calendar_view_query_param : $user['settings']['calendar_view'];
        $view['timezones'] = $this->timezones->to_array();
        $this->set_user_data($view);
		
		/// To get all available service along with their location ///
        //$view['available_services'] = $this->services_model->get_available_services();
		$services = $this->services_model->get_available_services();
		$i = 0;
		foreach($services as $service) {
			$available_services[$i] = $service;
			$location = $this->locations_model->get_row($service['location']);
			$allservicesbylocation[$location['location_name']][] = $service;
			$i++;			
		}	
		
		if (is_array($allservicesbylocation)) {
            ksort($allservicesbylocation);
        }
		
		$i=0;
		foreach($allservicesbylocation as $key => $val) {
			foreach($val as $res) {
				$available_services[$i] = $res;
				$available_services[$i]['location_name'] = $key;
				$i++;
			}	
		}	
		$view['available_services'] = $available_services;		
		/// To get all available service along with their location - Ends here ///		

        if ($this->session->userdata('role_slug') === DB_SLUG_SECRETARY)
        {
            $secretary = $this->secretaries_model->get_row($this->session->userdata('user_id'));
            $view['secretary_providers'] = $secretary['providers'];
        }
        else
        {
            $view['secretary_providers'] = [];
        }

        $results = $this->appointments_model->get_batch(['hash' => $appointment_hash]);

        if ($appointment_hash !== '' && count($results) > 0)
        {
            $appointment = $results[0];
            $appointment['customer'] = $this->customers_model->get_row($appointment['id_users_customer']);
            $view['edit_appointment'] = $appointment; // This will display the appointment edit dialog on page load.
        }
        else
        {
            $view['edit_appointment'] = NULL;
        }

        $this->load->view('backend/header', $view);
        $this->load->view('backend/calendar', $view);
        $this->load->view('backend/footer', $view);
    }

    /**
     * Check whether current user is logged in and has the required privileges to view a page.
     *
     * The backend page requires different privileges from the users to display pages. Not all pages are available to
     * all users. For example secretaries should not be able to edit the system users.
     *
     * @param string $page This argument must match the roles field names of each section (eg "appointments", "users"
     * ...).
     * @param bool $redirect If the user has not the required privileges (either not logged in or insufficient role
     * privileges) then the user will be redirected to another page. Set this argument to FALSE when using ajax (default
     * true).
     *
     * @return bool Returns whether the user has the required privileges to view the page or not. If the user is not
     * logged in then he will be prompted to log in. If he hasn't the required privileges then an info message will be
     * displayed.
     */
    protected function has_privileges($page, $redirect = TRUE)
    {
        // Check if user is logged in.
        $user_id = $this->session->userdata('user_id');

        if ($user_id == FALSE)
        {
            // User not logged in, display the login view.
            if ($redirect)
            {
                header('Location: ' . site_url('user/login'));
            }
            return FALSE;
        }

        // Check if the user has the required privileges for viewing the selected page.
        $role_slug = $this->session->userdata('role_slug');

        $role_privileges = $this->db->get_where('roles', ['slug' => $role_slug])->row_array();

        if ($role_privileges[$page] < PRIV_VIEW)
        {
            // User does not have the permission to view the page.
            if ($redirect)
            {
                header('Location: ' . site_url('user/no_privileges'));
            }
            return FALSE;
        }

        return TRUE;
    }

    /**
     * Set the user data in order to be available at the view and js code.
     *
     * @param array $view Contains the view data.
     */
    protected function set_user_data(&$view)
    {
        $view['user_id'] = $this->session->userdata('user_id');
        $view['user_email'] = $this->session->userdata('user_email');
        $view['timezone'] = $this->session->userdata('timezone');
        $view['role_slug'] = $this->session->userdata('role_slug');
        $view['privileges'] = $this->roles_model->get_privileges($this->session->userdata('role_slug'));
    }

    /**
     * Display the backend customers page.
     *
     * In this page the user can manage all the customer records of the system.
     */
    public function customers()
    {
        $this->session->set_userdata('dest_url', site_url('backend/customers'));

        if ( ! $this->has_privileges(PRIV_CUSTOMERS))
        {
            return;
        }

        $view['base_url'] = config('base_url');
        $view['page_title'] = lang('customers');
        $view['user_display_name'] = $this->user_model->get_user_display_name($this->session->userdata('user_id'));
        $view['active_menu'] = PRIV_CUSTOMERS;
        $view['company_name'] = $this->settings_model->get_setting('company_name');
        $view['date_format'] = $this->settings_model->get_setting('date_format');
        $view['time_format'] = $this->settings_model->get_setting('time_format');
        $view['first_weekday'] = $this->settings_model->get_setting('first_weekday');
        $view['require_phone_number'] = $this->settings_model->get_setting('require_phone_number');
        $view['customers'] = $this->customers_model->get_batch();
        $view['available_providers'] = $this->providers_model->get_available_providers();
        $view['available_services'] = $this->services_model->get_available_services();
        $view['timezones'] = $this->timezones->to_array();

        if ($this->session->userdata('role_slug') === DB_SLUG_SECRETARY)
        {
            $secretary = $this->secretaries_model->get_row($this->session->userdata('user_id'));
            $view['secretary_providers'] = $secretary['providers'];
        }
        else
        {
            $view['secretary_providers'] = [];
        }

        $this->set_user_data($view);

        $this->load->view('backend/header', $view);
        $this->load->view('backend/customers', $view);
        $this->load->view('backend/footer', $view);
    }

    /**
     * Displays the backend services page.
     *
     * Here the admin user will be able to organize and create the services that the user will be able to book
     * appointments in frontend.
     *
     * NOTICE: The services that each provider is able to service is managed from the backend services page.
     */
    public function services()
    {
        $this->session->set_userdata('dest_url', site_url('backend/services'));

        if ( ! $this->has_privileges(PRIV_SERVICES))
        {
            return;
        }

        $view['base_url'] = config('base_url');
        $view['page_title'] = lang('services');
        $view['user_display_name'] = $this->user_model->get_user_display_name($this->session->userdata('user_id'));
        $view['active_menu'] = PRIV_SERVICES;
        $view['company_name'] = $this->settings_model->get_setting('company_name');
        $view['date_format'] = $this->settings_model->get_setting('date_format');
        $view['time_format'] = $this->settings_model->get_setting('time_format');
        $view['first_weekday'] = $this->settings_model->get_setting('first_weekday');
        $view['services'] = $this->services_model->get_batch();
        $view['categories'] = $this->services_model->get_all_categories();
        $view['locations'] = $this->locations_model->get_batch();
        $view['timezones'] = $this->timezones->to_array();
        $this->set_user_data($view);

        $this->load->view('backend/header', $view);
        $this->load->view('backend/services', $view);
        $this->load->view('backend/footer', $view);
    }
	
    /**
     * Displays the backend locations page.
     *
     * Here the admin user will be able to organize and create the locations that the user will be able to book
     * appointments in frontend.
     *
     */
    public function locations()
    {
        $this->session->set_userdata('dest_url', site_url('backend/locations'));

        if ( ! $this->has_privileges(PRIV_SERVICES))
        {
            return;
        }

        $view['base_url'] = config('base_url');
        $view['page_title'] = lang('services');
        $view['user_display_name'] = $this->user_model->get_user_display_name($this->session->userdata('user_id'));
        $view['active_menu'] = PRIV_LOCATIONS;
        $view['company_name'] = $this->settings_model->get_setting('company_name');
        $view['date_format'] = $this->settings_model->get_setting('date_format');
        $view['time_format'] = $this->settings_model->get_setting('time_format');
        $view['first_weekday'] = $this->settings_model->get_setting('first_weekday');
        $view['services'] = $this->locations_model->get_batch();
        $view['categories'] = $this->services_model->get_all_categories();
        $view['timezones'] = $this->timezones->to_array();
        $this->set_user_data($view);

        $this->load->view('backend/header', $view);
        $this->load->view('backend/locations', $view);
        $this->load->view('backend/footer', $view);
    }
	
	

    /**
     * Display the backend users page.
     *
     * In this page the admin user will be able to manage the system users. By this, we mean the provider, secretary and
     * admin users. This is also the page where the admin defines which service can each provider provide.
     */
    public function users()
    {
        $this->session->set_userdata('dest_url', site_url('backend/users'));

        if ( ! $this->has_privileges(PRIV_USERS))
        {
            return;
        }

        $view['base_url'] = config('base_url');
        $view['page_title'] = lang('users');
        $view['user_display_name'] = $this->user_model->get_user_display_name($this->session->userdata('user_id'));
        $view['active_menu'] = PRIV_USERS;
        $view['company_name'] = $this->settings_model->get_setting('company_name');
        $view['date_format'] = $this->settings_model->get_setting('date_format');
        $view['time_format'] = $this->settings_model->get_setting('time_format');
        $view['first_weekday'] = $this->settings_model->get_setting('first_weekday');
        $view['admins'] = $this->admins_model->get_batch();
        $view['providers'] = $this->providers_model->get_batch();
        $view['secretaries'] = $this->secretaries_model->get_batch();
        //$view['services'] = $this->services_model->get_batch();
        $view['working_plan'] = $this->settings_model->get_setting('company_working_plan');
        $view['timezones'] = $this->timezones->to_array();
        $view['working_plan_exceptions'] = '{}';
		
		/// To get location data for service ///
		$servicesInitial = $this->services_model->get_batch();		
		$i=0;
		foreach($servicesInitial as $res) {
			$services[$i]  = $res;	
			$location_name = $this->locations_model->get_row($res['location']);
			$services[$i]['location_name'] = !empty($location_name) ? $location_name['location_name'] : "N/A";
			$i++;
		}			
        
		$view['services'] = $services;
		
        $this->set_user_data($view);

        $this->load->view('backend/header', $view);
        $this->load->view('backend/users', $view);
        $this->load->view('backend/footer', $view);
    }

    /**
     * Display the user/system settings.
     *
     * This page will display the user settings (name, password etc). If current user is an administrator, then he will
     * be able to make change to the current Easy!Appointment installation (core settings like company name, book
     * timeout etc).
     */
    public function settings()
    {
        $this->session->set_userdata('dest_url', site_url('backend/settings'));
        if ( ! $this->has_privileges(PRIV_SYSTEM_SETTINGS, FALSE)
            && ! $this->has_privileges(PRIV_USER_SETTINGS))
        {
            return;
        }

        $user_id = $this->session->userdata('user_id');

        $view['base_url'] = config('base_url');
        $view['page_title'] = lang('settings');
        $view['user_display_name'] = $this->user_model->get_user_display_name($user_id);
        $view['active_menu'] = PRIV_SYSTEM_SETTINGS;
        $view['company_name'] = $this->settings_model->get_setting('company_name');
        $view['date_format'] = $this->settings_model->get_setting('date_format');
        $view['first_weekday'] = $this->settings_model->get_setting('first_weekday');
        $view['time_format'] = $this->settings_model->get_setting('time_format');
        $view['role_slug'] = $this->session->userdata('role_slug');
        $view['system_settings'] = $this->settings_model->get_settings();
        $view['user_settings'] = $this->user_model->get_user($user_id);
        $view['timezones'] = $this->timezones->to_array();

        // book_advance_timeout preview
        $book_advance_timeout = $this->settings_model->get_setting('book_advance_timeout');
        $hours = floor($book_advance_timeout / 60);
        $minutes = $book_advance_timeout % 60;
        $view['book_advance_timeout_preview'] = sprintf('%02d:%02d', $hours, $minutes);

        $this->set_user_data($view);

        $this->load->view('backend/header', $view);
        $this->load->view('backend/settings', $view);
        $this->load->view('backend/footer', $view);
    }

    /**
     * This method will update the installation to the latest available version in the server.
     *
     * IMPORTANT: The code files must exist in the server, this method will not fetch any new files but will update
     * the database schema.
     *
     * This method can be used either by loading the page in the browser or by an ajax request. But it will answer with
     * JSON encoded data.
     */
    public function update()
    {
        try
        {
            if ( ! $this->has_privileges(PRIV_SYSTEM_SETTINGS, TRUE))
            {
                throw new Exception('You do not have the required privileges for this task!');
            }

            if ( ! $this->migration->current())
            {
                throw new Exception($this->migration->error_string());
            }

            $view = ['success' => TRUE];
        }
        catch (Exception $exception)
        {
            $view = ['success' => FALSE, 'exception' => $exception->getMessage()];
        }

        $this->load->view('general/update', $view);
    }
	
	
    /**
     * Display the appointments reports 
     *
     */
    public function reports()
    {
        error_reporting(0);
		$this->session->set_userdata('dest_url', site_url('backend/reports'));

        // Check if user is logged in.
        $user_id = $this->session->userdata('user_id');
        if ($user_id == FALSE)
        {
            // User not logged in, display the login view.
            header('Location: ' . site_url('user/login'));
            return FALSE;
        }
		
		/// login check Ends here ///		
        $view['base_url']      = config('base_url');
        $view['page_title']    = lang('reports');
        $view['user_display_name'] = $this->user_model->get_user_display_name($this->session->userdata('user_id'));
        $view['active_menu']   = PRIV_REPORTS;
        $view['company_name']  = $this->settings_model->get_setting('company_name');
        $view['date_format']   = $this->settings_model->get_setting('date_format');
        $view['time_format']   = $this->settings_model->get_setting('time_format');
        $view['first_weekday'] = $this->settings_model->get_setting('first_weekday');
        $view['admins']        = $this->admins_model->get_batch();
        //$view['providers']     = $this->providers_model->get_batch();
        $view['secretaries']   = $this->secretaries_model->get_batch();
        //$view['services']      = $this->services_model->get_batch();
        $view['working_plan']  = $this->settings_model->get_setting('company_working_plan');
        $view['timezones']     = $this->timezones->to_array();
        $view['working_plan_exceptions'] = '{}';
		
		//// Pagination ///////
		$filter_array['sid']          = !empty($this->input->get('sid')) ? $this->input->get('sid') : "";
		$filter_array['pid']          = !empty($this->input->get('pid')) ? $this->input->get('pid') : "";
		$filter_array['lid']          = !empty($this->input->get('lid')) ? $this->input->get('lid') : "";
		$filter_array['start_date']   = !empty($this->input->get('start_date')) ? $this->input->get('start_date') : "";
		$filter_array['end_date']     = !empty($this->input->get('end_date')) ? $this->input->get('end_date') : "";
		$filter_array['sort_type']    = !empty($this->input->get('sort_type')) ? $this->input->get('sort_type') : "";
		$filter_array['sort_order']   = !empty($this->input->get('sort_order')) ? $this->input->get('sort_order') : "";

		$config["base_url"]           = base_url() . "index.php/backend/reports";
		$config["total_rows"]         = $this->reports_model->get_appointments_count($filter_array);
		$config["per_page"]           = 20;
		$config["uri_segment"]        = 3;
		$total_pages                  = $config["total_rows"] / $config["per_page"];
		$config["num_links"]          = round($total_pages);
		$config['page_query_string']  = FALSE;	
		$config['reuse_query_string'] = TRUE;
		$offset                       = ($this->uri->segment(3))? $this->uri->segment(3) : 0;
		$page                         = ( $offset + $config["per_page"] ) / $config["per_page"];

		$config['full_tag_open']      = '<div class="reports_pagination">Displaying '.$page.' of '.$config["num_links"].'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
		$config['full_tag_close']     = '</div>';
		$config['next_link']          = 'Next >>>';
		$config['prev_link']          = '<<< Previous';

		$this->pagination->initialize($config);	
		
		$view["links"]          = $this->pagination->create_links();
		$view['total_rows']     = $config["total_rows"];
		$view['total_pages']    = $config["num_links"];
		$view['sort_type']      = !empty($this->input->get('sort_type')) ? $this->input->get('sort_type') : "";
		$view['sort_order']     = !empty($this->input->get('sort_order')) ? $this->input->get('sort_order') : "";
		$view['rev_sort_order'] = ($this->input->get('sort_order')=='asc') ? 'desc' : 'asc';
		$view['records_count']  = $config["total_rows"];
		
		if(!empty($this->input->get('sort_type'))) {
			$sortImg['sortimg_book_datetime']  = ($this->input->get('sort_type')=='book_datetime')  ? "<img src='".config('base_url')."/assets/img/".$this->input->get('sort_order').".png'>" : "";
			$sortImg['sortimg_start_datetime'] = ($this->input->get('sort_type')=='start_datetime') ? "<img src='".config('base_url')."/assets/img/".$this->input->get('sort_order').".png'>" : "";
			$sortImg['sortimg_end_datetime']   = ($this->input->get('sort_type')=='end_datetime')   ? "<img src='".config('base_url')."/assets/img/".$this->input->get('sort_order').".png'>" : "";
			$sortImg['sortimg_service_name']   = ($this->input->get('sort_type')=='service_name')   ? "<img src='".config('base_url')."/assets/img/".$this->input->get('sort_order').".png'>" : "";
			$sortImg['sortimg_doctor_name']    = ($this->input->get('sort_type')=='doctor_name')    ? "<img src='".config('base_url')."/assets/img/".$this->input->get('sort_order').".png'>" : "";
		}
		
		$view['sortImg'] = $sortImg;
		
		/// To get all location ///
		$locations = $this->locations_model->get_batch();
		$view['locations'] = $locations;
		
		/// get services based on location ///
		$view['services'] = "";
		if(!empty($this->input->get('lid'))) {
			$view['services'] = $this->services_model->get_batch(array('location' => $this->input->get('lid')));
		}

		/// get providers based on location and services ///
		$view['providers'] = "";
		if(!empty($this->input->get('lid')) && !empty($this->input->get('sid'))) {
			$view['providers'] = $this->providers_model->get_providers_service_location($this->input->get('lid'), $this->input->get('sid'));
		}
		

		/// To get appointments information ///
		$filter_array['offset']   = $offset;
		$filter_array['per_page'] = $config["per_page"];		
		$i=0;
		$appointmentsArray = $this->reports_model->get_appointments($filter_array);
		foreach($appointmentsArray as $appres) {
			$customerInfo = $this->reports_model->get_customerinfo($appres['id_users_customer']);	
			$appointmentsArray[$i]['customerInfo'] = ucfirst($customerInfo['first_name'])." ".ucfirst($customerInfo['last_name']);
			if( !empty ( $customerInfo['address'] ) ) {
				$appointmentsArray[$i]['customerInfo'] .= '<br>'.$customerInfo['address'];
			}	
			if( !empty ( $customerInfo['city'] ) ) {
				$appointmentsArray[$i]['customerInfo'] .= '<br>'.$customerInfo['city'];
			}	
			if( !empty ( $customerInfo['state'] ) ) {
				$appointmentsArray[$i]['customerInfo'] .= '<br>'.$customerInfo['state'];
			}	
			if( !empty ( $customerInfo['zip_code'] ) ) {
				$appointmentsArray[$i]['customerInfo'] .= '<br>'.$customerInfo['zip_code'];
			}	
			if( !empty ( $customerInfo['email'] ) ) {
				$appointmentsArray[$i]['customerInfo'] .= '<br>'.$customerInfo['email'];
			}	
			if( !empty ( $customerInfo['phone_number'] ) ) {
				$appointmentsArray[$i]['customerInfo'] .= '<br>'.$customerInfo['phone_number'];
			}	
			if( !empty ( $customerInfo['timezone'] ) ) {
				$appointmentsArray[$i]['customerInfo'] .= '<br>Timezone: '.$customerInfo['timezone'];
			}			
			$i++;
		}
		$view['appointments'] = $appointmentsArray;		
		///////////////////////////////////////////////////
        $this->set_user_data($view);

        $this->load->view('backend/header', $view);
        $this->load->view('backend/reports', $view);
        $this->load->view('backend/footer', $view);
    }
	
	
	
    /**
     * Export reports to CSV 
     *
     */
    public function exporttocsv()
    {
        error_reporting(0);
		$this->session->set_userdata('dest_url', site_url('backend/reports'));

        // Check if user is logged in.
        $user_id = $this->session->userdata('user_id');
        if ($user_id == FALSE)
        {
            // User not logged in, display the login view.
            header('Location: ' . site_url('user/login'));
            return FALSE;
        }
		
		/// login check Ends here ///		
        $view['base_url']      = config('base_url');
        $view['page_title']    = lang('reports');
        $view['user_display_name'] = $this->user_model->get_user_display_name($this->session->userdata('user_id'));
        $view['active_menu']   = PRIV_REPORTS;
        $view['company_name']  = $this->settings_model->get_setting('company_name');
        $view['date_format']   = $this->settings_model->get_setting('date_format');
        $view['time_format']   = $this->settings_model->get_setting('time_format');
        $view['first_weekday'] = $this->settings_model->get_setting('first_weekday');
        $view['admins']        = $this->admins_model->get_batch();
        $view['providers']     = $this->providers_model->get_batch();
        $view['secretaries']   = $this->secretaries_model->get_batch();
        $view['services']      = $this->services_model->get_batch();
        $view['working_plan']  = $this->settings_model->get_setting('company_working_plan');
        $view['timezones']     = $this->timezones->to_array();
        $view['working_plan_exceptions'] = '{}';
		
		//// Filter Parameters ///////
		$filter_array['sid']          = !empty($this->input->get('sid')) ? $this->input->get('sid') : "";
		$filter_array['pid']          = !empty($this->input->get('pid')) ? $this->input->get('pid') : "";
		$filter_array['lid']          = !empty($this->input->get('lid')) ? $this->input->get('lid') : "";
		$filter_array['start_date']   = !empty($this->input->get('start_date')) ? $this->input->get('start_date') : "";
		$filter_array['end_date']     = !empty($this->input->get('end_date')) ? $this->input->get('end_date') : "";
		$filter_array['sort_type']    = !empty($this->input->get('sort_type')) ? $this->input->get('sort_type') : "";
		$filter_array['sort_order']   = !empty($this->input->get('sort_order')) ? $this->input->get('sort_order') : "";
				
		/// To write into CSV file ///
	    $delimiter = ","; 
		$filename = "appointments_report_" . time() . ".csv"; 
		 
		// Create a file pointer 
		$f = fopen('php://memory', 'w'); 
		 
		// Set column headers 
		$fields = array(
						'Booking Date',
						'Start Date',
						'End Date',
						'Type',
						'Doctor Name',
						'Doctor Timezone',
						'Customer Name',
						'Customer Address',
						'Customer City',
						'Customer State',
						'Customer Zipcode',
						'Customer Email',
						'Customer Phone',
						'Customer Timezone'
					);
					
		fputcsv($f, $fields, $delimiter); 
				
		/// To get appointments information ///
		$appointmentsArray = $this->reports_model->get_appointments($filter_array);
		foreach($appointmentsArray as $appres) {
			$bookdate  = date_format( date_create( $appres['book_datetime'] ), "d M,Y H:i" );
			$startdate = date_format( date_create( $appres['start_datetime'] ), "d M,Y H:i" );
			$enddate   = date_format( date_create( $appres['end_datetime'] ), "d M,Y H:i" );
			$apptype   = ucfirst($appres['name']);
			$doctor    = ucfirst($appres['first_name'])." ".ucfirst($appres['last_name']);
			$doctortz  = $appres['timezone'];			
			
			$getcustomerInfo  = $this->reports_model->get_customerinfo($appres['id_users_customer']);	
			$customername     = ucfirst($getcustomerInfo['first_name'])." ".ucfirst($getcustomerInfo['last_name']);
			$customerAddress  = !empty($getcustomerInfo['address'])      ? $getcustomerInfo['address'] : "";			
			$customerCity     = !empty($getcustomerInfo['city'])         ? $getcustomerInfo['city'] : "";
			$customerState    = !empty($getcustomerInfo['state'])        ? $getcustomerInfo['state'] : "";
			$customerZipcode  = !empty($getcustomerInfo['zip_code'])     ? $getcustomerInfo['zip_code'] : "";
			$customerEmail    = !empty($getcustomerInfo['email'])        ? $getcustomerInfo['email'] : "";
			$customerPhone    = !empty($getcustomerInfo['phone_number']) ? $getcustomerInfo['phone_number'] : "";
			$customerTimezone = !empty($getcustomerInfo['timezone'])     ? $getcustomerInfo['timezone'] : "";	
			
			$rowData = array(
							$bookdate,
							$startdate,
							$enddate,
							$apptype,
							$doctor,
							$doctortz,
							$customername,
							$customerAddress,
							$customerCity,
							$customerState,
							$customerZipcode,
							$customerEmail,
							$customerPhone,
							$customerTimezone							
						);
						
			fputcsv($f, $rowData, $delimiter);	
			
		}

		// Move back to beginning of file 
		fseek($f, 0); 
		 
		// Set headers to download file rather than displayed 
		header('Content-Type: text/csv'); 
		header('Content-Disposition: attachment; filename="' . $filename . '";'); 
		 
		//output all remaining data on a file pointer 
		fpassthru($f);	
		
	}
	
    /**
     * Display the patient files.
     */
    public function patientfiles()
    {
        error_reporting(0);
		$patientId = $this->uri->segment(3);
		$this->session->set_userdata('dest_url', site_url('backend/customers'));

        // Check if user is logged in.
        $user_id = $this->session->userdata('user_id');
        if ($user_id == FALSE)
        {
            // User not logged in, display the login view.
            header('Location: ' . site_url('user/login'));
            return FALSE;
        }
		
		/// login check Ends here ///		
        $view['base_url']      = config('base_url');
        $view['page_title']    = 'Patient Files';
        $view['user_display_name'] = $this->user_model->get_user_display_name($this->session->userdata('user_id'));
        $view['active_menu']   = PRIV_CUSTOMERS;
        $view['company_name']  = $this->settings_model->get_setting('company_name');
        $view['date_format']   = $this->settings_model->get_setting('date_format');
        $view['time_format']   = $this->settings_model->get_setting('time_format');
        $view['first_weekday'] = $this->settings_model->get_setting('first_weekday');
        $view['admins']        = $this->admins_model->get_batch();
        $view['providers']     = $this->providers_model->get_batch();
        $view['secretaries']   = $this->secretaries_model->get_batch();
        $view['services']      = $this->services_model->get_batch();
        $view['working_plan']  = $this->settings_model->get_setting('company_working_plan');
        $view['timezones']     = $this->timezones->to_array();
        $view['working_plan_exceptions'] = '{}';
		
		$patientFiles = $this->files_model->get_patient_files($patientId);
		$customerName = $this->files_model->get_customerinfo($patientId);
		
		$view['files'] = $patientFiles;
		$view['customerName'] = $customerName;
		$view['patientId'] = $patientId;
		
	    $this->load->view('backend/header', $view);
        $this->load->view('backend/patient_files_list', $view);
        $this->load->view('backend/footer', $view);	
	}
	
    /**
     * Add patient files.
     */
    public function addfiles() {
		$fileDescription = str_replace("\n","<br>",$this->input->post('filedesc'));
		$patientId = $this->input->post('patientId');
		$config['upload_path']   = './uploads/';
        $config['allowed_types'] = 'gif|jpg|png|pdf|doc|docx';
		$config['file_name']     = time()."_".$_FILES["patientfile"]['name'];

        $this->load->library('upload', $config);

        if (!$this->upload->do_upload('patientfile')) {			
			$this->session->set_flashdata('successMsg', '<font color=red>'.$this->upload->display_errors().'</font>');
        } else {
			$upload_data = $this->upload->data(); //Returns array of containing all of the data related to the file you uploaded.
			$file_name   = $upload_data['file_name'];
			$uniqueId    = substr(str_shuffle('abcdefghijklmnopqrstuvwxyz0123456789') , 0 , 16 );
			$fileArray   = array('unique_id' => $uniqueId,'file_name' => $file_name, 'file_description' => $fileDescription, 'patient_id' => $patientId, 'status' => '1');
			$this->files_model->insert($fileArray);
            $this->session->set_flashdata('successMsg', '<font color=green>File added successfully.</font>');
        }
		redirect('/backend/patientfiles/'.$patientId, 'refresh');		 
	}

    /**
     * Files send notification
     */
    public function files_sendnotification() {
		$fileUniqueId     = $this->uri->segment(3);
		$patientFilesInfo = $this->files_model->get_patientfileinfo($fileUniqueId);
		$patientId        = $patientFilesInfo['patient_id'];
		$filesExpiryHours = $this->settings_model->get_setting('patient_file_expiry');
		
		$currentDate = date('Y-m-d H:i:s');
		$expiryDate  = date("Y-m-d H:i:s", strtotime('+'.$filesExpiryHours.' hours'));
		
		$fileArray   = array('file_id' => $patientFilesInfo['file_id'],'sent_date' => $currentDate, 'expiry_date' => $expiryDate);
		$this->files_model->update($fileArray);
		
		$this->session->set_flashdata('successMsg', '<font color=green>Notification Sent.</font><br>The file below is available for download now :<br>File Description:<br>'.str_replace("\n","<br>", $patientFilesInfo['file_description']).'<br>File Location :'.base_url().'index.php/backend/download_patientfiles/'.$fileUniqueId);
		redirect('/backend/patientfiles/'.$patientId, 'refresh');
	}

    /**
     * To delete expired patient files
     */
    public function cron_deletepatientfiles() {
		$patientFiles = $this->files_model->get_patient_files_withoutId();
		$cnt = count($patientFiles);
		
		if($cnt > 0) {
			foreach($patientFiles as $res) {
				$fileArray = array('file_id' => $res['file_id'],'status' => '0');
				$this->files_model->update($fileArray);	
				@unlink('./uploads/'.$res['file_name']);	
			}	
		} else {
			echo "<h1>No Records Found.</h1>";
		}
	}
	
	
    /**
     * To download patient files
     */
    public function download_patientfiles() {
		$fileUniqueId     = $this->uri->segment(3);
		$patientFilesInfo = $this->files_model->get_patientfileinfo($fileUniqueId);
	
		$currentDate = date('Y-m-d H:i:s');
		
		if(!empty($patientFilesInfo['expiry_date']) && $currentDate > $patientFilesInfo['expiry_date']) {
			echo "<h1>Link Expired.</h1>";		
		} else {
			$this->load->helper('download');
			$filepath = './uploads/'.$patientFilesInfo['file_name'];
			$data = file_get_contents($filepath);
			force_download($patientFilesInfo['file_name'], $data);			
		}	
		
	}
	
}
