<?php

namespace RxConnexionBundle\Controller;

use RxConnexionBundle\Entity\AuditTrailEntity;
use RxConnexionBundle\Entity\PatientTicketEntity;
use RxConnexionBundle\Entity\TicketEntity;
use RxConnexionBundle\Entity\TicketNoteEntity;
use RxConnexionBundle\Entity\PatientNoteEntity;
use RxConnexionBundle\Entity\TransferInventoryEntity;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;


/**
 * @Route("/main")
 */
class MainController extends Controller
{
    /**
     * @Route("", name="main")
     */
    public function indexAction()
    {
        $authService = $this->get('rx_connexion.authService');
        $userData = $this->get('session')->get('userData');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();

        return $this->render('@RxConnexion/Admin/index.html.twig', array(
            'title' => 'Home',
            'page_title' => 'Home',
            'javascripts' => array('rxconnexion/admin/js/admin/index.js?v=1.1.17'),
            'stylesheets' => array('rxconnexion/admin/css/admin/index.css?v=1.0.1'),
            'userData' => $userData
        ));
//        'rxconnexion/chart-js/chart.js/dist/Chart.bundle.min.js',
    }

    /**
     * @Route("/dashboard_count", name="main_dashboard_count")
     */
    public function dashboardCountAction(){

        $userData = $this->get('session')->get('userData');

        $dashboardData = $this->get('rx_connexion.dashboardService')->getDashboardData();

        if($userData['type'] === 'Clinician'){
            $json = array(
                'appointments' => $dashboardData['appointments'],
                'insurance_package' => $dashboardData['insurance_package'],
                'appointments_pending_update' => $dashboardData['appointments_pending_update'],
                'tickets' => $dashboardData['tickets'],
                'reminders' => $dashboardData['reminders'],
                'clinician_letters' => $dashboardData['clinician_letters'],
                'encounter_overdue' => $dashboardData['clinician_overdue'],
            );
        } else {
            $json = array(
                /*'with_fax_no_encounters'=> $withFaxNoEncounters,
                'new_faxes'=> $newFaxes,
                'init_encounters'=> $noEncounters,
                'for_rebookings'=> $forReBookings,
                'encounter_calls' => $encounterCalls,
                'appointment_notice' => $appointmentNotice,
                'seventy_two_hour_followups' => $for72hourFollowUps,
                'three_months_followups' => $for3MonthFollowUps,
                'six_months_followups' => $for6MonthFollowUps,*/

                'with_fax_no_encounters'=> in_array('Admin Dashboard Patient With Fax No Encounter', $userData['accesses']) || $userData['type'] == 'Super Admin' ? $dashboardData['withFaxNoEncounters'] : 0,
                'with_referral_no_encounters'=> in_array('Admin Dashboard Patient With Referral No Encounter', $userData['accesses']) || $userData['type'] == 'Super Admin' ? $dashboardData['withReferralNoEncounters'] : 0,
                'with_specialist_services'=> in_array('Admin Dashboard Referral With Specialist Service', $userData['accesses']) || $userData['type'] == 'Super Admin' ?  $dashboardData['withSpecialistServices'] : 0,
                'with_other_services'=> in_array('Admin Dashboard Referral With Other Service', $userData['accesses']) || $userData['type'] == 'Super Admin' ? $dashboardData['withOtherServices'] : 0,
                'new_faxes'=> in_array('Admin Dashboard New Fax', $userData['accesses']) || $userData['type'] == 'Super Admin' ? $dashboardData['newFaxes'] : 0,
                'new_unite_faxes'=> in_array('Admin Dashboard New Unite Fax', $userData['accesses']) || $userData['type'] == 'Super Admin' ? $dashboardData['newUniteFaxes'] : 0,
                'init_encounters'=> in_array('Admin Dashboard Patient Initial Encounter', $userData['accesses']) || $userData['type'] == 'Super Admin' ?  $dashboardData['patientNoCharts'] : 0,
                'for_rebookings'=> in_array('Admin Dashboard Patient For Rebooking', $userData['accesses']) || $userData['type'] == 'Super Admin' ?  $dashboardData['forRebookings'] : 0,
                'encounter_calls'=> in_array('Admin Dashboard Patient Encounter Call', $userData['accesses']) || $userData['type'] == 'Super Admin' ?  $dashboardData['encounterCalls'] : 0,
                'appointment_notice'=> in_array('Admin Dashboard Appointment Notice', $userData['accesses']) || $userData['type'] == 'Super Admin' ?  $dashboardData['appointmentNotice'] : 0,
                'seventy_two_hour_followups'=> in_array('Admin Dashboard Patient 72 Hours Follow Up', $userData['accesses']) || $userData['type'] == 'Super Admin' ?  $dashboardData['for72HoursFollowUp'] : 0,
                'three_months_followups'=> in_array('Admin Dashboard Patient 3 Month Follow Up', $userData['accesses']) || $userData['type'] == 'Super Admin' ?  $dashboardData['for3MonthsFollowUp'] : 0,
                'six_months_followups'=> in_array('Admin Dashboard Patient 6 Month Follow Up', $userData['accesses']) || $userData['type'] == 'Super Admin' ?  $dashboardData['for6MonthsFollowUp'] : 0,
                'pft'=> in_array('Admin Dashboard Patient Pft', $userData['accesses']) || $userData['type'] == 'Super Admin' ?  $dashboardData['forPft'] : 0,
                'my_taks' => in_array('Admin Dashboard My Task', $userData['accesses']) || $userData['type'] == 'Super Admin' ?  $dashboardData['myTask'] : 0,
                'endorsed' => in_array('Admin Dashboard Endorsed', $userData['accesses']) || $userData['type'] == 'Super Admin' ?  $dashboardData['endorsed'] : 0,
                'letters' => in_array('Admin Dashboard Letters', $userData['accesses']) || $userData['type'] == 'Super Admin' ?  $dashboardData['letters'] : 0,
                'accountsReceivable' => in_array('Admin Dashboard Accounts Receivable', $userData['accesses']) || $userData['type'] == 'Super Admin' ?  $dashboardData['accountsReceivable'] : 0,
                'reminder' => $dashboardData['reminder'],
                'appointment' => $dashboardData['appointments'],
                'ppo' => in_array('Admin Dashboard Pending Purchase Order', $userData['accesses']) || $userData['type'] == 'Super Admin' ?  $dashboardData['ppo'] : 0,
                'payables' => in_array('Admin Dashboard Payables', $userData['accesses']) || $userData['type'] == 'Super Admin' ?  $dashboardData['payables'] : 0,
            );
        }
        return new JsonResponse($json);
    }

    /**
     * @Route(
     *      "/patient/with_fax_no_encounter",
     *      name = "with_fax_no_encounter_preview"
     * )
     */
    public function with_fax_no_encounter_previewAction(Request $request) {
        $get = $request->query->all();
        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Dashboard Patient With Fax No Encounter'))) return $authService->redirectToHome();

        $yearNow = date('Y');
        $yearFilter = array();
        $i = 0;
        for ($y=$yearNow; $y > $yearNow-10; $y--) {
            $yearFilter[$i]['display'] = $y;
            $yearFilter[$i]['value'] = $y;
            $i++;
        }

        $makeDate = "2000-1-1";
        $monthStart = date("n", strtotime($makeDate));
        $monthFilter = array();
        $i = 0;
        for ($m=$monthStart; $m < $monthStart+12; $m++) {
            $month = date('F', mktime(0,0,0,$m, 1, date('Y')));
            $monthFilter[$i]['display'] = $month;
            $monthFilter[$i]['value'] = $m;
            $i++;
        }


        ini_set('memory_limit', '2048M');
        set_time_limit(0);

        $em = $this->getDoctrine()->getManager();
        $userData = $this->get('session')->get('userData');
        $patientWithFaxNoEncounters = $em->getRepository('RxConnexionBundle:FaxTranEntity')->dashboardWithFaxNoEncounters($get, $this->get('session')->get('userData'));
        $patientWithFaxNoEncountersSummaries = $em->getRepository('RxConnexionBundle:FaxTranEntity')->dashboardWithFaxNoEncountersSummary($get, $this->get('session')->get('userData'));
        $healthFacilities = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->branchesForMultiple($userData);

        $page_title = 'Fax without Encounter';
        return $this->render('@RxConnexion/Admin/Dashboard/with_fax_no_encounter.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'records' => $patientWithFaxNoEncounters,
            'yearFilter'  => $yearFilter,
            'monthFilter'  => $monthFilter,
            'healthFacilities' => $healthFacilities,
            'summaries' => $patientWithFaxNoEncountersSummaries,
            'branch' => isset($get['branch']) ? $get['branch'] : 'All',
            'getYear' => isset($get['year']) ? $get['year'] : 'All',
            'getMonth' => isset($get['month']) ? $get['month'] : 'All'
        ));
    }

    /**
     * @Route(
     *      "/patient/fax_no_encounter/export_to_excel",
     *      name = "patient_fax_no_encounter_export_to_excel"
     * )
     */
    public function dashboard_fax_no_encounter_exportToExcelAction(Request $request) {
        $get = $request->query->all();
        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Dashboard Fax No Encounter Excel'))) return $authService->redirectToHome();

        ini_set('memory_limit', '2048M');
        set_time_limit(0);

        $makeDate = "2000-1-1";
        $monthStart = date("n", strtotime($makeDate));
        $monthFilter = array();
        $i = 0;
        for ($m=$monthStart; $m < $monthStart+12; $m++) {
            $month = date('F', mktime(0,0,0,$m, 1, date('Y')));
            $monthFilter[$i]['display'] = $month;
            $monthFilter[$i]['value'] = $m;
            $i++;
        }

        $yearNow = date('Y');
        $yearFilter = array();
        $i = 0;
        for ($y=$yearNow; $y > $yearNow-10; $y--) {
            $yearFilter[$i]['display'] = $y;
            $yearFilter[$i]['value'] = $y;
            $i++;
        }

        $em = $this->getDoctrine()->getManager();
        $patientWithFaxNoEncounters = $em->getRepository('RxConnexionBundle:FaxTranEntity')->dashboardWithFaxNoEncounters($get, $this->get('session')->get('userData'));

        ini_set('memory_limit', '2048M');
        set_time_limit(0);

        $cellsData[] = array('cell' => 'A1', 'data' => 'Fax w/o Encounter Report');

        $columnRange = range('A', 'L');
        $cellsData = array(
            array('cell' => 'A1', 'data' => 'Referral Date'),
            array('cell' => 'B1', 'data' => 'Branch'),
            array('cell' => 'C1', 'data' => 'Full Name'),
            array('cell' => 'D1', 'data' => 'Latest Patient Notes'),
        );
        $rowCtr = 1;
        $totalCount = 0;

        foreach($patientWithFaxNoEncounters as $record) {

            $rowCtr++;
            $totalCount++;

            $cellsData[] = array('cell' => "A$rowCtr", 'data' => isset($record['referralDate']) ? $record['referralDate'] : '');
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => isset($record['healthFacility']) ? $record['healthFacility'] : '');
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => isset($record['fullName']) ? $record['fullName'] : '');
            $cellsData[] = array('cell' => "D$rowCtr", 'data' => isset($record['latestNotes']) ? strip_tags($record['fullName']) : '');
        }

        $rowCtr++;
        $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Total Records: ' . $totalCount);

        $page_title = 'Fax no Encounter Report';
        return $this->export_to_excel($columnRange, $cellsData, $page_title);
    }


    /**
     * @Route(
     *      "/patient/with_referral_no_encounter",
     *      name = "with_referral_no_encounter_preview"
     * )
     */
    public function with_referral_no_encounter_previewAction(Request $request) {
        $get = $request->query->all();
        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Dashboard Patient With Referral No Encounter'))) return $authService->redirectToHome();

        $yearNow = date('Y');
        $yearFilter = array();
        $i = 0;
        for ($y=$yearNow; $y > $yearNow-10; $y--) {
            $yearFilter[$i]['display'] = $y;
            $yearFilter[$i]['value'] = $y;
            $i++;
        }

        $makeDate = "2000-1-1";
        $monthStart = date("n", strtotime($makeDate));
        $monthFilter = array();
        $i = 0;
        for ($m=$monthStart; $m < $monthStart+12; $m++) {
            $month = date('F', mktime(0,0,0,$m, 1, date('Y')));
            $monthFilter[$i]['display'] = $month;
            $monthFilter[$i]['value'] = $m;
            $i++;
        }


        ini_set('memory_limit', '2048M');
        set_time_limit(0);

        $em = $this->getDoctrine()->getManager();
        $userData = $this->get('session')->get('userData');
        $patientWithFaxNoEncounters = $em->getRepository('RxConnexionBundle:FaxTranEntity')->dashboardWithReferralNoEncounters($get, $this->get('session')->get('userData'));
        $patientWithFaxNoEncountersSummaries = $em->getRepository('RxConnexionBundle:FaxTranEntity')->dashboardWithRefferalNoEncountersSummary($get, $this->get('session')->get('userData'));
        $healthFacilities = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->branchesForMultiple($userData);

        $page_title = 'Referral without Encounter';
        return $this->render('@RxConnexion/Admin/Dashboard/with_referral_no_encounter.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'records' => $patientWithFaxNoEncounters,
            'yearFilter'  => $yearFilter,
            'monthFilter'  => $monthFilter,
            'healthFacilities' => $healthFacilities,
            'summaries' => $patientWithFaxNoEncountersSummaries,
            'branch' => isset($get['branch']) ? $get['branch'] : 'All',
            'getYear' => isset($get['year']) ? $get['year'] : 'All',
            'getMonth' => isset($get['month']) ? $get['month'] : 'All'
        ));
    }

    /**
     * @Route(
     *      "/patient/referral_no_encounter/export_to_excel",
     *      name = "patient_referral_no_encounter_export_to_excel"
     * )
     */
    public function dashboard_referral_no_encounter_exportToExcelAction(Request $request) {
        $get = $request->query->all();
        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Dashboard Patient With Referral No Encounter Excel'))) return $authService->redirectToHome();

        ini_set('memory_limit', '2048M');
        set_time_limit(0);

        $makeDate = "2000-1-1";
        $monthStart = date("n", strtotime($makeDate));
        $monthFilter = array();
        $i = 0;
        for ($m=$monthStart; $m < $monthStart+12; $m++) {
            $month = date('F', mktime(0,0,0,$m, 1, date('Y')));
            $monthFilter[$i]['display'] = $month;
            $monthFilter[$i]['value'] = $m;
            $i++;
        }

        $yearNow = date('Y');
        $yearFilter = array();
        $i = 0;
        for ($y=$yearNow; $y > $yearNow-10; $y--) {
            $yearFilter[$i]['display'] = $y;
            $yearFilter[$i]['value'] = $y;
            $i++;
        }

        $em = $this->getDoctrine()->getManager();
        $patientWithFaxNoEncounters = $em->getRepository('RxConnexionBundle:FaxTranEntity')->dashboardWithReferralNoEncounters($get, $this->get('session')->get('userData'));

        ini_set('memory_limit', '2048M');
        set_time_limit(0);

        $cellsData[] = array('cell' => 'A1', 'data' => 'Referral w/o Encounter Report');

        $columnRange = range('A', 'L');
        $cellsData = array(
            array('cell' => 'A1', 'data' => 'Referral Date'),
            array('cell' => 'B1', 'data' => 'Branch'),
            array('cell' => 'C1', 'data' => 'Full Name'),
            array('cell' => 'D1', 'data' => 'Latest Patient Notes'),
        );
        $rowCtr = 1;
        $totalCount = 0;

        foreach($patientWithFaxNoEncounters as $record) {

            $rowCtr++;
            $totalCount++;

            $cellsData[] = array('cell' => "A$rowCtr", 'data' => isset($record['referralDate']) ? $record['referralDate'] : '');
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => isset($record['healthFacility']) ? $record['healthFacility'] : '');
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => isset($record['fullName']) ? $record['fullName'] : '');
            $cellsData[] = array('cell' => "D$rowCtr", 'data' => isset($record['latestNotes']) ? strip_tags($record['fullName']) : '');
        }

        $rowCtr++;
        $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Total Records: ' . $totalCount);

        $page_title = 'Referral no Encounter Report';
        return $this->export_to_excel($columnRange, $cellsData, $page_title);
    }

    /*Patients with specialist services*/

    /**
     * @Route(
     *      "/patient/referral_with_specialist_service",
     *      name = "referral_with_specialist_service_preview"
     * )
     */
    public function referral_with_specialist_service_previewAction(Request $request) {
        $get = $request->query->all();
        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Dashboard Referral With Specialist Service'))) return $authService->redirectToHome();

        $yearNow = date('Y');
        $yearFilter = array();
        $i = 0;
        for ($y=$yearNow; $y > $yearNow-10; $y--) {
            $yearFilter[$i]['display'] = $y;
            $yearFilter[$i]['value'] = $y;
            $i++;
        }

        $makeDate = "2000-1-1";
        $monthStart = date("n", strtotime($makeDate));
        $monthFilter = array();
        $i = 0;
        for ($m=$monthStart; $m < $monthStart+12; $m++) {
            $month = date('F', mktime(0,0,0,$m, 1, date('Y')));
            $monthFilter[$i]['display'] = $month;
            $monthFilter[$i]['value'] = $m;
            $i++;
        }

        ini_set('memory_limit', '2048M');
        set_time_limit(0);

        $em = $this->getDoctrine()->getManager();
        $userData = $this->get('session')->get('userData');
        $dashboardWithReferralWithSpecialistService = $em->getRepository('RxConnexionBundle:ReferralEntity')->dashboardWithReferralWithSpecialistService($get, $this->get('session')->get('userData'));
        $dashboardWithReferralWithSpecialistServiceSummaries = $em->getRepository('RxConnexionBundle:ReferralEntity')->dashboardWithReferralWithSpecialistServiceSummary($get, $this->get('session')->get('userData'));
        $healthFacilities = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->branchesForMultiple($userData);

        if (isset($get['export_to_excel'])) {
            return $this->redirect($this->generateUrl('referral_with_specialist_service_export_to_excel', array(
                'params' => $get
            )), 302);
        }

        $page_title = 'Referral with Specialist Service';
        return $this->render('@RxConnexion/Admin/Dashboard/referral_with_specialist_service.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'records' => $dashboardWithReferralWithSpecialistService,
            'yearFilter'  => $yearFilter,
            'monthFilter'  => $monthFilter,
            'healthFacilities' => $healthFacilities,
            'summaries' => $dashboardWithReferralWithSpecialistServiceSummaries,
            'branch' => isset($get['branch']) ? $get['branch'] : 'All',
            'getYear' => isset($get['year']) ? $get['year'] : 'All',
            'getMonth' => isset($get['month']) ? $get['month'] : 'All'
        ));
    }

    /**
     * @Route(
     *      "/patient/referral_with_specialist_service/export_to_excel",
     *      name = "referral_with_specialist_service_export_to_excel"
     * )
     */
    public function referral_with_specialist_service_exportToExcelAction(Request $request) {
        $get = $request->get('params');

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Dashboard Referral With Specialist Service Excel'))) return $authService->redirectToHome();

        ini_set('memory_limit', '2048M');
        set_time_limit(0);

        $makeDate = "2000-1-1";
        $monthStart = date("n", strtotime($makeDate));
        $monthFilter = array();
        $i = 0;
        for ($m=$monthStart; $m < $monthStart+12; $m++) {
            $month = date('F', mktime(0,0,0,$m, 1, date('Y')));
            $monthFilter[$i]['display'] = $month;
            $monthFilter[$i]['value'] = $m;
            $i++;
        }

        $yearNow = date('Y');
        $yearFilter = array();
        $i = 0;
        for ($y=$yearNow; $y > $yearNow-10; $y--) {
            $yearFilter[$i]['display'] = $y;
            $yearFilter[$i]['value'] = $y;
            $i++;
        }

        $em = $this->getDoctrine()->getManager();
        $patientWithFaxNoEncounters = $em->getRepository('RxConnexionBundle:ReferralEntity')->dashboardWithReferralWithSpecialistService($get, $this->get('session')->get('userData'));

        ini_set('memory_limit', '2048M');
        set_time_limit(0);

        $cellsData[] = array('cell' => 'A1', 'data' => 'Referral with Specialist Service Report');

        $columnRange = range('A', 'L');
        $cellsData = array(
            array('cell' => 'A1', 'data' => 'Referral Date'),
            array('cell' => 'B1', 'data' => 'Branch'),
            array('cell' => 'C1', 'data' => 'Full Name'),
            array('cell' => 'D1', 'data' => 'Latest Patient Notes'),
        );
        $rowCtr = 1;
        $totalCount = 0;

        foreach($patientWithFaxNoEncounters as $record) {

            $rowCtr++;
            $totalCount++;

            $cellsData[] = array('cell' => "A$rowCtr", 'data' => isset($record['referralDate']) ? $record['referralDate'] : '');
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => isset($record['healthFacility']) ? $record['healthFacility'] : '');
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => isset($record['fullName']) ? $record['fullName'] : '');
            $cellsData[] = array('cell' => "D$rowCtr", 'data' => isset($record['latestNotes']) ? strip_tags($record['latestNotes']) : '');
        }

        $rowCtr++;
        $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Total Records: ' . $totalCount);

        $page_title = 'Specialist Service Report';
        return $this->export_to_excel($columnRange, $cellsData, $page_title);
    }

    /*Patients with other services*/

    /**
     * @Route(
     *      "/patient/referral_with_other_service",
     *      name = "referral_with_other_service_preview"
     * )
     */
    public function referral_with_other_service_previewAction(Request $request) {
        $get = $request->query->all();
        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Dashboard Referral With Other Service'))) return $authService->redirectToHome();

        $yearNow = date('Y');
        $yearFilter = array();
        $i = 0;
        for ($y=$yearNow; $y > $yearNow-10; $y--) {
            $yearFilter[$i]['display'] = $y;
            $yearFilter[$i]['value'] = $y;
            $i++;
        }

        $makeDate = "2000-1-1";
        $monthStart = date("n", strtotime($makeDate));
        $monthFilter = array();
        $i = 0;
        for ($m=$monthStart; $m < $monthStart+12; $m++) {
            $month = date('F', mktime(0,0,0,$m, 1, date('Y')));
            $monthFilter[$i]['display'] = $month;
            $monthFilter[$i]['value'] = $m;
            $i++;
        }


        ini_set('memory_limit', '2048M');
        set_time_limit(0);

        $em = $this->getDoctrine()->getManager();
        $userData = $this->get('session')->get('userData');
        $dashboardWithReferralWithOtherService = $em->getRepository('RxConnexionBundle:ReferralEntity')->dashboardWithReferralWithOtherService($get, $this->get('session')->get('userData'));
        $dashboardWithReferralWithOtherServiceSummaries = $em->getRepository('RxConnexionBundle:ReferralEntity')->dashboardWithReferralWithOtherServiceSummary($get, $this->get('session')->get('userData'));
        $healthFacilities = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->branchesForMultiple($userData);

        if (isset($get['export_to_excel'])) {
            return $this->redirect($this->generateUrl('referral_with_other_service_export_to_excel', array(
                'params' => $get
            )), 302);
        }

        $page_title = 'Referral with Other Service';
        return $this->render('@RxConnexion/Admin/Dashboard/referral_with_other_service.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'records' => $dashboardWithReferralWithOtherService,
            'yearFilter'  => $yearFilter,
            'monthFilter'  => $monthFilter,
            'healthFacilities' => $healthFacilities,
            'summaries' => $dashboardWithReferralWithOtherServiceSummaries,
            'branch' => isset($get['branch']) ? $get['branch'] : 'All',
            'getYear' => isset($get['year']) ? $get['year'] : 'All',
            'getMonth' => isset($get['month']) ? $get['month'] : 'All'
        ));
    }

    /**
     * @Route(
     *      "/patient/referral_with_other_service/export_to_excel",
     *      name = "referral_with_other_service_export_to_excel"
     * )
     */
    public function referral_with_other_service_exportToExcelAction(Request $request) {
        $get = $request->get('params');
        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Dashboard Referral With Other Service Excel'))) return $authService->redirectToHome();

        ini_set('memory_limit', '2048M');
        set_time_limit(0);

        $makeDate = "2000-1-1";
        $monthStart = date("n", strtotime($makeDate));
        $monthFilter = array();
        $i = 0;
        for ($m=$monthStart; $m < $monthStart+12; $m++) {
            $month = date('F', mktime(0,0,0,$m, 1, date('Y')));
            $monthFilter[$i]['display'] = $month;
            $monthFilter[$i]['value'] = $m;
            $i++;
        }

        $yearNow = date('Y');
        $yearFilter = array();
        $i = 0;
        for ($y=$yearNow; $y > $yearNow-10; $y--) {
            $yearFilter[$i]['display'] = $y;
            $yearFilter[$i]['value'] = $y;
            $i++;
        }

        $em = $this->getDoctrine()->getManager();
        $dashboardWithReferralWithSpecialistService = $em->getRepository('RxConnexionBundle:ReferralEntity')->dashboardWithReferralWithOtherService($get, $this->get('session')->get('userData'));

        ini_set('memory_limit', '2048M');
        set_time_limit(0);

        $cellsData[] = array('cell' => 'A1', 'data' => 'Referral with Other Service Report');

        $columnRange = range('A', 'L');
        $cellsData = array(
            array('cell' => 'A1', 'data' => 'Referral Date'),
            array('cell' => 'B1', 'data' => 'Branch'),
            array('cell' => 'C1', 'data' => 'Full Name'),
            array('cell' => 'D1', 'data' => 'Latest Patient Notes'),
        );
        $rowCtr = 1;
        $totalCount = 0;

        foreach($dashboardWithReferralWithSpecialistService as $record) {

            $rowCtr++;
            $totalCount++;

            $cellsData[] = array('cell' => "A$rowCtr", 'data' => isset($record['referralDate']) ? $record['referralDate'] : '');
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => isset($record['healthFacility']) ? $record['healthFacility'] : '');
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => isset($record['fullName']) ? $record['fullName'] : '');
            $cellsData[] = array('cell' => "D$rowCtr", 'data' => isset($record['latestNotes']) ? strip_tags($record['latestNotes']) : '');
        }

        $rowCtr++;
        $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Total Records: ' . $totalCount);

        $page_title = 'Other Service Report';
        return $this->export_to_excel($columnRange, $cellsData, $page_title);
    }

    /**
     * @Route(
     *      "/patient/initial_encounter",
     *      name = "patient_initial_encounter_preview"
     * )
     */
    public function patient_initial_encounter_previewAction(Request $request) {
        $get = $request->query->all();
        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Dashboard Patient Initial Encounter'))) return $authService->redirectToHome();

        ini_set('memory_limit', '2048M');
        set_time_limit(0);

        $makeDate = "2000-1-1";
        $monthStart = date("n", strtotime($makeDate));
        $monthFilter = array();
        $i = 0;
        for ($m=$monthStart; $m < $monthStart+12; $m++) {
            $month = date('F', mktime(0,0,0,$m, 1, date('Y')));
            $monthFilter[$i]['display'] = $month;
            $monthFilter[$i]['value'] = $m;
            $i++;
        }

        $yearNow = date('Y');
        $yearFilter = array();
        $i = 0;
        for ($y=$yearNow; $y > $yearNow-10; $y--) {
            $yearFilter[$i]['display'] = $y;
            $yearFilter[$i]['value'] = $y;
            $i++;
        }

        $em = $this->getDoctrine()->getManager();
        $userData = $this->get('session')->get('userData');
        $noEncounters = $em->getRepository('RxConnexionBundle:PatientEntity')->dashboardPatientNoCharts($get, $this->get('session')->get('userData'));
        $noEncountersSummaries = $em->getRepository('RxConnexionBundle:PatientEntity')->dashboardPatientNoChartsSummary($get, $this->get('session')->get('userData'));
        $healthFacilities = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->branchesForMultiple($userData);

        $page_title = 'Patient without Encounter';
        return $this->render('@RxConnexion/Admin/Dashboard/initial_encounter.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'records' => $noEncounters,
            'monthFilter'  => $monthFilter,
            'yearFilter'  => $yearFilter,
            'summaries'  => $noEncountersSummaries,
            'healthFacilities' => $healthFacilities,
            'branch' => isset($get['branch']) ? $get['branch'] : 'All',
            'getYear' => isset($get['year']) ? $get['year'] : 'All',
            'getMonth' => isset($get['month']) ? $get['month'] : 'All'

        ));
    }

    /**
     * @Route(
     *      "/patient/initial_encounter/export_to_excel",
     *      name = "patient_initial_encounter_export_to_excel"
     * )
     */
    public function dashboard_initial_encounter_exportToExcelAction(Request $request) {
        $get = $request->query->all();
        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Dashboard Initial Encounter Excel'))) return $authService->redirectToHome();

        ini_set('memory_limit', '2048M');
        set_time_limit(0);

        $makeDate = "2000-1-1";
        $monthStart = date("n", strtotime($makeDate));
        $monthFilter = array();
        $i = 0;
        for ($m=$monthStart; $m < $monthStart+12; $m++) {
            $month = date('F', mktime(0,0,0,$m, 1, date('Y')));
            $monthFilter[$i]['display'] = $month;
            $monthFilter[$i]['value'] = $m;
            $i++;
        }

        $yearNow = date('Y');
        $yearFilter = array();
        $i = 0;
        for ($y=$yearNow; $y > $yearNow-10; $y--) {
            $yearFilter[$i]['display'] = $y;
            $yearFilter[$i]['value'] = $y;
            $i++;
        }

        $em = $this->getDoctrine()->getManager();
        $noEncounters = $em->getRepository('RxConnexionBundle:PatientEntity')->dashboardPatientNoCharts($get, $this->get('session')->get('userData'));

        ini_set('memory_limit', '2048M');
        set_time_limit(0);

        $cellsData[] = array('cell' => 'A1', 'data' => 'Patient w/o Encounter Report');

        $columnRange = range('A', 'L');
        $cellsData = array(
            array('cell' => 'A1', 'data' => 'Branch'),
            array('cell' => 'B1', 'data' => 'Patient ID'),
            array('cell' => 'C1', 'data' => 'Full Name'),
            array('cell' => 'D1', 'data' => 'Invoice No.'),
            array('cell' => 'E1', 'data' => 'Note'),
            array('cell' => 'F1', 'data' => 'File'),
            array('cell' => 'G1', 'data' => 'Ticket No.'),
            array('cell' => 'H1', 'data' => 'Referring Physician'),
            array('cell' => 'I1', 'data' => 'Referring Affiliate'),
        );
        $rowCtr = 1;
        $totalCount = 0;

        foreach($noEncounters as $record) {

            $rowCtr++;
            $totalCount++;

            $cellsData[] = array('cell' => "A$rowCtr", 'data' => isset($record['healthFacility']) ? $record['healthFacility'] : '');
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => isset($record['patientId']) ? $record['patientId'] : '');
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => isset($record['patientName']) ? $record['patientName'] : '');
            $cellsData[] = array('cell' => "D$rowCtr", 'data' => isset($record['invoiceNo']) ? $record['invoiceNo'] : '');
            $cellsData[] = array('cell' => "E$rowCtr", 'data' => isset($record['note']) ? $record['note'] : '');
            $cellsData[] = array('cell' => "F$rowCtr", 'data' => isset($record['fileDesc']) ? $record['fileDesc'] : '');
            $cellsData[] = array('cell' => "G$rowCtr", 'data' => isset($record['ticketNo']) ? $record['ticketNo'] : '');
            $cellsData[] = array('cell' => "H$rowCtr", 'data' => isset($record['referringProvider']) ? $record['referringProvider'] : '');
            $cellsData[] = array('cell' => "I$rowCtr", 'data' => isset($record['referringHealthFacility']) ? $record['referringHealthFacility'] : '');
        }

        $rowCtr++;
        $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Total Records: ' . $totalCount);

        $page_title = 'Initial Encounter Report';
        return $this->export_to_excel($columnRange, $cellsData, $page_title);
    }

    /**
     * @Route(
     *      "/dashboard/appointment_notice_preview",
     *      name = "dashboard_appointment_notice_preview"
     * )
     */
    public function dashboard_appointment_notice_previewAction(Request $request) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Dashboard Appointment Notice'))) return $authService->redirectToHome();

        ini_set('memory_limit', '2048M');
        set_time_limit(0);

        $get = $request->query->all();

        $makeDate = "2000-1-1";
        $monthStart = date("n", strtotime($makeDate));
        $monthFilter = array();
        $i = 0;
        for ($m=$monthStart; $m < $monthStart+12; $m++) {
            $month = date('F', mktime(0,0,0,$m, 1, date('Y')));
            $monthFilter[$i]['display'] = $month;
            $monthFilter[$i]['value'] = $m;
            $i++;
        }

        $yearNow = date('Y');
        $yearFilter = array();
        $i = 0;
        for ($y=$yearNow; $y > $yearNow-10; $y--) {
            $yearFilter[$i]['display'] = $y;
            $yearFilter[$i]['value'] = $y;
            $i++;
        }

        $em = $this->getDoctrine()->getManager();
        $userData = $this->get('session')->get('userData');
        $records = $em->getRepository('RxConnexionBundle:PatientEntity')->dashboardAppointmentNotice($get, $this->get('session')->get('userData'));
        $recordsSummaries = $em->getRepository('RxConnexionBundle:PatientEntity')->dashboardAppointmentNoticeSummary($get, $this->get('session')->get('userData'));
        $healthFacilities = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->branchesForMultiple($userData);

        $chartTypes = $em->getRepository('RxConnexionBundle:ChartTypeEntity')->findBy(array(), array('description' => 'asc'));

        $page_title = 'Appointment Notice';
        return $this->render('@RxConnexion/Admin/Dashboard/appointment_notice.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'records' => $records,
            'healthFacilities' => $healthFacilities,
            'chartTypes' => $chartTypes,
            'monthFilter'  => $monthFilter,
            'yearFilter'  => $yearFilter,
            'summaries'  => $recordsSummaries,
            'branch' => isset($get['branch']) ? $get['branch'] : 'All',
            'chartType' => isset($get['chartType']) ? $get['chartType'] : 'All',
            'getYear' => isset($get['year']) ? $get['year'] : 'All',
            'getMonth' => isset($get['month']) ? $get['month'] : 'All'
        ));
    }

    /**
     * @Route(
     *      "/patient/appointment_notice/export_to_excel",
     *      name = "patient_appointment_notice_export_to_excel"
     * )
     */
    public function dashboard_appointment_notice_exportToExcelAction(Request $request) {
        $get = $request->query->all();
        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Dashboard Appointment Notice Excel'))) return $authService->redirectToHome();

        ini_set('memory_limit', '2048M');
        set_time_limit(0);

        $makeDate = "2000-1-1";
        $monthStart = date("n", strtotime($makeDate));
        $monthFilter = array();
        $i = 0;
        for ($m=$monthStart; $m < $monthStart+12; $m++) {
            $month = date('F', mktime(0,0,0,$m, 1, date('Y')));
            $monthFilter[$i]['display'] = $month;
            $monthFilter[$i]['value'] = $m;
            $i++;
        }

        $yearNow = date('Y');
        $yearFilter = array();
        $i = 0;
        for ($y=$yearNow; $y > $yearNow-10; $y--) {
            $yearFilter[$i]['display'] = $y;
            $yearFilter[$i]['value'] = $y;
            $i++;
        }

        $em = $this->getDoctrine()->getManager();
        $appointmentNotice = $em->getRepository('RxConnexionBundle:PatientEntity')->dashboardAppointmentNotice($get, $this->get('session')->get('userData'));

        ini_set('memory_limit', '2048M');
        set_time_limit(0);

        $cellsData[] = array('cell' => 'A1', 'data' => 'Appointment Notice Report');

        $columnRange = range('A', 'L');
        $cellsData = array(
            array('cell' => 'A1', 'data' => 'Schedule ID'),
            array('cell' => 'B1', 'data' => 'Branch'),
            array('cell' => 'C1', 'data' => 'Schedule Date'),
            array('cell' => 'D1', 'data' => 'Patient Name'),
            array('cell' => 'E1', 'data' => 'Clinician'),
            array('cell' => 'F1', 'data' => 'Encounter Type'),
            array('cell' => 'G1', 'data' => 'Start Time'),
            array('cell' => 'H1', 'data' => 'End Time'),
        );
        $rowCtr = 1;
        $totalCount = 0;

        foreach($appointmentNotice as $record) {

            $rowCtr++;
            $totalCount++;

            $cellsData[] = array('cell' => "A$rowCtr", 'data' => isset($record['schedId']) ? $record['schedId'] : '');
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => isset($record['hfDesc']) ? $record['hfDesc'] : '');
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => isset($record['schedDate']) ? $record['schedDate'] : '');
            $cellsData[] = array('cell' => "D$rowCtr", 'data' => isset($record['ptName']) ? $record['ptName'] : '');
            $cellsData[] = array('cell' => "E$rowCtr", 'data' => isset($record['provName']) ? $record['provName'] : '');
            $cellsData[] = array('cell' => "F$rowCtr", 'data' => isset($record['ctDesc']) ? $record['ctDesc'] : '');
            $cellsData[] = array('cell' => "G$rowCtr", 'data' => isset($record['sTime']) ? $record['sTime'] : '');
            $cellsData[] = array('cell' => "H$rowCtr", 'data' => isset($record['eTime']) ? $record['eTime'] : '');
        }

        $rowCtr++;
        $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Total Records: ' . $totalCount);

        $page_title = 'Appointment Notice Report';
        return $this->export_to_excel($columnRange, $cellsData, $page_title);
    }

    /**
     * @Route(
     *      "/patient/for_rebooking",
     *      name = "patient_for_rebooking"
     * )
     */
    public function patient_for_rebooking_previewAction(Request $request) {
        $get = $request->query->all();
        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Dashboard Patient For Rebooking'))) return $authService->redirectToHome();

        ini_set('memory_limit', '2048M');
        set_time_limit(0);

        $makeDate = "2000-1-1";
        $monthStart = date("n", strtotime($makeDate));
        $monthFilter = array();
        $i = 0;
        for ($m=$monthStart; $m < $monthStart+12; $m++) {
            $month = date('F', mktime(0,0,0,$m, 1, date('Y')));
            $monthFilter[$i]['display'] = $month;
            $monthFilter[$i]['value'] = $m;
            $i++;
        }

        $yearNow = date('Y');
        $yearFilter = array();
        $i = 0;
        for ($y=$yearNow; $y > $yearNow-10; $y--) {
            $yearFilter[$i]['display'] = $y;
            $yearFilter[$i]['value'] = $y;
            $i++;
        }

        $em = $this->getDoctrine()->getManager();
        $userData = $this->get('session')->get('userData');
        $forReBookings = $em->getRepository('RxConnexionBundle:PatientChartEntity')->dashboardForRebooking($get, $this->get('session')->get('userData'));
        $forReBookingsSummaries = $em->getRepository('RxConnexionBundle:PatientChartEntity')->dashboardForRebookingSummary($get, $this->get('session')->get('userData'));
        $healthFacilities = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->branchesForMultiple($userData);
        $encounterTypes = $em->getRepository('RxConnexionBundle:ChartTypeEntity')->findAll();

        $page_title = 'Patient For Rebooking';
        return $this->render('@RxConnexion/Admin/Dashboard/for_rebooking.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'records' => $forReBookings,
            'monthFilter'  => $monthFilter,
            'yearFilter'  => $yearFilter,
            'summaries' => $forReBookingsSummaries,
            'healthFacilities' => $healthFacilities,
            'encounterTypes' => $encounterTypes,
            'branch' => isset($get['branch']) ? $get['branch'] : 'All',
            'encounterType' => isset($get['encounterType']) ? $get['encounterType'] : 'All',
            'getYear' => isset($get['year']) ? $get['year'] : 'All',
            'getMonth' => isset($get['month']) ? $get['month'] : 'All'
        ));
    }

    /**
     * @Route(
     *      "/patient/for_rebooking/export_to_excel",
     *      name = "patient_for_rebooking_export_to_excel"
     * )
     */
    public function patient_for_rebooking_exportToExcelAction(Request $request) {
        $get = $request->query->all();
        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Dashboard Patient For Rebooking Excel'))) return $authService->redirectToHome();

        ini_set('memory_limit', '2048M');
        set_time_limit(0);

        $makeDate = "2000-1-1";
        $monthStart = date("n", strtotime($makeDate));
        $monthFilter = array();
        $i = 0;
        for ($m=$monthStart; $m < $monthStart+12; $m++) {
            $month = date('F', mktime(0,0,0,$m, 1, date('Y')));
            $monthFilter[$i]['display'] = $month;
            $monthFilter[$i]['value'] = $m;
            $i++;
        }

        $yearNow = date('Y');
        $yearFilter = array();
        $i = 0;
        for ($y=$yearNow; $y > $yearNow-10; $y--) {
            $yearFilter[$i]['display'] = $y;
            $yearFilter[$i]['value'] = $y;
            $i++;
        }

        $em = $this->getDoctrine()->getManager();
        $forReBookings = $em->getRepository('RxConnexionBundle:PatientChartEntity')->dashboardForRebooking($get, $this->get('session')->get('userData'));

        ini_set('memory_limit', '2048M');
        set_time_limit(0);

        $cellsData[] = array('cell' => 'A1', 'data' => 'For Rebooking Report');

        $columnRange = range('A', 'L');
        $cellsData = array(
            array('cell' => 'A1', 'data' => 'Branch'),
            array('cell' => 'B1', 'data' => 'Encounter ID'),
            array('cell' => 'C1', 'data' => 'Patient'),
            array('cell' => 'D1', 'data' => 'Encounter Date'),
            array('cell' => 'E1', 'data' => 'Clinician'),
            array('cell' => 'F1', 'data' => 'Encounter Type'),
            array('cell' => 'G1', 'data' => 'Encounter Status'),
            array('cell' => 'H1', 'data' => 'Latest Notes'),
        );
        $rowCtr = 1;
        $totalCount = 0;

        foreach($forReBookings as $record) {

            $rowCtr++;
            $totalCount++;

            $cellsData[] = array('cell' => "A$rowCtr", 'data' => isset($record['healthFacility']) ? $record['healthFacility'] : '');
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => isset($record['patientChartId']) ? $record['patientChartId'] : '');
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => isset($record['fullName']) ? $record['fullName'] : '');
            $cellsData[] = array('cell' => "D$rowCtr", 'data' => isset($record['chartDate']) ? $record['chartDate'] : '');
            $cellsData[] = array('cell' => "E$rowCtr", 'data' => isset($record['providerName']) ? $record['providerName'] : '');
            $cellsData[] = array('cell' => "F$rowCtr", 'data' => isset($record['chartType']) ? $record['chartType'] : '');
            $cellsData[] = array('cell' => "G$rowCtr", 'data' => isset($record['chartStatus']) ? $record['chartStatus'] : '');
            $cellsData[] = array('cell' => "H$rowCtr", 'data' => isset($record['note']) ? strip_tags($record['note']) : '');
        }

        $rowCtr++;
        $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Total Records: ' . $totalCount);

        $page_title = 'For Rebooking Report';
        return $this->export_to_excel($columnRange, $cellsData, $page_title);
    }

    /**
     * @Route(
     *      "/patient/encounter_calls",
     *      name = "patient_encounter_call"
     * )
     */
    public function patient_encounter_call_previewAction(Request $request) {
        $get = $request->query->all();
        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Dashboard Patient Encounter Call'))) return $authService->redirectToHome();

        ini_set('memory_limit', '2048M');
        set_time_limit(0);

        $em = $this->getDoctrine()->getManager();
        $userData = $this->get('session')->get('userData');
        $encounterCalls = $em->getRepository('RxConnexionBundle:PatientChartEntity')->dashboardEncounterCalls($get, $this->get('session')->get('userData'));
        $healthFacilities = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->branchesForMultiple($userData);
        $encounterTypes = $em->getRepository('RxConnexionBundle:ChartTypeEntity')->findAll();

        $page_title = 'Reminder Call';
        return $this->render('@RxConnexion/Admin/Dashboard/encounter_call.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'records' => $encounterCalls,
            'encounterTypes' => $encounterTypes,
            'healthFacilities' => $healthFacilities,
            'branch' => isset($get['branch']) ? $get['branch'] : '',
            'encounterType' => isset($get['encounterType']) ? $get['encounterType'] : 'All',
        ));
    }

    /**
     * @Route(
     *      "/patient/72_hours_follow_up",
     *      name = "patient_72_hours_follow_up"
     * )
     */
    public function patient_72_hours_follow_up_previewAction(Request $request) {
        $get = $request->query->all();
        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Dashboard Patient 72 Hours Follow Up'))) return $authService->redirectToHome();

        ini_set('memory_limit', '2048M');
        set_time_limit(0);

        $makeDate = "2000-1-1";
        $monthStart = date("n", strtotime($makeDate));
        $monthFilter = array();
        $i = 0;
        for ($m=$monthStart; $m < $monthStart+12; $m++) {
            $month = date('F', mktime(0,0,0,$m, 1, date('Y')));
            $monthFilter[$i]['display'] = $month;
            $monthFilter[$i]['value'] = $m;
            $i++;
        }

        $yearNow = date('Y');
        $yearFilter = array();
        $i = 0;
        for ($y=$yearNow; $y > $yearNow-10; $y--) {
            $yearFilter[$i]['display'] = $y;
            $yearFilter[$i]['value'] = $y;
            $i++;
        }

        $em = $this->getDoctrine()->getManager();
        $userData = $this->get('session')->get('userData');
        $for72MonthFollowUps = $em->getRepository('RxConnexionBundle:PatientChartEntity')->dashboardForSeventyTwoHourFollowUps($get, $this->get('session')->get('userData'));
        $for72MonthFollowUpsSummary = $em->getRepository('RxConnexionBundle:PatientChartEntity')->dashboardForSeventyTwoHourFollowUpsSummary($get, $this->get('session')->get('userData'));
        $healthFacilities = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->branchesForMultiple($userData);
        $encounterTypes = $em->getRepository('RxConnexionBundle:ChartTypeEntity')->findAll();

        $page_title = 'Patient Encounter (72 Hours Follow Up)';
        return $this->render('@RxConnexion/Admin/Dashboard/72_hour_follow_up.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'records' => $for72MonthFollowUps,
            'summaries' => $for72MonthFollowUpsSummary,
            'healthFacilities' => $healthFacilities,
            'encounterTypes' => $encounterTypes,
            'monthFilter'  => $monthFilter,
            'yearFilter'  => $yearFilter,
            'branch' => isset($get['branch']) ? $get['branch'] : 'All',
            'encounterType' => isset($get['encounterType']) ? $get['encounterType'] : 'All',
            'getYear' => isset($get['year']) ? $get['year'] : 'All',
            'getMonth' => isset($get['month']) ? $get['month'] : 'All'
        ));
    }

    /**
     * @Route(
     *      "/patient/72_months_follow_up/export_to_excel",
     *      name = "patient_72_months_follow_up_export_to_excel"
     * )
     */
    public function patient_72_month_follow_up_exportToExcelAction(Request $request) {
        $get = $request->query->all();
        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Dashboard Patient 72 Month Follow Up Excel'))) return $authService->redirectToHome();

        ini_set('memory_limit', '2048M');
        set_time_limit(0);

        $makeDate = "2000-1-1";
        $monthStart = date("n", strtotime($makeDate));
        $monthFilter = array();
        $i = 0;
        for ($m=$monthStart; $m < $monthStart+12; $m++) {
            $month = date('F', mktime(0,0,0,$m, 1, date('Y')));
            $monthFilter[$i]['display'] = $month;
            $monthFilter[$i]['value'] = $m;
            $i++;
        }

        $yearNow = date('Y');
        $yearFilter = array();
        $i = 0;
        for ($y=$yearNow; $y > $yearNow-10; $y--) {
            $yearFilter[$i]['display'] = $y;
            $yearFilter[$i]['value'] = $y;
            $i++;
        }

        $em = $this->getDoctrine()->getManager();
        $for72MonthFollowUps = $em->getRepository('RxConnexionBundle:PatientChartEntity')->dashboardForSeventyTwoHourFollowUps($get, $this->get('session')->get('userData'));

        ini_set('memory_limit', '2048M');
        set_time_limit(0);

        $cellsData[] = array('cell' => 'A1', 'data' => '72 Hour(s) Follow-up Report');

        $columnRange = range('A', 'L');
        $cellsData = array(
            array('cell' => 'A1', 'data' => 'Branch'),
            array('cell' => 'B1', 'data' => 'Patient'),
            array('cell' => 'C1', 'data' => 'Last CPAP Setup Date'),
            array('cell' => 'D1', 'data' => 'Last CPAP Setup Status'),
            array('cell' => 'E1', 'data' => 'Current AHI'),
            array('cell' => 'F1', 'data' => 'Primary Clinician'),
            array('cell' => 'G1', 'data' => 'Note'),
        );
        $rowCtr = 1;
        $totalCount = 0;

        foreach($for72MonthFollowUps as $record) {

            $rowCtr++;
            $totalCount++;

            $cellsData[] = array('cell' => "A$rowCtr", 'data' => isset($record['healthFacility']) ? $record['healthFacility'] : '');
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => isset($record['fullName']) ? $record['fullName'] : '');
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => isset($record['cpapSetupDate']) ? $record['cpapSetupDate'] : '');
            $cellsData[] = array('cell' => "D$rowCtr", 'data' => isset($record['cpapSetupStatus']) ? $record['cpapSetupStatus'] : '');
            $cellsData[] = array('cell' => "E$rowCtr", 'data' => isset($record['currentAhi']) ? $record['currentAhi'] : '');
            $cellsData[] = array('cell' => "E$rowCtr", 'data' => isset($record['primaryProvider']) ? $record['primaryProvider'] : '');
            $cellsData[] = array('cell' => "F$rowCtr", 'data' => isset($record['note']) ? strip_tags($record['note']) : '');
        }

        $rowCtr++;
        $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Total Records: ' . $totalCount);

        $page_title = '72 Hours Follow Up Report';
        return $this->export_to_excel($columnRange, $cellsData, $page_title);
    }

    /**
     * @Route(
     *      "/patient/3_months_follow_up",
     *      name = "patient_3_months_follow_up"
     * )
     */
    public function patient_3_month_follow_up_previewAction(Request $request) {
        $get = $request->query->all();
        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Dashboard Patient 3 Month Follow Up'))) return $authService->redirectToHome();

        ini_set('memory_limit', '2048M');
        set_time_limit(0);

        $makeDate = "2000-1-1";
        $monthStart = date("n", strtotime($makeDate));
        $monthFilter = array();
        $i = 0;
        for ($m=$monthStart; $m < $monthStart+12; $m++) {
            $month = date('F', mktime(0,0,0,$m, 1, date('Y')));
            $monthFilter[$i]['display'] = $month;
            $monthFilter[$i]['value'] = $m;
            $i++;
        }

        $yearNow = date('Y');
        $yearFilter = array();
        $i = 0;
        for ($y=$yearNow; $y > $yearNow-10; $y--) {
            $yearFilter[$i]['display'] = $y;
            $yearFilter[$i]['value'] = $y;
            $i++;
        }


        $em = $this->getDoctrine()->getManager();
        $userData = $this->get('session')->get('userData');
        $for3MonthFollowUps = $em->getRepository('RxConnexionBundle:PatientChartEntity')->dashboardForThreeMonthsFollowUps($get, $this->get('session')->get('userData'));
        $for3MonthFollowUpsSummaries = $em->getRepository('RxConnexionBundle:PatientChartEntity')->dashboardForThreeMonthsFollowUpsSummary($get, $this->get('session')->get('userData'));
        $healthFacilities = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->branchesForMultiple($userData);
        $encounterTypes = $em->getRepository('RxConnexionBundle:ChartTypeEntity')->findAll();

        $page_title = 'Patient Encounter (3 Months Follow Up)';
        return $this->render('@RxConnexion/Admin/Dashboard/3_month_follow_up.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'monthFilter'  => $monthFilter,
            'yearFilter'  => $yearFilter,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'summaries' => $for3MonthFollowUpsSummaries,
            'records' => $for3MonthFollowUps,
            'healthFacilities' => $healthFacilities,
            'encounterTypes' => $encounterTypes,
            'encounterType' => isset($get['encounterType']) ? $get['encounterType'] : 'All',
            'branch' => isset($get['branch']) ? $get['branch'] : 'All',
            'getYear' => isset($get['year']) ? $get['year'] : 'All',
            'getMonth' => isset($get['month']) ? $get['month'] : 'All'
        ));
    }

    /**
     * @Route(
     *      "/patient/3_months_follow_up/export_to_excel",
     *      name = "patient_3_months_follow_up_export_to_excel"
     * )
     */
    public function patient_3_month_follow_up_exportToExcelAction(Request $request) {
        $get = $request->query->all();
        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Dashboard Patient 3 Month Follow Up Excel'))) return $authService->redirectToHome();

        ini_set('memory_limit', '2048M');
        set_time_limit(0);

        $makeDate = "2000-1-1";
        $monthStart = date("n", strtotime($makeDate));
        $monthFilter = array();
        $i = 0;
        for ($m=$monthStart; $m < $monthStart+12; $m++) {
            $month = date('F', mktime(0,0,0,$m, 1, date('Y')));
            $monthFilter[$i]['display'] = $month;
            $monthFilter[$i]['value'] = $m;
            $i++;
        }

        $yearNow = date('Y');
        $yearFilter = array();
        $i = 0;
        for ($y=$yearNow; $y > $yearNow-10; $y--) {
            $yearFilter[$i]['display'] = $y;
            $yearFilter[$i]['value'] = $y;
            $i++;
        }

        $em = $this->getDoctrine()->getManager();
        $for3MonthFollowUps = $em->getRepository('RxConnexionBundle:PatientChartEntity')->dashboardForThreeMonthsFollowUps($get, $this->get('session')->get('userData'));

        ini_set('memory_limit', '2048M');
        set_time_limit(0);

        $cellsData[] = array('cell' => 'A1', 'data' => '3 Months Follow-up Report');

        $columnRange = range('A', 'L');
        $cellsData = array(
            array('cell' => 'A1', 'data' => 'Branch'),
            array('cell' => 'B1', 'data' => 'Patient'),
            array('cell' => 'C1', 'data' => 'Latest Care Call Date'),
            array('cell' => 'D1', 'data' => 'Latest Care Call Status'),
            array('cell' => 'E1', 'data' => 'Latest CPAP Setup Date'),
            array('cell' => 'F1', 'data' => 'Latest CPAP Setup Status'),
            array('cell' => 'G1', 'data' => 'Primary Clinician'),
            array('cell' => 'H1', 'data' => 'Latest Note'),
        );
        $rowCtr = 1;
        $totalCount = 0;

        foreach($for3MonthFollowUps as $record) {

            $rowCtr++;
            $totalCount++;

            $cellsData[] = array('cell' => "A$rowCtr", 'data' => isset($record['healthFacility']) ? $record['healthFacility'] : '');
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => isset($record['fullName']) ? $record['fullName'] : '');
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => isset($record['careCallDate']) ? $record['careCallDate'] : '');
            $cellsData[] = array('cell' => "D$rowCtr", 'data' => isset($record['careCallStatus']) ? $record['careCallStatus'] : '');
            $cellsData[] = array('cell' => "E$rowCtr", 'data' => isset($record['cpapSetupDate']) ? $record['cpapSetupDate'] : '');
            $cellsData[] = array('cell' => "F$rowCtr", 'data' => isset($record['cpapSetupStatus']) ? $record['cpapSetupStatus'] : '');
            $cellsData[] = array('cell' => "G$rowCtr", 'data' => isset($record['primaryProvider']) ? $record['primaryProvider'] : '');
            $cellsData[] = array('cell' => "H$rowCtr", 'data' => isset($record['note']) ? strip_tags($record['note']) : '');
        }

        $rowCtr++;
        $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Total Records: ' . $totalCount);

        $page_title = '3 Months Follow Up Report';
        return $this->export_to_excel($columnRange, $cellsData, $page_title);
    }


    /**
     * @Route(
     *      "/patient/6_months_follow_up",
     *      name = "patient_6_months_follow_up"
     * )
     */
    public function patient_6_months_follow_up_previewAction(Request $request) {
        $params = $request->query->all();

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Dashboard Patient 6 Month Follow Up'))) return $authService->redirectToHome();

        ini_set('memory_limit', '2048M');
        set_time_limit(0);

        $makeDate = "2000-1-1";
        $monthStart = date("n", strtotime($makeDate));
        $monthFilter = array();
        $i = 0;
        for ($m=$monthStart; $m < $monthStart+12; $m++) {
            $month = date('F', mktime(0,0,0,$m, 1, date('Y')));
            $monthFilter[$i]['display'] = $month;
            $monthFilter[$i]['value'] = $m;
            $i++;
        }

        $yearNow = date('Y');
        $yearFilter = array();
        $i = 0;
        for ($y=$yearNow; $y > $yearNow-10; $y--) {
            $yearFilter[$i]['display'] = $y;
            $yearFilter[$i]['value'] = $y;
            $i++;
        }

        $em = $this->getDoctrine()->getManager();

        $userData = $this->get('session')->get('userData');

        $for6MonthFollowUps = $em->getRepository('RxConnexionBundle:PatientChartEntity')->dashboardForSixMonthsFollowUps($params, $this->get('session')->get('userData'));
        $for6MonthFollowUpsSummaries = $em->getRepository('RxConnexionBundle:PatientChartEntity')->dashboardForSixMonthsFollowUpsSummary($params, $this->get('session')->get('userData'));
        $healthFacilities = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->branchesForMultiple($userData);
        $encounterTypes = $em->getRepository('RxConnexionBundle:ChartTypeEntity')->findAll();

        $page_title = 'Patient Encounter (6 Months Follow Up)';
        return $this->render('@RxConnexion/Admin/Dashboard/6_month_follow_up.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'records' => $for6MonthFollowUps,
            'summaries' => $for6MonthFollowUpsSummaries,
            'monthFilter'  => $monthFilter,
            'yearFilter' => $yearFilter,
            'healthFacilities' => $healthFacilities,
            'encounterTypes' => $encounterTypes,
            'encounterType' => isset($params['encounterType']) ? $params['encounterType'] : 'All',
            'branch' => isset($params['branch']) ? $params['branch'] : 'All',
            'getYear' => isset($params['year']) ? $params['year'] : 'All',
            'getMonth' => isset($params['month']) ? $params['month'] : 'All'
        ));
    }

    /**
     * @Route(
     *      "/patient/6_months_follow_up/export_to_excel",
     *      name = "patient_6_months_follow_up_export_to_excel"
     * )
     */
    public function patient_6_months_follow_up_exportToExcelAction(Request $request) {
        $get = $request->query->all();
        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Dashboard Patient 6 Month Follow Up Excel'))) return $authService->redirectToHome();

        ini_set('memory_limit', '2048M');
        set_time_limit(0);

        $makeDate = "2000-1-1";
        $monthStart = date("n", strtotime($makeDate));
        $monthFilter = array();
        $i = 0;
        for ($m=$monthStart; $m < $monthStart+12; $m++) {
            $month = date('F', mktime(0,0,0,$m, 1, date('Y')));
            $monthFilter[$i]['display'] = $month;
            $monthFilter[$i]['value'] = $m;
            $i++;
        }

        $yearNow = date('Y');
        $yearFilter = array();
        $i = 0;
        for ($y=$yearNow; $y > $yearNow-10; $y--) {
            $yearFilter[$i]['display'] = $y;
            $yearFilter[$i]['value'] = $y;
            $i++;
        }

        $em = $this->getDoctrine()->getManager();
        $for6MonthFollowUps = $em->getRepository('RxConnexionBundle:PatientChartEntity')->dashboardForSixMonthsFollowUps($get);

        ini_set('memory_limit', '2048M');
        set_time_limit(0);

        $cellsData[] = array('cell' => 'A1', 'data' => '6 Months Follow-up Report');

        $columnRange = range('A', 'M');
        $cellsData = array(
            array('cell' => 'A1', 'data' => 'Branch'),
            array('cell' => 'B1', 'data' => 'Patient'),
            array('cell' => 'C1', 'data' => 'Latest 6 Months Follow-up Date'),
            array('cell' => 'D1', 'data' => 'Latest 6 Months Follow-up Status'),
            array('cell' => 'E1', 'data' => 'Latest CPAP Setup Date'),
            array('cell' => 'F1', 'data' => 'Latest CPAP Setup Status'),
            array('cell' => 'G1', 'data' => 'Latest CPAP Setup Sold Date'),
            array('cell' => 'H1', 'data' => 'Latest CPAP Setup Sold Status'),
            array('cell' => 'I1', 'data' => 'Latest CPAP End Eval Date'),
            array('cell' => 'J1', 'data' => 'Latest CPAP End Eval Status'),
            array('cell' => 'K1', 'data' => 'Primary Clinician'),
            array('cell' => 'L1', 'data' => 'Next 6 months Follow up date'),
            array('cell' => 'M1', 'data' => 'Latest Notes'),
        );
        $rowCtr = 1;
        $totalCount = 0;

        foreach($for6MonthFollowUps as $record) {

            $rowCtr++;
            $totalCount++;

            $cellsData[] = array('cell' => "A$rowCtr", 'data' => isset($record['healthFacility']) ? $record['healthFacility'] : '');
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => isset($record['fullName']) ? $record['fullName'] : '');
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => isset($record['sixMonthFFdate']) ? $record['sixMonthFFdate'] : '');
            $cellsData[] = array('cell' => "D$rowCtr", 'data' => isset($record['sixMonthFFstatus']) ? $record['sixMonthFFstatus'] : '');
            $cellsData[] = array('cell' => "E$rowCtr", 'data' => isset($record['cpapSetupDate']) ? $record['cpapSetupDate'] : '');
            $cellsData[] = array('cell' => "F$rowCtr", 'data' => isset($record['cpapSetupStatus']) ? $record['cpapSetupStatus'] : '');
            $cellsData[] = array('cell' => "G$rowCtr", 'data' => isset($record['cpapSetupSoldDate']) ? $record['cpapSetupSoldDate'] : '');
            $cellsData[] = array('cell' => "H$rowCtr", 'data' => isset($record['cpapSetupSoldStatus']) ? $record['cpapSetupSoldStatus'] : '');
            $cellsData[] = array('cell' => "I$rowCtr", 'data' => isset($record['cpaEndEvalDate']) ? $record['cpaEndEvalDate'] : '');
            $cellsData[] = array('cell' => "J$rowCtr", 'data' => isset($record['cpapEndEvalStatus']) ? $record['cpapEndEvalStatus'] : '');
            $cellsData[] = array('cell' => "K$rowCtr", 'data' => isset($record['primaryProviderName']) ? $record['primaryProviderName'] : '');
            $cellsData[] = array('cell' => "L$rowCtr", 'data' => $record['sixMonthFFdate'] != '' ? $record['sixMonthsFFPlusSixMonths'] : $record['cpapSetupPlusSixMonths']);
            $cellsData[] = array('cell' => "M$rowCtr", 'data' => isset($record['note']) ? strip_tags($record['note']) : '');
        }

        $rowCtr++;
        $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Total Records: ' . $totalCount);

        $page_title = '6 Months Follow Up Report';
        return $this->export_to_excel($columnRange, $cellsData, $page_title);
    }

    /**
     * @Route(
     *      "/patient/pft",
     *      name = "patient_pft"
     * )
     */
    public function patient_pft_previewAction(Request $request) {
        $params = $request->query->all();

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Dashboard Patient Pft'))) return $authService->redirectToHome();

        ini_set('memory_limit', '2048M');
        set_time_limit(0);

        $makeDate = "2000-1-1";
        $monthStart = date("n", strtotime($makeDate));
        $monthFilter = array();
        $i = 0;
        for ($m=$monthStart; $m < $monthStart+12; $m++) {
            $month = date('F', mktime(0,0,0,$m, 1, date('Y')));
            $monthFilter[$i]['display'] = $month;
            $monthFilter[$i]['value'] = $m;
            $i++;
        }

        $yearNow = date('Y');
        $yearFilter = array();
        $i = 0;
        for ($y=$yearNow; $y > $yearNow-10; $y--) {
            $yearFilter[$i]['display'] = $y;
            $yearFilter[$i]['value'] = $y;
            $i++;
        }

        $em = $this->getDoctrine()->getManager();

        $userData = $this->get('session')->get('userData');

        $forPft = $em->getRepository('RxConnexionBundle:PatientChartEntity')->dashboardForPfts($params, $this->get('session')->get('userData'));
        //$forPftSummaries = $em->getRepository('RxConnexionBundle:PatientChartEntity')->dashboardPftSummary($params, $this->get('session')->get('userData'));
        $healthFacilities = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->branchesForMultiple($userData);
        $encounterTypes = $em->getRepository('RxConnexionBundle:ChartTypeEntity')->findAll();

        $page_title = 'Patient Service (PFT)';
        return $this->render('@RxConnexion/Admin/Dashboard/pft.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'records' => $forPft,
            'monthFilter'  => $monthFilter,
            'yearFilter' => $yearFilter,
            'healthFacilities' => $healthFacilities,
            'encounterTypes' => $encounterTypes,
            'encounterType' => isset($params['encounterType']) ? $params['encounterType'] : 'All',
            'branch' => isset($params['branch']) ? $params['branch'] : 'All',
            'getYear' => isset($params['year']) ? $params['year'] : 'All',
            'getMonth' => isset($params['month']) ? $params['month'] : 'All'
        ));
    }

    /**
     * @Route(
     *      "/patient/pft/export_to_excel",
     *      name = "patient_pft_export_to_excel"
     * )
     */
    public function patient_pft_exportToExcelAction(Request $request) {
        $get = $request->query->all();
        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Dashboard Patient 6 Month Follow Up Excel'))) return $authService->redirectToHome();

        ini_set('memory_limit', '2048M');
        set_time_limit(0);

        $makeDate = "2000-1-1";
        $monthStart = date("n", strtotime($makeDate));
        $monthFilter = array();
        $i = 0;
        for ($m=$monthStart; $m < $monthStart+12; $m++) {
            $month = date('F', mktime(0,0,0,$m, 1, date('Y')));
            $monthFilter[$i]['display'] = $month;
            $monthFilter[$i]['value'] = $m;
            $i++;
        }

        $yearNow = date('Y');
        $yearFilter = array();
        $i = 0;
        for ($y=$yearNow; $y > $yearNow-10; $y--) {
            $yearFilter[$i]['display'] = $y;
            $yearFilter[$i]['value'] = $y;
            $i++;
        }

        $em = $this->getDoctrine()->getManager();
        $forPft = $em->getRepository('RxConnexionBundle:PatientChartEntity')->dashboardForPfts($get, $this->get('session')->get('userData'));

        ini_set('memory_limit', '2048M');
        set_time_limit(0);

        $cellsData[] = array('cell' => 'A1', 'data' => 'Patient Service (PFT) - No PFT Encounter');

        $columnRange = range('A', 'C');
        $cellsData = array(
            array('cell' => 'A1', 'data' => 'Branch'),
            array('cell' => 'B1', 'data' => 'Patient'),
            array('cell' => 'C1', 'data' => 'Latest Notes'),
        );
        $rowCtr = 1;
        $totalCount = 0;

        foreach($forPft['no_pft'] as $record) {

            $rowCtr++;
            $totalCount++;

            $cellsData[] = array('cell' => "A$rowCtr", 'data' => isset($record['healthFacility']) ? $record['healthFacility'] : '');
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => isset($record['fullName']) ? $record['fullName'] : '');
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => isset($record['note']) ? strip_tags($record['note']) : '');
        }

        $rowCtr++;
        $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Total Records: ' . $totalCount);

        $page_title = '6 Months Follow Up Report';
        return $this->export_to_excel($columnRange, $cellsData, $page_title);
    }


    /**
     * @Route(
     *      "/dashboard/my_tasks",
     *      name = "my_task"
     * )
     */
    public function my_taskAction(Request $request) {
        $get = $request->query->all();
        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Dashboard My Task'))) return $authService->redirectToHome();
        ini_set('memory_limit', '2048M');
        set_time_limit(0);

        $userData = $this->get('session')->get('userData');
        $em = $this->getDoctrine()->getManager();

	    $transferInventories = $em->getRepository(TransferInventoryEntity::class)->countForReceive($userData);
	    $myTasks = $em->getRepository('RxConnexionBundle:PatientChartEntity')->dashboardMyTasks($get, $userData);
        $myTasksFromTicket = $em->getRepository('RxConnexionBundle:TicketEntity')->dashboardMyTasks($userData);
	    $healthFacilities = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->branchesForMultiple($userData);
	    $reminders = $this->get_reminders($userData);

	    $page_title = 'My Tasks';
        return $this->render('@RxConnexion/Admin/Dashboard/my_task.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'records' => $myTasks,
            'records2' => $myTasksFromTicket,
            'reminders' => $reminders,
            'healthFacilities' => $healthFacilities,
            'branch' => isset($get['branch']) ? $get['branch'] : 'All',
            'reportParams' => http_build_query($get),
	        'transferInventories' => $transferInventories,
        ));
    }

    /**
     * @Route(
     *      "/dashboard/endorsed",
     *      name = "endorsed"
     * )
     */
    public function endorsedAction(Request $request) {
        $get = $request->query->all();
        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Dashboard Endorsed'))) return $authService->redirectToHome();

        ini_set('memory_limit', '2048M');
        set_time_limit(0);

        $em = $this->getDoctrine()->getManager();
        $defaultStatus = $em->getRepository('RxConnexionBundle:TicketStatusEntity')->findOneBy(array('description' => 'Endorsed'));
        $get['status'] = isset($get['status']) ? $get['status'] : ($defaultStatus ? $defaultStatus->getId() : '');
        $endorsedDetails = $em->getRepository('RxConnexionBundle:TicketEntity')->dashboardEndorsed($get, $this->get('session')->get('userData'));
        $accountUsers = $em->getRepository('RxConnexionBundle:AccountUserEntity')->findBy(array(
            'isActive' => 1
        ));

        foreach ($endorsedDetails AS $key => $endorsedDetail){
            if($endorsedDetail['patients'] != null){
                $patients = explode('~', $endorsedDetail['patients']);
                $patientsDetails = array();
                foreach($patients AS $patient){
                    $patientDetails = explode('|', $patient);
                    if(isset($patientDetails[0]) && isset($patientDetails[1]) && isset($patientDetails[2])){
                        $patientsDetails[] = array(
                            'fullName' => $patientDetails[0],
                            'id' => $patientDetails[1],
                            'branch' => $patientDetails[2]
                        );
                    }
                }
                $endorsedDetails[$key]['patientDetails'] = $patientsDetails;
            }else{
                $endorsedDetails[$key]['patientDetails'] = array();
            }
        }
        foreach ($endorsedDetails AS $key => $endorsedDetail){
            if($endorsedDetail['patientCharts'] != null){
                $patientCharts = explode('~', $endorsedDetail['patientCharts']);
                $patientChartsDetails = array();
                foreach($patientCharts AS $patientChart){
                    $patientChartDetails = explode('|', $patientChart);
                    if(isset($patientChartDetails[0]) && isset($patientChartDetails[1]) &&  isset($patientChartDetails[2]) &&   isset($patientChartDetails[3]) && isset($patientChartDetails[4])){
                        $patientChartsDetails[] = array(
                            'id' => $patientChartDetails[0],
                            'chartDate' => $patientChartDetails[1],
                            'chartType' => $patientChartDetails[2],
                            'patientId' => $patientChartDetails[3],
                            'patientFullName' => $patientChartDetails[4],
                        );
                    }
                }
                $endorsedDetails[$key]['patientChartDetails'] = $patientChartsDetails;
            }else{
                $endorsedDetails[$key]['patientChartDetails'] = array();
            }
        }
        $endorsedStatus = $em->getRepository('RxConnexionBundle:TicketStatusEntity')->findBy(array('isDeleted' => false));
        $severity = $em->getRepository('RxConnexionBundle:TicketSeverityEntity')->findBy(array('isDeleted' => false));
        $severitySelected = isset($get['severity']) && $get['severity'] != 'All' ? $em->getRepository('RxConnexionBundle:TicketSeverityEntity')->find($get['severity']) : null;

        $page_title = 'Endorsement';
        return $this->render('@RxConnexion/Admin/Dashboard/endorsed.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'records' => $endorsedDetails,
            'endorsedStatus' => $endorsedStatus,
            'severity' => $severity,
            'accountUsers' => $accountUsers,
            'status' => isset($get['status']) ? $get['status'] : ($defaultStatus ? $defaultStatus->getId() : ''),
            'severity_selected' => isset($get['severity']) && $get['severity'] != 'All' ? $severitySelected->getId() : 'All',
        ));
    }

    /**
     * @Route(
     *      "patient/create_ticket/form/{patient_id}",
     *      defaults = {
     *          "patient_id": 0
     *      },
     *      name = "patient_create_ticket_form"
     * )
     */
    public function patient_create_ticket_formAction($patient_id, Request $request) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();


        $em = $this->getDoctrine()->getManager();
        $ticketStatuses = $em->getRepository('RxConnexionBundle:TicketStatusEntity')->findBy(array('isDeleted' => false));
        $ticketSeverities = $em->getRepository('RxConnexionBundle:TicketSeverityEntity')->findBy(array('isDeleted' => false));
        $title = 'Update Status';

        $result['html'] =  $this->renderView('@RxConnexion/Admin/Dashboard/patient_create_ticket_form.html.twig', array(
            'title' => $title,
            'page_title' => $title,
            'patient_id' => $patient_id,
            'ticketStatuses' => $ticketStatuses,
            'ticketSeverities' => $ticketSeverities
        ));
        $result['success'] = true;
        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/patient_create_ticket/save_action",
     *      name = "patient_create_ticket_save"
     * )
     */
    public function patient_create_ticket_saveAction(Request $request) {

        $result['success'] = false;
        $result['successMessages'] = array();
        $result['errorMessages'] = array();

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        $em = $this->getDoctrine()->getManager();
        $form = $request->get('form');
        $errors = $em->getRepository('RxConnexionBundle:TicketEntity')->validateFromDashboard($form);

        if(!count($errors)) {
            $ticket = new TicketEntity();
            $ticketNote = new TicketNoteEntity();
            $ticketPatient = new PatientTicketEntity();
            $ticket->setAccountUser($em->getReference('RxConnexionBundle:AccountUserEntity', $form['accountUser']));
            $ticket->setTicketSeverity($em->getReference('RxConnexionBundle:TicketSeverityEntity', $form['severity']));
            $ticket->setTicketStatus($em->getReference('RxConnexionBundle:TicketStatusEntity', $form['status']));
            $em->persist($ticket);
            $ticketNote->setTicket($ticket);
            $ticketNote->setNote($form['note']);
            $em->persist($ticketNote);
            $ticketPatient->setTicket($ticket);
            $ticketPatient->setPatient($em->getReference('RxConnexionBundle:PatientEntity', $form['id']));
            $em->persist($ticketPatient);
            $em->flush();
            $patientNote = new PatientNoteEntity();
            $patientNote->setNote($form['note']);
            $patientNote->setPatient($ticketPatient->getPatient());
            $em->persist($patientNote);
            $newAT = new AuditTrailEntity(
                'Ticket',
                $em->getClassMetadata(TicketEntity::class)->getTableName(),
                AuditTrailEntity::AXN_NEW
            );
            $newAT->entity = $ticket;
            $newAT->parseDetails();
            $em->persist($newAT);
            $em->flush();
            $result['success'] = true;
            $result['successMessages'][] = 'Record Successfully Saved.';
        }
        else {

            foreach ($errors as $error) {
                $result['errorMessages'][] = $error;
            }
        }
        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/dashboard/letters",
     *      name = "dashboard_letters"
     * )
     */
    public function dashboard_lettersAction(Request $request) {
        $get = $request->query->all();

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Dashboard Letters'))) return $authService->redirectToHome();

        ini_set('memory_limit', '2048M');
        set_time_limit(0);

        $em = $this->getDoctrine()->getManager();
        $userData = $this->get('session')->get('userData');
        $patientLetters = $em->getRepository('RxConnexionBundle:PatientLetterEntity')->dashboardPatientLettersNotSent($get, $this->get('session')->get('userData'));
        $healthFacilities = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->branchesForMultiple($userData);

        $page_title = 'Letters';
        return $this->render('@RxConnexion/Admin/Dashboard/letters.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'records' => $patientLetters,
            'healthFacilities' => $healthFacilities,
            'branch' => isset($get['branch']) ? $get['branch'] : 'All'
        ));
    }


    /**
     * @Route(
     *      "/dashboard/clinician",
     *      name = "dashboard_clinician_preview"
     * )
     */
    public function dashboard_clinician_previewAction(Request $request) {
        $get = $request->query->all();
        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Clinician Dashboard'))) return $authService->redirectToHome();

        ini_set('memory_limit', '2048M');
        set_time_limit(0);

        $authService = $this->get('rx_connexion.authService');
        $userData = $this->get('session')->get('userData');

        $page_title = 'Clinician Dashboard';
        return $this->render('@RxConnexion/Admin/Dashboard/clinician_dashboard.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'userData' => $userData,
            'javascripts' => array('rxconnexion/admin/js/clinicianDashboard/clinicianDashboard.js?v=1.0.7'),
            'stylesheets' => array('rxconnexion/admin/css/admin/index.css?v=1.0.1'),
        ));
    }

    /**
     * @Route(
     *      "/dashboard/cbt",
     *      name = "cbt_dashboard"
     * )
     */
    public function cbt_dashboardAction(Request $request) {
        $get = $request->query->all();
        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Clinician Dashboard'))) return $authService->redirectToHome();

        ini_set('memory_limit', '2048M');
        set_time_limit(0);

        $authService = $this->get('rx_connexion.authService');
        $userData = $this->get('session')->get('userData');

        $page_title = 'Clinician Dashboard';
        return $this->render('@RxConnexion/Admin/Dashboard/cbt_dashboard.html.twig', array(
            'title' => 'CBT Dashboad',
            'page_title' => 'CBT Dashboad',
            'userData' => $userData,            
            'stylesheets' => array('rxconnexion/admin/css/admin/index.css?v=1.0.1'),
        ));
    }

    /**
     * @Route("/clinician_dashboard_count/{provider_id}", name="clinician_dashboard_count")
     */
    public function clinicianDashboardCount($provider_id, Request $request){

        $dashboardData = $this->get('rx_connexion.dashboardService')->getClinicianDashboardData($provider_id);

        $json = array(
            'appointments' => $dashboardData['appointments'],
            'insurance_package' => $dashboardData['insurance_package'],
            'appointments_pending_update' => $dashboardData['appointments_pending_update'],
            'tickets' => $dashboardData['tickets'],
            'reminders' => $dashboardData['reminders'],
            'clinician_letters' => $dashboardData['clinician_letters'],
            'encounter_overdue' => $dashboardData['encounter_overdue'],
        );

        return new JsonResponse($json);
    }

    //Private Functions Here
    private function export_to_excel($columnRange, $cellsData, $page_title, $customStyle=array()) {

        $phpExcelObject = $this->get('phpexcel')->createPHPExcelObject();
        $activeSheet = $phpExcelObject->setActiveSheetIndex(0);

        foreach($cellsData as $cellData) {
            $activeSheet->setCellValue($cellData['cell'], $cellData['data']);
        }

        //foreach($columnRange as $column) {
        //    $phpExcelObject->getActiveSheet()->getColumnDimension($column)->setAutoSize(true);
        //}

        $activeSheet->getStyle($columnRange[0] . '1:' . $columnRange[count($columnRange) - 1] . '1')->applyFromArray(array(
            'fill' => array(
                'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                'color' => array('rgb' => 'ADD8E6')
            ),
            'font' => array(
                'bold' => true,
                'color' => array('rgb' => '000000')
            )
        ));

        foreach($customStyle as $cs) {
            $activeSheet->getStyle($cs['cell'])->applyFromArray($cs['style']);
        }

        $phpExcelObject->getActiveSheet()->setTitle(str_replace(':', '-', $page_title));
        // Set active sheet index to the first sheet, so Excel opens this as the first sheet
        $phpExcelObject->setActiveSheetIndex(0);

        // create the writer
        $writer = $this->get('phpexcel')->createWriter($phpExcelObject, 'Excel5');
        // create the response
        $response = $this->get('phpexcel')->createStreamedResponse($writer);
        // adding headers
        $response->headers->set('Content-Type', 'text/vnd.ms-excel; charset=utf-8');
        $response->headers->set('Content-Disposition', 'attachment;filename="' . $page_title . '.xls"');
        $response->headers->set('Pragma', 'public');
        $response->headers->set('Cache-Control', 'maxage=1');

        return $response;
    }

    private function get_reminders($userData){
        $em = $this->getDoctrine()->getManager();
        $accountUser = $em->getRepository('RxConnexionBundle:AccountUserEntity')->find($userData['id']);
        $userGroups = $accountUser->getUserGroupIdsAsArray();

        $accountUserReminders = $em->getRepository('RxConnexionBundle:AccountUserReminderEntity')->findBy(array(
            'accountUser' => $userData['id'],
            'isDeleted' => false,
            'status' => 'Pending',
        ));
        $assignedAccountUserReminders = $em->getRepository('RxConnexionBundle:AccountUserReminderEntity')->findBy(array(
            'assignedToAccountUser' => $userData['id'],
            'isDeleted' => false,
            'status' => 'Pending',
        ));
        $assignedUserGroupReminders = $em->getRepository('RxConnexionBundle:AccountUserReminderEntity')->findAssignedToUserGroup($userGroups);
        $reminders = array();
        foreach($accountUserReminders as $accountUserReminder){
            $exists = $this->in_array_assoc($accountUserReminder->getId(), 'id', $reminders);
            if(!$exists['exist']){
                $reminders[] = array(
                    'id' => $accountUserReminder->getId(),
                    'assigner' => $accountUserReminder->getAccountUser()->getFullName(),
                    'assigner_id' => $accountUserReminder->getAccountUser()->getId(),
                    'assignedTo' => $accountUserReminder->getAssignedToAccountUser() ? $accountUserReminder->getAssignedToAccountUser()->getFullName() : '',
                    'assignedTo_id' => $accountUserReminder->getAssignedToAccountUser() ? $accountUserReminder->getAssignedToAccountUser()->getId() : '',
                    'assignedToUserGroup' => $accountUserReminder->getAssignedToUserGroup() ? $accountUserReminder->getAssignedToUserGroup()->getDescription() : '',
                    'assignedToUserGroup_id' => $accountUserReminder->getAssignedToUserGroup() ? $accountUserReminder->getAssignedToUserGroup()->getId() : '',
                    'reminderType_description' => $accountUserReminder->getReminderType()->getDescription(),
                    'note' => $accountUserReminder->getNote(),
                    'startDate' => $accountUserReminder->getStartDateAsString(),
                    'endDate' => $accountUserReminder->getEndDateAsString(),
                );
            }
        }
        foreach($assignedAccountUserReminders as $assignedAccountUserReminder){
            $exists = $this->in_array_assoc($assignedAccountUserReminder->getId(), 'id', $reminders);
            if(!$exists['exist']){
                $reminders[] = array(
                    'id' => $assignedAccountUserReminder->getId(),
                    'assigner' => $assignedAccountUserReminder->getAccountUser()->getFullName(),
                    'assigner_id' => $assignedAccountUserReminder->getAccountUser()->getId(),
                    'assignedTo' => $assignedAccountUserReminder->getAssignedToAccountUser() ? $assignedAccountUserReminder->getAssignedToAccountUser()->getFullName() : '',
                    'assignedTo_id' => $assignedAccountUserReminder->getAssignedToAccountUser() ? $assignedAccountUserReminder->getAssignedToAccountUser()->getId() : '',
                    'assignedToUserGroup' => $assignedAccountUserReminder->getAssignedToUserGroup() ? $assignedAccountUserReminder->getAssignedToUserGroup()->getDescription() : '',
                    'assignedToUserGroup_id' => $assignedAccountUserReminder->getAssignedToUserGroup() ? $assignedAccountUserReminder->getAssignedToUserGroup()->getId() : '',
                    'reminderType_description' => $assignedAccountUserReminder->getReminderType()->getDescription(),
                    'note' => $assignedAccountUserReminder->getNote(),
                    'startDate' => $assignedAccountUserReminder->getStartDateAsString(),
                    'endDate' => $assignedAccountUserReminder->getEndDateAsString(),
                );
            }
        }
        foreach($assignedUserGroupReminders as $assignedUserGroupReminder){
            $exists = $this->in_array_assoc($assignedUserGroupReminder->getId(), 'id', $reminders);
            if(!$exists['exist']){
                $reminders[] = array(
                    'id' => $assignedUserGroupReminder->getId(),
                    'assigner' => $assignedUserGroupReminder->getAccountUser()->getFullName(),
                    'assigner_id' => $assignedUserGroupReminder->getAccountUser()->getId(),
                    'assignedTo' => $assignedUserGroupReminder->getAssignedToAccountUser() ? $assignedUserGroupReminder->getAssignedToAccountUser()->getFullName() : '',
                    'assignedTo_id' => $assignedUserGroupReminder->getAssignedToAccountUser() ? $assignedUserGroupReminder->getAssignedToAccountUser()->getId() : '',
                    'assignedToUserGroup' => $assignedUserGroupReminder->getAssignedToUserGroup() ? $assignedUserGroupReminder->getAssignedToUserGroup()->getDescription() : '',
                    'assignedToUserGroup_id' => $assignedUserGroupReminder->getAssignedToUserGroup() ? $assignedUserGroupReminder->getAssignedToUserGroup()->getId() : '',
                    'reminderType_description' => $assignedUserGroupReminder->getReminderType()->getDescription(),
                    'note' => $assignedUserGroupReminder->getNote(),
                    'startDate' => $assignedUserGroupReminder->getStartDateAsString(),
                    'endDate' => $assignedUserGroupReminder->getEndDateAsString(),
                );
            }
        }
        return $reminders;
    }

    private function in_array_assoc($val, $key, $arr) {
        $in_array = array('exist' => false, 'key' => 0);
        foreach($arr as $rowKey => $row) {
            if($row[$key]==$val) {
                $in_array['exist'] = true;
                $in_array['key'] = $rowKey;
                break;
            }
        }
        return $in_array;
    }
}