<?php

namespace RxConnexionBundle\Controller;

use RxConnexionBundle\Entity\AccountUserEntity;
use RxConnexionBundle\Entity\FaxTranEntity;
use RxConnexionBundle\Entity\FaxTranOutboundEntity;
use RxConnexionBundle\Entity\PatientLetterEntity;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;

/**
 * @Route("/main/report")
 */
class ReportController extends Controller
{
    /**
     * @Route("/patient", name="report_patient")
     */
    public function patientAction() {

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

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

        $em = $this->getDoctrine()->getManager();
        $branch = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->branchesForMultiple($userData);
        $company = $em->getRepository('RxConnexionBundle:CompanyEntity')->companiesForMultiple($userData);

        $page_title = 'Patient Report';
        return $this->render('@RxConnexion/Report/Patient/index.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'company' => $company,
            'branch' => $branch,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/patient/patient.js')
        ));
    }

    /**
     * @Route(
     *      "/patient/preview/{company_id}/{branch_id}/{insurance}/{status}/{province_id}/{postal_code_id}/{referring_health_facility}/{referring_provider}",
     *      name = "report_patient_preview"
     * )
     */
    public function patient_previewAction($company_id, $branch_id, $insurance, $status, $province_id, $postal_code_id, $referring_health_facility, $referring_provider) {

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

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientEntity')->reportPatient(array(
            'company' => $company_id,
            'branch' => $branch_id,
            'insurance' => $insurance,
            'status' => $status,
            'province' => $province_id,
            'postal_code' => $postal_code_id,
            'patientReferringAffiliate' => $referring_health_facility,
            'patientReferringProvider' => $referring_provider,
            'userData' => $userData
        ));

        $summary = array(
            'branch' => array(),
            'active' => array(),
            'province' => array(),
            'postal_code' => array(),
        );

        $status_active = 0;
        $status_inactive = 0;
        $status_count = array();
        foreach ($records as $record) {
            //branch
            if(isset($summary['branch'][$record['patientBranch']])){
                if(isset($summary['branch'][$record['patientBranch']])) {
                    $summary['branch'][$record['patientBranch']]++;
                }
                else {
                    $summary['branch'][$record['patientBranch']] = 1;
                }
            } else {
                $summary['branch'] = array(
                    $record['patientBranch'] => 1
                );
            }

            //active
            if($record['is_active'] == 1) {
                $status_active++;
            }

            if($record['is_active'] == 0) {
                $status_inactive++;
            }

            $status_count = array(
                'active' => $status_active,
                'inactive' => $status_inactive
            );

            //province
            if(isset($summary['province'][$record['patientProvince']])){
                if(isset($summary['province'][$record['patientProvince']])) {
                    $summary['province'][$record['patientProvince']]++;
                }
                else {
                    $summary['province'][$record['patientProvince']] = 1;
                }
            } else {
                $summary['province'] = array(
                    $record['patientProvince'] => 1
                );
            }

            //postal
            if(isset($summary['postal_code'][$record['postalCode']])){
                if(isset($summary['postal_code'][$record['postalCode']])) {
                    $summary['postal_code'][$record['postalCode']]++;
                }
                else {
                    $summary['postal_code'][$record['postalCode']] = 1;
                }
            } else {
                $summary['postal_code'] = array(
                    $record['postalCode'] => 1
                );
            }
        }

        $page_title = 'Patient Report';
        return $this->render('@RxConnexion/Report/Patient/preview.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'javascripts' => array('rxconnexion/admin/js/report/report_preview.js'),
            'records' => $records,
            'summary' => $summary,
            'active_count' => $status_count,
            'sum_branch' => $branch_id,
            'sum_stat' => $status,
            'sum_prov' => $province_id,
            'sum_post' => $postal_code_id
        ));
    }

    /**
     * @Route(
     *      "/patient/export_to_pdf/{company_id}/{branch_id}/{insurance}/{status}/{province_id}/{postal_code_id}",
     *      name = "report_patient_export_to_pdf"
     * )
     */
    public function patient_export_to_pdfAction($company_id, $branch_id, $insurance, $status, $province_id, $postal_code_id) {

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

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientEntity')->reportPatient(array(
            'company' => $company_id,
            'branch' => $branch_id,
            'insurance' => $insurance,
            'status' => $status,
            'province' => $province_id,
            'postal_code' => $postal_code_id,
            'userData' => $userData
        ));

        $summary = array(
            'branch' => array(),
            'active' => array(),
            'province' => array(),
            'postal_code' => array(),
        );

        $status_active = 0;
        $status_inactive = 0;
        $status_count = array();
        foreach ($records as $record) {
            //branch
            if(isset($summary['branch'][$record['patientBranch']])){
                if(isset($summary['branch'][$record['patientBranch']])) {
                    $summary['branch'][$record['patientBranch']]++;
                }
                else {
                    $summary['branch'][$record['patientBranch']] = 1;
                }
            } else {
                $summary['branch'] = array(
                    $record['patientBranch'] => 1
                );
            }

            //active
            if($record['is_active'] == 1) {
                $status_active++;
            }

            if($record['is_active'] == 0) {
                $status_inactive++;
            }

            $status_count = array(
                'active' => $status_active,
                'inactive' => $status_inactive
            );

            //province
            if(isset($summary['province'][$record['patientProvince']])){
                if(isset($summary['province'][$record['patientProvince']])) {
                    $summary['province'][$record['patientProvince']]++;
                }
                else {
                    $summary['province'][$record['patientProvince']] = 1;
                }
            } else {
                $summary['province'] = array(
                    $record['patientProvince'] => 1
                );
            }

            //postal
            if(isset($summary['postal_code'][$record['postalCode']])){
                if(isset($summary['postal_code'][$record['postalCode']])) {
                    $summary['postal_code'][$record['postalCode']]++;
                }
                else {
                    $summary['postal_code'][$record['postalCode']] = 1;
                }
            } else {
                $summary['postal_code'] = array(
                    $record['postalCode'] => 1
                );
            }
        }

        $page_title = 'Patient Report';
        $content = $this->renderView('@RxConnexion/Report/Patient/preview.wkpdf.twig', array(
            'page_title' => $page_title,
            'records' => $records,
            'summary' => $summary,
            'active_count' => $status_count,
            'sum_branch' => $branch_id,
            'sum_stat' => $status,
            'sum_prov' => $province_id,
            'sum_post' => $postal_code_id
        ));

        $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content, array(
            'dpi' => 72,
            // 'disable-smart-shrinking',
            'zoom' => 'LINUX' == strtoupper(PHP_OS) ? 0.78 : 1
        ));

        $pdfResponse = array(
            'success' => true,
            'msg' => 'PDF was successfully generated.',
            'pdfBase64' => base64_encode($xml)
        );
        if($pdfResponse['success']) {
            $pdfContent = $pdfResponse['pdfBase64'];
            return new Response(base64_decode($pdfContent), 200, array(
                'Content-Type' => 'application/pdf',
                'Content-Disposition'   => 'attachment; filename="Patient Report' . date('m/d/Y') . ' Details.pdf"'
            ));
        } else {
            $this->get('session')->getFlashBag()->set('error_messages', $pdfResponse['msg']);
            return $this->redirect($this->generateUrl('report_patient', 302));
        }
    }

    /**
     * @Route(
     *      "/patient/export_to_excel/{company_id}/{branch_id}/{insurance}/{status}/{province_id}/{postal_code_id}",
     *      name = "report_patient_export_to_excel"
     * )
     */
    public function patient_export_to_excelAction($company_id, $branch_id, $insurance, $status, $province_id, $postal_code_id) {

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

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientEntity')->reportPatient(array(
            'company' => $company_id,
            'branch' => $branch_id,
            'insurance' => $insurance,
            'status' => $status,
            'province' => $province_id,
            'postal_code' => $postal_code_id,
            'userData' => $userData
        ));

        $columnRange = range('A', 'H');
        $cellsData = array(
            array('cell' => 'A1', 'data' => 'Patient'),
            array('cell' => 'B1', 'data' => 'City'),
            array('cell' => 'C1', 'data' => 'Province'),
            array('cell' => 'D1', 'data' => 'Postal Code'),
            array('cell' => 'E1', 'data' => 'Branch'),
            array('cell' => 'F1', 'data' => 'Company'),
            array('cell' => 'G1', 'data' => 'Patient Insurance'),
            array('cell' => 'H1', 'data' => 'Status'),
        );
        $rowCtr = 1;
        $totalCount = 0;

        foreach($records as $record) {

            $rowCtr++;
            $totalCount++;

            $cellsData[] = array('cell' => "A$rowCtr", 'data' => $record['fullName']);
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => $record['cityDesc']);
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => $record['patientProvince']);
            $cellsData[] = array('cell' => "D$rowCtr", 'data' => $record['postalCode']);
            $cellsData[] = array('cell' => "E$rowCtr", 'data' => $record['patientBranch']);
            $cellsData[] = array('cell' => "F$rowCtr", 'data' => $record['companyDesc']);
            $cellsData[] = array('cell' => "G$rowCtr", 'data' => $record['patientInsurance']);
            $cellsData[] = array('cell' => "H$rowCtr", 'data' => $record['is_active'] ? 'Active' : 'Inactive');
        }

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


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

    /**
     * @Route("/appointment/redirect/{dateFrom}/{dateTo}",
     *      defaults = {
     *          "dateFrom":  "null",
     *          "dateTo":  "null",
     *      },
     *
     *      name = "report_appointment_redirect_preview"),
     */
    public function scheduleRedirectAction($dateFrom, $dateTo) {
        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();

        $em = $this->getDoctrine()->getManager();
        $scheduleStatus = $em->getRepository('RxConnexionBundle:ScheduleStatusEntity')->findOneBy(array(
              'description' => 'Booked'
        ));

        return $this->redirect($this->generateUrl('report_appointment_preview', array(
            'dateFrom' => $dateFrom,
            'dateTo' => $dateTo,
            'patient_id' => 'null',
            'provider_id' => 'null',
            'company_id' => 'null',
            'healthFacility_id' => 'null',
            'status_id' => $scheduleStatus->getId(),
            'user_id' => 'null',
        )));
    }


    /**
     * @Route("/appointment", name="report_schedule")
     */
    public function scheduleAction() {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Appointment Preview'))) return $authService->redirectToHome();
        $em = $this->getDoctrine()->getManager();
        $scheduleStatuses = $em->getRepository('RxConnexionBundle:ScheduleStatusEntity')->findAll();
        $session = $this->get('session');
        $userData = $session->get('userData');

        $company = $em->getRepository('RxConnexionBundle:CompanyEntity')->companiesForMultiple($userData);
        $branch = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->branchesForMultiple($userData);
        $clinicians = $em->getRepository('RxConnexionBundle:ProviderEntity')->clinicianForMultiple();

        $page_title = 'Appointment Report';
        return $this->render('@RxConnexion/Report/Schedule/index.html.twig', array(
            'title' => $page_title,
            'company' => $company,
            'branch' => $branch,
            'clinician' => $clinicians,
            'page_title' => $page_title,
            'scheduleStatuses' => $scheduleStatuses,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/schedule/schedule.js')
        ));
    }

    /**
     * @Route(
     *      "/appointment/preview/{dateFrom}/{dateTo}/{patient_id}/{provider_id}/{company_id}/{healthFacility_id}/{status_id}/{user_id}",
     *      name = "report_appointment_preview"
     * )
     */
    public function appointment_previewAction($dateFrom, $dateTo, $patient_id, $provider_id, $company_id, $healthFacility_id, $status_id, $user_id) {

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

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:ScheduleEntity')->reportSchedule(array(
            'dateFrom' => $dateFrom,
            'dateTo' => $dateTo,
            'patient_id' => $patient_id,
            'clinician' => $provider_id,
            'company' => $company_id,
            'branch' => $healthFacility_id,
            'status_id' => $status_id,
            'user_id' => $user_id,
            'userData' => $userData
        ));

        $summary = array(
            'clinicians' => array()
        );

        foreach($records as $record) {
            if(isset($summary['clinicians'][$record['clinician']])) {
                if (isset($summary['clinicians'][$record['clinician']][$record['chartType']][$record['scheduleStatus']])) {
                    $summary['clinicians'][$record['clinician']][$record['chartType']][$record['scheduleStatus']]++;
                } else {
                    $summary['clinicians'][$record['clinician']][$record['chartType']][$record['scheduleStatus']] = 1;
                }

            } else {
                $summary['clinicians'][$record['clinician']][$record['chartType']] = array(
                    $record['scheduleStatus'] => 1
                );
            }
        }

        $page_title = 'Appointment Report';
        return $this->render('@RxConnexion/Report/Schedule/preview.html.twig', array(
            'title' => $page_title,
            'date_from' => $dateFrom,
            'date_to' => $dateTo,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'javascripts' => array('rxconnexion/admin/js/report/report_preview.js'),
            'records' => $records,
            'apptSummary' => $summary
        ));
    }

    /**
     * @Route(
     *      "/appointment/export_to_pdf/{dateFrom}/{dateTo}/{patient_id}/{provider_id}/{company_id}/{healthFacility_id}/{status_id}/{user_id}",
     *      name = "report_appointment_export_to_pdf"
     * )
     */
    public function appointment_export_to_pdfAction($dateFrom, $dateTo, $patient_id, $provider_id, $company_id, $healthFacility_id, $status_id, $user_id) {

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

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:ScheduleEntity')->reportSchedule(array(
            'dateFrom' => $dateFrom,
            'dateTo' => $dateTo,
            'patient_id' => $patient_id,
            'clinician' => $provider_id,
            'company' => $company_id,
            'branch' => $healthFacility_id,
            'status_id' => $status_id,
            'user_id' => $user_id,
            'userData' => $userData
        ));

        $page_title = 'Appointment Report';
        $content = $this->renderView('@RxConnexion/Report/Schedule/preview.wkpdf.twig', array(
            'title' => $page_title,
            'date_from' => $dateFrom,
            'date_to' => $dateTo,
            'page_title' => $page_title,
            'records' => $records
        ));

        $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content, array(
            'dpi' => 72,
            // 'disable-smart-shrinking',
            'zoom' => 'LINUX' == strtoupper(PHP_OS) ? 0.78 : 1
        ));

        $pdfResponse = array(
            'success' => true,
            'msg' => 'PDF was successfully generated.',
            'pdfBase64' => base64_encode($xml)
        );
        if($pdfResponse['success']) {
            $pdfContent = $pdfResponse['pdfBase64'];
            return new Response(base64_decode($pdfContent), 200, array(
                'Content-Type' => 'application/pdf',
                'Content-Disposition'   => 'attachment; filename="Appointment Report' . date('m/d/Y') . ' Details.pdf"'
            ));
        } else {
            $this->get('session')->getFlashBag()->set('error_messages', $pdfResponse['msg']);
            return $this->redirect($this->generateUrl('report_schedule', 302));
        }
    }

    /**
     * @Route(
     *      "/appointment/export_to_excel/{dateFrom}/{dateTo}/{patient_id}/{provider_id}/{company_id}/{healthFacility_id}/{status_id}/{user_id}",
     *      name = "report_appointment_export_to_excel"
     * )
     */
    public function appointment_export_to_excelAction($dateFrom, $dateTo, $patient_id, $provider_id, $company_id, $healthFacility_id, $status_id, $user_id) {

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

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:ScheduleEntity')->reportSchedule(array(
            'dateFrom' => $dateFrom,
            'dateTo' => $dateTo,
            'patient_id' => $patient_id,
            'clinician' => $provider_id,
            'company' => $company_id,
            'branch' => $healthFacility_id,
            'status_id' => $status_id,
            'user_id' => $user_id,
            'userData' => $userData
        ));

        $columnRange = range('A', 'L');
        $cellsData = array(
            array('cell' => 'A1', 'data' => 'Schedule ID'),
            array('cell' => 'B1', 'data' => 'Schedule Date'),
            array('cell' => 'C1', 'data' => 'Time'),
            array('cell' => 'D1', 'data' => 'Schedule Status'),
            array('cell' => 'E1', 'data' => 'Patient'),
            array('cell' => 'F1', 'data' => 'Company'),
            array('cell' => 'G1', 'data' => 'Branch'),
            array('cell' => 'H1', 'data' => 'Clinician'),
            array('cell' => 'I1', 'data' => 'Encounter Type'),
            array('cell' => 'J1', 'data' => 'Encounter Status'),
            array('cell' => 'K1', 'data' => 'Created By')
        );
        $rowCtr = 1;
        $totalCount = 0;

        foreach($records as $record) {

            $rowCtr++;
            $totalCount++;

            $cellsData[] = array('cell' => "A$rowCtr", 'data' => $record['scheduleId']);
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => $record['startTime'].' - '.$record['endTime']);
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => $record['patient']);
            $cellsData[] = array('cell' => "D$rowCtr", 'data' => $record['scheduleDate']);
            $cellsData[] = array('cell' => "E$rowCtr", 'data' => $record['patient']);
            $cellsData[] = array('cell' => "F$rowCtr", 'data' => $record['companyDesc']);
            $cellsData[] = array('cell' => "G$rowCtr", 'data' => $record['branch']);
            $cellsData[] = array('cell' => "H$rowCtr", 'data' => $record['clinician']);
            $cellsData[] = array('cell' => "I$rowCtr", 'data' => $record['chartType']);
            $cellsData[] = array('cell' => "J$rowCtr", 'data' => $record['chartStatus']);
            $cellsData[] = array('cell' => "K$rowCtr", 'data' => $record['user']);
        }

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


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

    //Affiliation Report
    /**
     * @Route("/affiliation", name="report_affiliation")
     */
    public function medical_institutionAction() {

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

        $page_title = 'Affiliation Report';
        return $this->render('@RxConnexion/Report/Medical_Institution/index.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/medical-institution/medical_institution.js')
        ));
    }

    /**
     * @Route(
     *      "/affiliation/preview/{affiliate_id}/{referring_affiliate_id}/{sales_agent_id}",
     *      name = "report_medical_institution_preview"
     * )
     */
    public function medical_institution_previewAction($affiliate_id, $referring_affiliate_id, $sales_agent_id) {

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->reportMedicalInstitution(array(
            'affiliate' => $affiliate_id,
            'referringAffiliate' => $referring_affiliate_id,
            'salesAgent' => $sales_agent_id
        ));

        $page_title = 'Affiliation Report';
        return $this->render('@RxConnexion/Report/Medical_Institution/preview.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'javascripts' => array('rxconnexion/admin/js/report/report_preview.js'),
            'records' => $records
        ));
    }

    /**
     * @Route(
     *      "/affiliation/export_to_pdf/{affiliate_id}/{referring_affiliate_id}/{sales_agent_id}",
     *      name = "report_medical_institution_export_to_pdf"
     * )
     */
    public function medical_institution_export_to_pdfAction($affiliate_id, $referring_affiliate_id, $sales_agent_id) {

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->reportMedicalInstitution(array(
            'affiliate' => $affiliate_id,
            'referringAffiliate' => $referring_affiliate_id,
            'salesAgent' => $sales_agent_id
        ));

        $page_title = 'Affiliation Report';
        $content = $this->renderView('@RxConnexion/Report/Medical_Institution/preview.wkpdf.twig', array(
            'page_title' => $page_title,
            'records' => $records
        ));

        $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content, array(
            'orientation'=>'Landscape',
            'dpi' => 72,
            // 'disable-smart-shrinking',
            'zoom' => 'LINUX' == strtoupper(PHP_OS) ? 0.78 : 1
        ));

        $pdfResponse = array(
            'success' => true,
            'msg' => 'PDF was successfully generated.',
            'pdfBase64' => base64_encode($xml)
        );
        if($pdfResponse['success']) {
            $pdfContent = $pdfResponse['pdfBase64'];
            return new Response(base64_decode($pdfContent), 200, array(
                'Content-Type' => 'application/pdf',
                'Content-Disposition'   => 'attachment; filename="Affiliation Report' . date('m/d/Y') . ' Details.pdf"'
            ));
        } else {
            $this->get('session')->getFlashBag()->set('error_messages', $pdfResponse['msg']);
            return $this->redirect($this->generateUrl('report_medical_institution', 302));
        }
    }

    /**
     * @Route(
     *      "/affiliation/export_to_excel/{affiliate_id}/{referring_affiliate_id}/{sales_agent_id}",
     *      name = "report_medical_institution_export_to_excel"
     * )
     */
    public function medical_institution_export_to_excelAction($affiliate_id, $referring_affiliate_id, $sales_agent_id) {

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->reportMedicalInstitution(array(
            'affiliate' => $affiliate_id,
            'referringAffiliate' => $referring_affiliate_id,
            'salesAgent' => $sales_agent_id
        ));

        $columnRange = range('A', 'Z');
        $cellsData = array(
            array('cell' => 'A1', 'data' => 'Affiliate'),
            array('cell' => 'B1', 'data' => 'Referring Affiliate'),
            array('cell' => 'C1', 'data' => 'Address'),
            array('cell' => 'D1', 'data' => 'Mobile No.(s)'),
            array('cell' => 'E1', 'data' => 'Tel No.(s)'),
            array('cell' => 'F1', 'data' => 'Email'),
            array('cell' => 'G1', 'data' => 'Sales Agent'),
        );
        $rowCtr = 1;
        $totalCount = 0;

        foreach($records as $record) {

            $rowCtr++;
            $totalCount++;

            $cellsData[] = array('cell' => "A$rowCtr", 'data' => $record['affiliate']);
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => $record['referring_affiliate']);
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => $record['address']);
            $cellsData[] = array('cell' => "D$rowCtr", 'data' => $record['mobile_no'].($record['mobile_no_two'] != '' ?  ' / '.$record['mobile_no_two'] : ''));
            $cellsData[] = array('cell' => "D$rowCtr", 'data' => $record['phone_no'].($record['phone_no_two'] != '' ?  ' / '.$record['phone_no_two'] : ''));
            $cellsData[] = array('cell' => "F$rowCtr", 'data' => $record['email']);
            $cellsData[] = array('cell' => "G$rowCtr", 'data' => $record['salesAgent']);
        }

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


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

    //Medication Report
    /**
     * @Route("/medication", name="report_medication")
     */
    public function medicationAction() {

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

        $page_title = 'Medication Report';
        return $this->render('@RxConnexion/Report/Medication/index.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/medication/medication.js')
        ));
    }

    /**
     * @Route(
     *      "/medication/preview/{patient_id}/{medication_id}/{medication_type}",
     *      name = "report_medication_preview"
     * )
     */
    public function medication_previewAction($patient_id, $medication_id, $medication_type) {

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:MedicationEntity')->reportMedication(array(
            'patient_id' => $patient_id,
            'medication_id' => $medication_id,
            'medication_type' => $medication_type
        ));

        $page_title = 'Medication Report';
        return $this->render('@RxConnexion/Report/Medication/preview.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'javascripts' => array('rxconnexion/admin/js/report/report_preview.js'),
            'records' => $records
        ));
    }

    /**
     * @Route(
     *      "/medication/export_to_pdf/{patient_id}/{medication_id}/{medication_type}",
     *      name = "report_medication_export_to_pdf"
     * )
     */
    public function medication_export_to_pdfAction($patient_id, $medication_id, $medication_type) {

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:MedicationEntity')->reportMedication(array(
            'patient_id' => $patient_id,
            'medication_id' => $medication_id,
            'medication_type' => $medication_type
        ));

        $page_title = 'Medication Report';
        $content = $this->renderView('@RxConnexion/Report/Medication/preview.wkpdf.twig', array(
            'page_title' => $page_title,
            'records' => $records
        ));

        $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content, array(
            'dpi' => 72,
            // 'disable-smart-shrinking',
            'zoom' => 'LINUX' == strtoupper(PHP_OS) ? 0.78 : 1
        ));

        $pdfResponse = array(
            'success' => true,
            'msg' => 'PDF was successfully generated.',
            'pdfBase64' => base64_encode($xml)
        );
        if($pdfResponse['success']) {
            $pdfContent = $pdfResponse['pdfBase64'];
            return new Response(base64_decode($pdfContent), 200, array(
                'Content-Type' => 'application/pdf',
                'Content-Disposition'   => 'attachment; filename="Medication Report' . date('m/d/Y') . ' Details.pdf"'
            ));
        } else {
            $this->get('session')->getFlashBag()->set('error_messages', $pdfResponse['msg']);
            return $this->redirect($this->generateUrl('report_medication', 302));
        }
    }

    /**
     * @Route(
     *      "/medication/export_to_excel/{patient_id}/{medication_id}/{medication_type}",
     *      name = "report_medication_export_to_excel"
     * )
     */
    public function medication_export_to_excelAction($patient_id, $medication_id, $medication_type) {

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:MedicationEntity')->reportMedication(array(
            'patient_id' => $patient_id,
            'medication_id' => $medication_id,
            'medication_type' => $medication_type
        ));

        $columnRange = range('A', 'L');
        $cellsData = array(
            array('cell' => 'A1', 'data' => 'Patient'),
            array('cell' => 'B1', 'data' => 'Diagnosis'),
            array('cell' => 'C1', 'data' => 'Medication Type'),
            array('cell' => 'D1', 'data' => 'Medication'),
        );
        $rowCtr = 1;
        $totalCount = 0;

        foreach($records as $record) {

            $rowCtr++;
            $totalCount++;

            $cellsData[] = array('cell' => "A$rowCtr", 'data' => $record['patientName']);
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => $record['diagnosis']);
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => $record['medication_type']);
            $cellsData[] = array('cell' => "D$rowCtr", 'data' => $record['medication']);
        }

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


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

    /**
     * @Route(
     *      "/encounter/redirect/preview/{date_from}/{date_to}/{company_id}/{branch_id}/{provider_id}/{chart_type_id}/{chart_status_id}",
     *      defaults = {
     *          "date_from":  "null",
     *          "date_to":  "null",
     *          "company_id":  "null",
     *          "branch_id":  "null",
     *          "provider_id":  "null",
     *          "chart_type_id":  "null",
     *          "chart_status_id":  "null",
     *      },
     *
     *      name = "report_encounter_redirect_preview",
     *
     * )
     */
    public function encounter_redirect_previewAction($date_from, $date_to, $company_id, $branch_id, $provider_id, $chart_type_id, $chart_status_id) {

        return $this->redirect($this->generateUrl('report_encounter_preview', array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company_id' => $company_id,
            'branch_id' => $branch_id,
            'provider_id' => $provider_id,
            'encountertype_id' => $chart_type_id,
            'encounter_status' => $chart_status_id,
            'user_id' => 'null',
            'status' => 'null'
        )), 302);
    }

    //Encounter Report
    /**
     * @Route("/encounter", name="report_encounter")
     */
    public function encounterAction() {

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

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

        $em = $this->getDoctrine()->getManager();
        $branch = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->branchesForMultiple($userData);
        $company = $em->getRepository('RxConnexionBundle:CompanyEntity')->companiesForMultiple($userData);
        $encounterType = $em->getRepository('RxConnexionBundle:ChartTypeEntity')->chartTypeForMultiple();
        $encounterStatus = $em->getRepository('RxConnexionBundle:PatientChartEntity')->findEncounterTypeStatus();

        $page_title = 'Encounter Report';
        return $this->render('@RxConnexion/Report/Encounter/index.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'chartType' => $encounterType,
            'chartStatus' => $encounterStatus,
            'branch' => $branch,
            'company' => $company,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/encounter/encounter.js?v=1.0.2')
        ));
    }

    /**
     * @Route(
     *      "/encounter/preview/{date_from}/{date_to}/{company_id}/{branch_id}/{provider_id}/{encountertype_id}/{encounter_status}/{user_id}/{status}",
     *      name = "report_encounter_preview"
     * )
     */
    public function encounter_previewAction($date_from, $date_to, $company_id, $branch_id, $provider_id, $encountertype_id, $encounter_status, $user_id, $status) {

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

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientChartEntity')->reportEncounter(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company_id,
            'branch' => $branch_id,
            'provider' => $provider_id,
            'encounter_type' => $encountertype_id,
            'encounter_status' => $encounter_status,
            'user_id' => $user_id,
            'patient_status' => $status,
            'userData' => $userData
        ));

        $summary = array(
            'encounterTypes' => array()
        );

        foreach ($records as $record) {
            if(isset($summary['encounterTypes'][$record['encounterType']])){
                if(isset($summary['encounterTypes'][$record['encounterType']][$record['encounterStatus']])) {
                    $summary['encounterTypes'][$record['encounterType']][$record['encounterStatus']]++;
                }
                else {
                    $summary['encounterTypes'][$record['encounterType']][$record['encounterStatus']] = 1;
                }
            } else {
                $summary['encounterTypes'][$record['encounterType']] = array(
                    $record['encounterStatus'] => 1
                );
            }
        }

        $page_title = 'Encounter Report';
        return $this->render('@RxConnexion/Report/Encounter/preview.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'javascripts' => array('rxconnexion/admin/js/report/report_preview.js'),
            'date_from' => $date_from,
            'date_to' => $date_to,
            'records' => $records,
            'summary' => $summary
        ));
    }

    /**
     * @Route(
     *      "/encounter/export_to_pdf/{date_from}/{date_to}/{company_id}/{branch_id}/{provider_id}/{encountertype_id}/{encounter_status}/{user_id}/{status}",
     *      name = "report_encounter_export_to_pdf"
     * )
     */
    public function encounter_export_to_pdfAction($date_from, $date_to, $company_id, $branch_id, $provider_id, $encountertype_id, $encounter_status, $user_id, $status) {

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

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientChartEntity')->reportEncounter(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company_id,
            'branch' => $branch_id,
            'provider' => $provider_id,
            'encounter_type' => $encountertype_id,
            'encounter_status' => $encounter_status,
            'user_id' => $user_id,
            'patient_status' => $status,
            'userData' => $userData
        ));

        $summary = array(
            'encounterTypes' => array()
        );

        foreach ($records as $record) {
            if(isset($summary['encounterTypes'][$record['encounterType']])){
                if(isset($summary['encounterTypes'][$record['encounterType']][$record['encounterStatus']])) {
                    $summary['encounterTypes'][$record['encounterType']][$record['encounterStatus']]++;
                }
                else {
                    $summary['encounterTypes'][$record['encounterType']][$record['encounterStatus']] = 1;
                }
            } else {
                $summary['encounterTypes'][$record['encounterType']] = array(
                    $record['encounterStatus'] => 1
                );
            }
        }

        $page_title = 'Encounter Report';
        $content = $this->renderView('@RxConnexion/Report/Encounter/preview.wkpdf.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'date_from' => $date_from,
            'date_to' => $date_to,
            'records' => $records,
            'summary' => $summary
        ));

        $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content, array(
            'dpi' => 72,
            // 'disable-smart-shrinking',
            'zoom' => 'LINUX' == strtoupper(PHP_OS) ? 0.78 : 1
        ));

        $pdfResponse = array(
            'success' => true,
            'msg' => 'PDF was successfully generated.',
            'pdfBase64' => base64_encode($xml)
        );
        if($pdfResponse['success']) {
            $pdfContent = $pdfResponse['pdfBase64'];
            return new Response(base64_decode($pdfContent), 200, array(
                'Content-Type' => 'application/pdf',
                'Content-Disposition'   => 'attachment; filename="Encounter Report' . date('m/d/Y') . ' Details.pdf"'
            ));
        } else {
            $this->get('session')->getFlashBag()->set('error_messages', $pdfResponse['msg']);
            return $this->redirect($this->generateUrl('report_encounter', 302));
        }
    }

    /**
     * @Route(
     *      "/encounter/export_to_excel/{date_from}/{date_to}/{company_id}/{branch_id}/{provider_id}/{encountertype_id}/{encounter_status}/{user_id}/{status}",
     *      name = "report_encounter_export_to_excel"
     * )
     */
    public function encounter_export_to_excelAction($date_from, $date_to, $company_id, $branch_id, $provider_id, $encountertype_id, $encounter_status, $user_id, $status) {

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

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientChartEntity')->reportEncounter(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company_id,
            'branch' => $branch_id,
            'provider' => $provider_id,
            'encounter_type' => $encountertype_id,
            'encounter_status' => $encounter_status,
            'user_id' => $user_id,
            'patient_status' => $status,
            'userData' => $userData
        ));

        $summary = array(
            'encounterTypes' => array()
        );

        foreach ($records as $record) {
            if(isset($summary['encounterTypes'][$record['encounterType']])){
                if(isset($summary['encounterTypes'][$record['encounterType']][$record['encounterStatus']])) {
                    $summary['encounterTypes'][$record['encounterType']][$record['encounterStatus']]++;
                }
                else {
                    $summary['encounterTypes'][$record['encounterType']][$record['encounterStatus']] = 1;
                }
            } else {
                $summary['encounterTypes'][$record['encounterType']] = array(
                    $record['encounterStatus'] => 1
                );
            }
        }

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

        foreach($records as $record) {

            $rowCtr++;
            $totalCount++;

            $cellsData[] = array('cell' => "A$rowCtr", 'data' => $record['encounterId']);
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => $record['accountUser']);
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => $record['encounterDate']);
            $cellsData[] = array('cell' => "D$rowCtr", 'data' => $record['patient']);
            $cellsData[] = array('cell' => "E$rowCtr", 'data' => $record['branch']);
            $cellsData[] = array('cell' => "F$rowCtr", 'data' => $record['clinician']);
            $cellsData[] = array('cell' => "G$rowCtr", 'data' => $record['encounterType']);
            $cellsData[] = array('cell' => "H$rowCtr", 'data' => $record['encounterStatus']);
            $cellsData[] = array('cell' => "I$rowCtr", 'data' => strip_tags($record['note']));
        }

        $rowCtr++;
        $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Total Records: ' . $totalCount);
        $rowCtr++;
        $rowCtr++;
        $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Summary');
        foreach ($summary['encounterTypes'] as $key => $sum) {
            $rowCtr++;
            $cellsData[] = array('cell' => "A$rowCtr", 'data' => $key);
            foreach ($sum as $key2 => $s) {
                $rowCtr++;
                $cellsData[] = array('cell' => "B$rowCtr", 'data' => $key2.":".$s);
            }
        }


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

    //Insurance Report
    /**
     * @Route("/insurance", name="report_insurance")
     */
    public function insuranceAction() {

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

        $page_title = 'Insurance Report';
        return $this->render('@RxConnexion/Report/Insurance/index.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/insurance/insurance.js')
        ));
    }

    /**
     * @Route(
     *      "/insurance/preview/{date_from}/{date_to}/{patient_id}/{insurance_id}",
     *      name = "report_insurance_preview"
     * )
     */
    public function insurance_previewAction($date_from, $date_to, $patient_id, $insurance_id) {

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:InsuranceEntity')->reportInsurance(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'patient_id' => $patient_id,
            'insurance_id' => $insurance_id
        ));

        $page_title = 'Insurance Report';
        return $this->render('@RxConnexion/Report/Insurance/preview.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'javascripts' => array('rxconnexion/admin/js/report/report_preview.js'),
            'records' => $records
        ));
    }

    /**
     * @Route(
     *      "/insurance/export_to_pdf/{date_from}/{date_to}/{patient_id}/{insurance_id}",
     *      name = "report_insurance_export_to_pdf"
     * )
     */
    public function insurance_export_to_pdfAction($date_from, $date_to, $patient_id, $insurance_id) {

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:InsuranceEntity')->reportInsurance(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'patient_id' => $patient_id,
            'insurance_id' => $insurance_id
        ));

        $page_title = 'Insurance Report';
        $content = $this->renderView('@RxConnexion/Report/Insurance/preview.wkpdf.twig', array(
            'page_title' => $page_title,
            'records' => $records
        ));

        $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content, array(
            'dpi' => 72,
            // 'disable-smart-shrinking',
            'zoom' => 'LINUX' == strtoupper(PHP_OS) ? 0.78 : 1
        ));

        $pdfResponse = array(
            'success' => true,
            'msg' => 'PDF was successfully generated.',
            'pdfBase64' => base64_encode($xml)
        );
        if($pdfResponse['success']) {
            $pdfContent = $pdfResponse['pdfBase64'];
            return new Response(base64_decode($pdfContent), 200, array(
                'Content-Type' => 'application/pdf',
                'Content-Disposition'   => 'attachment; filename="Insurance Report' . date('m/d/Y') . ' Details.pdf"'
            ));
        } else {
            $this->get('session')->getFlashBag()->set('error_messages', $pdfResponse['msg']);
            return $this->redirect($this->generateUrl('report_insurance', 302));
        }
    }

    /**
     * @Route(
     *      "/insurance/export_to_excel/{date_from}/{date_to}/{patient_id}/{insurance_id}",
     *      name = "report_insurance_export_to_excel"
     * )
     */
    public function insurance_export_to_excelAction($date_from, $date_to, $patient_id, $insurance_id) {

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:InsuranceEntity')->reportInsurance(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'patient_id' => $patient_id,
            'insurance_id' => $insurance_id
        ));

        $columnRange = range('A', 'L');
        $cellsData = array(
            array('cell' => 'A1', 'data' => 'Insurance Type'),
            array('cell' => 'B1', 'data' => 'Insurance Number'),
            array('cell' => 'C1', 'data' => 'Insurance'),
            array('cell' => 'D1', 'data' => 'Date Issued'),
            array('cell' => 'E1', 'data' => 'Expiry Date'),
            array('cell' => 'F1', 'data' => 'Patient'),
        );
        $rowCtr = 1;
        $totalCount = 0;

        foreach($records as $record) {

            $rowCtr++;
            $totalCount++;

            $cellsData[] = array('cell' => "A$rowCtr", 'data' => $record['insurance_type']);
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => $record['insurance_no']);
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => $record['insurance_type']);
            $cellsData[] = array('cell' => "D$rowCtr", 'data' => $record['insurance_desc']);
            $cellsData[] = array('cell' => "E$rowCtr", 'data' => $record['stateDate']);
            $cellsData[] = array('cell' => "F$rowCtr", 'data' => $record['expireDate']);
            $cellsData[] = array('cell' => "G$rowCtr", 'data' => $record['full_name']);
        }

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


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

    //Diagnosis Report
    /**
     * @Route("/diagnosis", name="report_diagnosis")
     */
    public function diagnosisAction() {

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

        $session = $this->get('session');
        $userData = $session->get('userData');
        $em = $this->getDoctrine()->getManager();
        $company = $em->getRepository('RxConnexionBundle:CompanyEntity')->companiesForMultiple($userData);
        $branch = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->branchesForMultiple($userData);

        $page_title = 'Diagnosis Report';
        return $this->render('@RxConnexion/Report/Diagnosis/index.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'company' => $company,
            'branch' => $branch,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/diagnosis/diagnosis.js')
        ));
    }

    /**
     * @Route(
     *      "/diagnosis/preview/{date_from}/{date_to}/{company}/{branch}/{diagnosis}/{status}/{specialist}/{referring_affiliate}/{chart_type}",
     *      name = "report_diagnosis_preview"
     * )
     */
    public function diagnosis_previewAction($date_from, $date_to, $company, $branch, $diagnosis, $status, $specialist, $referring_affiliate, $chart_type) {

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

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:DiagnosisEntity')->reportDiagnosis(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company,
            'branch' => $branch,
            'diagnosis' => $diagnosis,
            'status' => $status,
            'specialist' => $specialist,
            'referring_affiliate' => $referring_affiliate,
            'chart_type' => $chart_type,
            'userData' => $userData
        ));

        $page_title = 'Diagnosis Report';
        return $this->render('@RxConnexion/Report/Diagnosis/preview.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'javascripts' => array('rxconnexion/admin/js/report/report_preview.js'),
            'records' => $records
        ));
    }

    /**
     * @Route(
     *      "/diagnosis/export_to_pdf/{date_from}/{date_to}/{company}/{branch}/{diagnosis}/{status}/{specialist}/{referring_affiliate}/{chart_type}",
     *      name = "report_diagnosis_export_to_pdf"
     * )
     */
    public function diagnosis_export_to_pdfAction($date_from, $date_to, $company, $branch, $diagnosis, $status, $specialist, $referring_affiliate, $chart_type) {

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

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:DiagnosisEntity')->reportDiagnosis(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company,
            'branch' => $branch,
            'diagnosis' => $diagnosis,
            'status' => $status,
            'specialist' => $specialist,
            'referring_affiliate' => $referring_affiliate,
            'chart_type' => $chart_type,
            'userData' => $userData
        ));

        $page_title = 'Diagnosis Report';
        $content = $this->renderView('@RxConnexion/Report/Diagnosis/preview.wkpdf.twig', array(
            'page_title' => $page_title,
            'records' => $records
        ));

        $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content, array(
            'dpi' => 72,
            // 'disable-smart-shrinking',
            'zoom' => 'LINUX' == strtoupper(PHP_OS) ? 0.78 : 1
        ));

        $pdfResponse = array(
            'success' => true,
            'msg' => 'PDF was successfully generated.',
            'pdfBase64' => base64_encode($xml)
        );
        if($pdfResponse['success']) {
            $pdfContent = $pdfResponse['pdfBase64'];
            return new Response(base64_decode($pdfContent), 200, array(
                'Content-Type' => 'application/pdf',
                'Content-Disposition'   => 'attachment; filename="Diagnosis Report' . date('m/d/Y') . ' Details.pdf"'
            ));
        } else {
            $this->get('session')->getFlashBag()->set('error_messages', $pdfResponse['msg']);
            return $this->redirect($this->generateUrl('report_diagnosis', 302));
        }
    }

    /**
     * @Route(
     *      "/diagnosis/export_to_excel/{date_from}/{date_to}/{company}/{branch}/{diagnosis}/{status}/{specialist}/{referring_affiliate}/{chart_type}",
     *      name = "report_diagnosis_export_to_excel"
     * )
     */
    public function diagnosis_export_to_excelAction($date_from, $date_to, $company, $branch, $diagnosis, $status, $specialist, $referring_affiliate, $chart_type) {

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

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:DiagnosisEntity')->reportDiagnosis(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company,
            'branch' => $branch,
            'diagnosis' => $diagnosis,
            'status' => $status,
            'specialist' => $specialist,
            'referring_affiliate' => $referring_affiliate,
            'chart_type' => $chart_type,
            'userData' => $userData
        ));

        $columnRange = range('A', 'E');
        $cellsData = array(
            array('cell' => 'A1', 'data' => 'Referral Date'),
            array('cell' => 'B1', 'data' => 'Date Received'),
            array('cell' => 'C1', 'data' => 'Patient'),
            array('cell' => 'D1', 'data' => 'Company'),
            array('cell' => 'E1', 'data' => 'Branch'),
            array('cell' => 'F1', 'data' => 'Encounter Type'),
            array('cell' => 'G1', 'data' => 'Referring Affiliate'),
            array('cell' => 'H1', 'data' => 'Diagnosis'),
            array('cell' => 'I1', 'data' => 'Specialist'),
        );
        $rowCtr = 1;
        $totalCount = 0;

        foreach($records as $record) {

            $rowCtr++;
            $totalCount++;

            $cellsData[] = array('cell' => "A$rowCtr", 'data' => $record['referralDate']);
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => $record['receivedDate']);
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => $record['patientName']);
            $cellsData[] = array('cell' => "D$rowCtr", 'data' => $record['companyDesc']);
            $cellsData[] = array('cell' => "E$rowCtr", 'data' => $record['branchDesc']);
            $cellsData[] = array('cell' => "F$rowCtr", 'data' => $record['chartType']);
            $cellsData[] = array('cell' => "G$rowCtr", 'data' => $record['referringAffiliateDesc']);
            $cellsData[] = array('cell' => "H$rowCtr", 'data' => $record['diagnosisDesc']);
            $cellsData[] = array('cell' => "I$rowCtr", 'data' => $record['specialistName']);
        }

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


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

    /**
     * @Route(
     *      "/referral/redirect/preview/{date_from}/{date_to}/{company_id}/{branch_id}",
     *      defaults = {
     *          "date_from":  "null",
     *          "date_to":  "null",
     *          "company_id":  "null",
     *          "branch_id":  "null",
     *      },
     *
         *      name = "report_management_dashboard_referral_redirect_preview",
     *
     * )
     */
    public function managementDashboard_referral_redirect_previewAction($date_from, $date_to, $company_id, $branch_id) {

        return $this->redirect($this->generateUrl('report_referral_preview', array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company_id' => $company_id,
            'branch_id' => $branch_id,
            'patient_id' => 'null',
            'clinician_id' => 'null',
            'referring_affiliate_id' => 'null',
            'referring_physician_id' => 'null',
            'agent_id' => 'null',
        )), 302);
    }

    //Referrals Report
    /**
     * @Route("/referral", name="report_referral")
     */
    public function referralAction() {

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

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

        $em = $this->getDoctrine()->getManager();
        $branch = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->branchesForMultiple($userData);
        $company = $em->getRepository('RxConnexionBundle:CompanyEntity')->companiesForMultiple($userData);


        $page_title = 'Referral Report';
        return $this->render('@RxConnexion/Report/Referral/index.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'company' => $company,
            'branch' => $branch,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/referral/referral.js?v=1.0.2')
        ));
    }

    /**
     * @Route(
     *      "/referral/preview/{date_from}/{date_to}/{company_id}/{branch_id}/{receive_date_from}/{receive_date_to}/{patient_id}/{clinician_id}/{referring_affiliate_id}/{referring_physician_id}/{agent_id}",
     *      name = "report_referral_preview",
     *
     * )
     */
    public function referral_previewAction($date_from, $date_to, $company_id, $branch_id, $receive_date_from, $receive_date_to, $patient_id, $clinician_id, $referring_affiliate_id, $referring_physician_id, $agent_id) {

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

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:ReferralEntity')->reportReferral(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company_id,
            'branch' => $branch_id,
            'receive_date_from' => $receive_date_from,
            'receive_date_to' => $receive_date_to,
            'patient' => $patient_id,
            'clinician' => $clinician_id,
            'referring_affiliate' => $referring_affiliate_id,
            'referring_physician' => $referring_physician_id,
            'agent' => $agent_id,
            'userData' => $userData
        ));

        $page_title = 'Referral Report';
        return $this->render('@RxConnexion/Report/Referral/preview.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'javascripts' => array('rxconnexion/admin/js/report/report_preview.js'),
            'records' => $records,
        ));
    }

    /**
     * @Route(
     *      "/referral/export_to_pdf/{date_from}/{date_to}/{company_id}/{branch_id}/{receive_date_from}/{receive_date_to}/{patient_id}/{clinician_id}/{referring_affiliate_id}/{referring_physician_id}/{agent_id}",
     *      name = "report_referral_export_to_pdf"
     * )
     */
    public function referral_export_to_pdfAction($date_from, $date_to, $company_id, $branch_id, $receive_date_from, $receive_date_to, $patient_id, $clinician_id, $referring_affiliate_id, $referring_physician_id, $agent_id) {

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

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:ReferralEntity')->reportReferral(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company_id,
            'branch' => $branch_id,
            'receive_date_from' => $receive_date_from,
            'receive_date_to' => $receive_date_to,
            'patient' => $patient_id,
            'clinician' => $clinician_id,
            'referring_affiliate' => $referring_affiliate_id,
            'referring_physician' => $referring_physician_id,
            'agent' => $agent_id,
            'userData' => $userData
        ));



        $page_title = 'Referral Report';
        $content = $this->renderView('@RxConnexion/Report/Referral/preview.wkpdf.twig', array(
            'page_title' => $page_title,
            'records' => $records,
        ));

        $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content, array(
            'orientation'=>'Landscape',
            'dpi' => 72,
            // 'disable-smart-shrinking',
            'zoom' => 'LINUX' == strtoupper(PHP_OS) ? 0.78 : 1
        ));

        $pdfResponse = array(
            'success' => true,
            'msg' => 'PDF was successfully generated.',
            'pdfBase64' => base64_encode($xml)
        );
        if($pdfResponse['success']) {
            $pdfContent = $pdfResponse['pdfBase64'];
            return new Response(base64_decode($pdfContent), 200, array(
                'Content-Type' => 'application/pdf',
                'Content-Disposition'   => 'attachment; filename="Referral Report' . date('m/d/Y') . ' Details.pdf"'
            ));
        } else {
            $this->get('session')->getFlashBag()->set('error_messages', $pdfResponse['msg']);
            return $this->redirect($this->generateUrl('report_referral', 302));
        }
    }

    /**
     * @Route(
     *      "/referral/export_to_excel/{date_from}/{date_to}/{company_id}/{branch_id}/{receive_date_from}/{receive_date_to}/{patient_id}/{clinician_id}/{referring_affiliate_id}/{referring_physician_id}/{agent_id}",
     *      name = "report_referral_export_to_excel"
     * )
     */
    public function referral_export_to_excelAction($date_from, $date_to, $company_id, $branch_id, $receive_date_from, $receive_date_to, $patient_id, $clinician_id, $referring_affiliate_id, $referring_physician_id, $agent_id) {

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

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:ReferralEntity')->reportReferral(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company_id,
            'receive_date_from' => $receive_date_from,
            'receive_date_to' => $receive_date_to,
            'branch' => $branch_id,
            'patient' => $patient_id,
            'clinician' => $clinician_id,
            'referring_affiliate' => $referring_affiliate_id,
            'referring_physician' => $referring_physician_id,
            'agent' => $agent_id,
            'userData' => $userData
        ));

        $columnRange = range('A', 'L');
        $cellsData = array(
            array('cell' => 'A1', 'data' => 'Referral ID'),
            array('cell' => 'B1', 'data' => 'Staff'),
            array('cell' => 'C1', 'data' => 'Referral Date'),
            array('cell' => 'D1', 'data' => 'Received Date'),
            array('cell' => 'E1', 'data' => 'Branch'),
            array('cell' => 'F1', 'data' => 'Patient'),
            array('cell' => 'G1', 'data' => 'Referring Physician'),
            array('cell' => 'H1', 'data' => 'Referring Affiliate'),
            array('cell' => 'I1', 'data' => 'Encounter Type'),
            array('cell' => 'J1', 'data' => 'Encounter Status'),
            array('cell' => 'K1', 'data' => 'Letter Type'),
            array('cell' => 'L1', 'data' => 'Letter Status'),
            array('cell' => 'M1', 'data' => 'Agent'),
            array('cell' => 'N1', 'data' => 'Notes'),

        );
        $rowCtr = 1;
        $totalCount = 0;

        foreach($records['referral'] as $record) {

            $rowCtr++;
            $totalCount++;

            $cellsData[] = array('cell' => "A$rowCtr", 'data' => $record['referralId']);
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => $record['accountUser']);
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => $record['referral_date']);
            $cellsData[] = array('cell' => "D$rowCtr", 'data' => $record['receive_date']);
            $cellsData[] = array('cell' => "E$rowCtr", 'data' => $record['branch']);
            $cellsData[] = array('cell' => "F$rowCtr", 'data' => $record['patient']);
            $cellsData[] = array('cell' => "G$rowCtr", 'data' => $record['referring_physician']);
            $cellsData[] = array('cell' => "H$rowCtr", 'data' => $record['referring_affiliate']);
            $cellsData[] = array('cell' => "I$rowCtr", 'data' => $record['chartType']);
            $cellsData[] = array('cell' => "J$rowCtr", 'data' => $record['chartStatus']);
            $cellsData[] = array('cell' => "K$rowCtr", 'data' => $record['letterType']);
            $cellsData[] = array('cell' => "L$rowCtr", 'data' => $record['letterStatus']);
            $cellsData[] = array('cell' => "M$rowCtr", 'data' => $record['sales_agent']);
            $cellsData[] = array('cell' => "N$rowCtr", 'data' => strip_tags($record['note']));
        }

        $rowCtr++;
        $rowCtr++;
        $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Referral - Referring Physician');
        $rowCtr++;
        $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Referring Physician');
        $cellsData[] = array('cell' => "B$rowCtr", 'data' => 'Count');
        foreach($records['referralCount'] as $record) {
            $rowCtr++;
            $cellsData[] = array('cell' => "A$rowCtr", 'data' => $record['referringProvider']);
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => $record['referralCount']);
        }

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


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

    //Referrals(Marketing) Report
    /**
     * @Route("/referral_marketing", name="report_referral_marketing")
     */
    public function referralmarketingAction() {

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

        $session = $this->get('session');
        $userData = $session->get('userData');
        $em = $this->getDoctrine()->getManager();
        $branch = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->branchesForMultiple($userData);
        $company = $em->getRepository('RxConnexionBundle:CompanyEntity')->companiesForMultiple($userData);

        $page_title = 'Marketing Referral Report';
        return $this->render('@RxConnexion/Report/ReferralMarketing/index.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'branch' => $branch,
            'company' => $company,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/referralMarketing/referral_marketing.js?v=1.0.2')
        ));
    }

    /**
     * @Route(
     *      "/referral_marketing/preview/{date_from}/{date_to}/{company}/{branch}/{receive_date_from}/{receive_date_to}/{clinician}/{referring_affiliate}/{referring_physician}/{agent}",
     *      name = "report_referral_marketing_preview"
     * )
     */
    public function referralmarketing_previewAction($date_from, $date_to, $company, $branch, $receive_date_from, $receive_date_to, $clinician, $referring_affiliate, $referring_physician, $agent) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Referral Marketing Preview'))) return $authService->redirectToHome();

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:ReferralEntity')->reportReferralMarketing(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company,
            'branch' => $branch,
            'receive_date_from' => $receive_date_from,
            'receive_date_to' => $receive_date_to,
            'clinician' => $clinician,
            'referring_affiliate' => $referring_affiliate,
            'referring_physician' => $referring_physician,
            'agent' => $agent,
            'userData' => $userData,
        ));

        $lastProvider = array(
            'name' => null,
            'rowspan' => 0,
            'key' => 0,
            'total' => 0
        );

        $lastHealthFacility = array(
            'name' => null,
            'rowspan' => 0,
            'key' => 0,
            'total' => 0
        );

        $lastCompany = array(
            'name' => null,
            'rowspan' => 0,
            'key' => 0,
            'total' => 0
        );

        foreach ($records as $key => $record) {

            if($lastProvider['name'] != $record['referringProvider'] && $key > 0) {
                $records[$lastProvider['key']]['rowDetailsRefProvider'] = array(
                    'name' => $lastProvider['name'],
                    'rowspan' => $lastProvider['rowspan'],
                    'total' => $lastProvider['total'],
                );

                $lastProvider['key'] = $key;
                $lastProvider['rowspan'] = 0;
                $lastProvider['total'] = 0;

                $lastCompany['rowspan']++;
                $lastHealthFacility['rowspan']++;
            }

            if($lastHealthFacility['name'] != $record['referringHealthFacility'] && $key > 0) {

                $records[$lastHealthFacility['key']]['rowDetailsRefHf'] = array(
                    'name' => $lastHealthFacility['name'],
                    'rowspan' => $lastHealthFacility['rowspan'],
                    'total' => $lastHealthFacility['total'],
                );

                $lastHealthFacility['key'] = $key;
                $lastHealthFacility['rowspan'] = 0;
                $lastHealthFacility['total'] = 0;

                $lastCompany['rowspan']++;

            }

            if($lastCompany['name'] != $record['healthFacility'] && $key > 0) {

                $records[$lastCompany['key']]['rowDetailsCompany'] = array(
                    'name' => $lastCompany['name'],
                    'rowspan' => $lastCompany['rowspan'],
                    'total' => $lastCompany['total'],
                );

                $lastCompany['key'] = $key;
                $lastCompany['rowspan'] = 0;
                $lastCompany['total'] = 0;

            }


            $lastProvider['total']++;
            $lastProvider['name'] = $record['referringProvider'];


            $lastHealthFacility['total']++;
            $lastHealthFacility['name'] = $record['referringHealthFacility'];

            $lastCompany['total']++;
            $lastCompany['name'] = $record['healthFacility'];

            $lastCompany['rowspan']++;
            $lastHealthFacility['rowspan']++;
            $lastProvider['rowspan']++;
        }

        $records[$lastProvider['key']]['rowDetailsRefProvider'] = array(
            'name' => $lastProvider['name'],
            'rowspan' => $lastProvider['rowspan'],
            'total' => $lastProvider['total'],
        );

        $records[$lastHealthFacility['key']]['rowDetailsRefHf'] = array(
            'name' => $lastHealthFacility['name'],
            'rowspan' => $lastHealthFacility['rowspan']+1,
            'total' => $lastHealthFacility['total'],
        );

        $records[$lastCompany['key']]['rowDetailsCompany'] = array(
            'name' => $lastCompany['name'],
            'rowspan' => $lastCompany['rowspan']+2,
            'total' => $lastCompany['total'],
        );

        $page_title = 'Marketing Referral Report';
        return $this->render('@RxConnexion/Report/ReferralMarketing/preview.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'javascripts' => array('rxconnexion/admin/js/report/report_preview.js'),
            'records' => $records
        ));
    }

    /**
     * @Route(
     *      "/referral_marketing/export_to_pdf/{date_from}/{date_to}/{company}/{branch}/{receive_date_from}/{receive_date_to}/{clinician}/{referring_affiliate}/{referring_physician}/{agent}",
     *      name = "report_referral_marketing_export_to_pdf"
     * )
     */
    public function referral_marketingexport_to_pdfAction($date_from, $date_to, $company, $branch, $receive_date_from, $receive_date_to, $clinician, $referring_affiliate, $referring_physician, $agent) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Referral Marketing Pdf'))) return $authService->redirectToHome();

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:ReferralEntity')->reportReferralMarketing(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company,
            'branch' => $branch,
            'receive_date_from' => $receive_date_from,
            'receive_date_to' => $receive_date_to,
            'clinician' => $clinician,
            'referring_affiliate' => $referring_affiliate,
            'referring_physician' => $referring_physician,
            'agent' => $agent,
        ));

        $lastProvider = array(
            'name' => null,
            'rowspan' => 0,
            'key' => 0,
            'total' => 0
        );

        $lastHealthFacility = array(
            'name' => null,
            'rowspan' => 0,
            'key' => 0,
            'total' => 0
        );

        $lastCompany = array(
            'name' => null,
            'rowspan' => 0,
            'key' => 0,
            'total' => 0
        );

        foreach ($records as $key => $record) {

            if($lastProvider['name'] != $record['referringProvider'] && $key > 0) {
                $records[$lastProvider['key']]['rowDetailsRefProvider'] = array(
                    'name' => $lastProvider['name'],
                    'rowspan' => $lastProvider['rowspan'],
                    'total' => $lastProvider['total'],
                );

                $lastProvider['key'] = $key;
                $lastProvider['rowspan'] = 0;
                $lastProvider['total'] = 0;

                $lastCompany['rowspan']++;
                $lastHealthFacility['rowspan']++;
            }

            if($lastHealthFacility['name'] != $record['referringHealthFacility'] && $key > 0) {

                $records[$lastHealthFacility['key']]['rowDetailsRefHf'] = array(
                    'name' => $lastHealthFacility['name'],
                    'rowspan' => $lastHealthFacility['rowspan'],
                    'total' => $lastHealthFacility['total'],
                );

                $lastHealthFacility['key'] = $key;
                $lastHealthFacility['rowspan'] = 0;
                $lastHealthFacility['total'] = 0;

                $lastCompany['rowspan']++;

            }

            if($lastCompany['name'] != $record['healthFacility'] && $key > 0) {

                $records[$lastCompany['key']]['rowDetailsCompany'] = array(
                    'name' => $lastCompany['name'],
                    'rowspan' => $lastCompany['rowspan'],
                    'total' => $lastCompany['total'],
                );

                $lastCompany['key'] = $key;
                $lastCompany['rowspan'] = 0;
                $lastCompany['total'] = 0;

            }


            $lastProvider['total']++;
            $lastProvider['name'] = $record['referringProvider'];


            $lastHealthFacility['total']++;
            $lastHealthFacility['name'] = $record['referringHealthFacility'];

            $lastCompany['total']++;
            $lastCompany['name'] = $record['healthFacility'];

            $lastCompany['rowspan']++;
            $lastHealthFacility['rowspan']++;
            $lastProvider['rowspan']++;
        }

        $records[$lastProvider['key']]['rowDetailsRefProvider'] = array(
            'name' => $lastProvider['name'],
            'rowspan' => $lastProvider['rowspan'],
            'total' => $lastProvider['total'],
        );

        $records[$lastHealthFacility['key']]['rowDetailsRefHf'] = array(
            'name' => $lastHealthFacility['name'],
            'rowspan' => $lastHealthFacility['rowspan']+1,
            'total' => $lastHealthFacility['total'],
        );

        $records[$lastCompany['key']]['rowDetailsCompany'] = array(
            'name' => $lastCompany['name'],
            'rowspan' => $lastCompany['rowspan']+2,
            'total' => $lastCompany['total'],
        );

        $page_title = 'Marketing Referral Report';
        $content = $this->renderView('@RxConnexion/Report/ReferralMarketing/preview.wkpdf.twig', array(
            'page_title' => $page_title,
            'records' => $records
        ));

        $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content, array(
            'orientation'=>'Landscape',
            'dpi' => 72,
            // 'disable-smart-shrinking',
            'zoom' => 'LINUX' == strtoupper(PHP_OS) ? 0.78 : 1
        ));

        $pdfResponse = array(
            'success' => true,
            'msg' => 'PDF was successfully generated.',
            'pdfBase64' => base64_encode($xml)
        );
        if($pdfResponse['success']) {
            $pdfContent = $pdfResponse['pdfBase64'];
            return new Response(base64_decode($pdfContent), 200, array(
                'Content-Type' => 'application/pdf',
                'Content-Disposition'   => 'attachment; filename="Marketing Referral Report' . date('m/d/Y') . ' Details.pdf"'
            ));
        } else {
            $this->get('session')->getFlashBag()->set('error_messages', $pdfResponse['msg']);
            return $this->redirect($this->generateUrl('report_referral', 302));
        }
    }

    /**
     * @Route(
     *      "/referral_marketing/export_to_excel/{date_from}/{date_to}/{company}/{branch}/{receive_date_from}/{receive_date_to}/{clinician}/{referring_affiliate}/{referring_physician}/{agent}",
     *      name = "report_referral_marketing_export_to_excel"
     * )
     */
    public function referralmarketing_export_to_excelAction($date_from, $date_to, $company, $branch, $receive_date_from, $receive_date_to, $clinician, $referring_affiliate, $referring_physician, $agent) {

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

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:ReferralEntity')->reportReferralMarketing(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company,
            'branch' => $branch,
            'receive_date_from' => $receive_date_from,
            'receive_date_to' => $receive_date_to,
            'clinician' => $clinician,
            'referring_affiliate' => $referring_affiliate,
            'referring_physician' => $referring_physician,
            'agent' => $agent,
            'userData' => $userData,
        ));

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

        $activeSheet->setCellValue('A1', 'Clinic');
        $activeSheet->setCellValue('B1', 'Referring Affiliate');
        $activeSheet->setCellValue('C1', 'Referring Physician');
        $activeSheet->setCellValue('D1', 'Patient');
        $activeSheet->setCellValue('E1', 'Referral Date');
        $activeSheet->setCellValue('F1', 'Receive Date');
        $activeSheet->setCellValue('G1', 'Encounter Type');
        $activeSheet->setCellValue('H1', 'Encounter Status');
        $activeSheet->setCellValue('I1', 'Sold');
        $activeSheet->setCellValue('J1', 'Agent');
        $activeSheet->setCellValue('K1', 'Rate');
        $activeSheet->setCellValue('L1', 'Total');
        $activeSheet->getStyle('A1:L1')->applyFromArray(array(
            'fill' => array(
                'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                'color' => array('rgb' => 'ADD8E6')
            ),
            'borders' => array(
                'allborders' => array(
                    'style' => \PHPExcel_Style_Border::BORDER_THIN
                )
            )
        ));

        $rowCtr = 1;

        $lastProvider = array(
            'name' => null,
            'rowStart' => null,
            'total' => 0
        );

        $lastHealthFacility = array(
            'name' => null,
            'rowStart' => null,
            'total' => 0
        );

        $lastCompany = array(
            'name' => null,
            'rowStart' => null,
            'total' => 0
        );

        $totalCount = 0;
        foreach($records as $record) {

            $totalCount++;
            $rowCtr++;

            if ($lastCompany['name'] != $record['healthFacility']) {

                if ($lastCompany['rowStart'] > 0) {

                    //
                    $activeSheet->getStyle('C'.$lastProvider['rowStart'].':C'.($rowCtr-1))->applyFromArray(array(
                        'borders' => array(
                            'allborders' => array(
                                'style' => \PHPExcel_Style_Border::BORDER_THIN
                            )
                        )
                    ));
                    $activeSheet->mergeCells('C'.$lastProvider['rowStart'].':C'.($rowCtr-1));
                    $activeSheet->getStyle('C'.$lastProvider['rowStart'])->applyFromArray(array(
                        'alignment' => array(
                            'vertical' => \PHPExcel_Style_Alignment::VERTICAL_CENTER,
                            'horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER,

                        ),
                        'fill' => array(
                            'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                            'color' => array('rgb' => 'E2EFDD')
                        ),
                    ));

                    $activeSheet->setCellValue('C'.$rowCtr, 'Total');
                    $activeSheet->getStyle('C'.$rowCtr)->applyFromArray(array(
                        'alignment' => array(
                            'horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_RIGHT,
                        ),

                    ));

                    $activeSheet->setCellValue('L'.$rowCtr, $lastHealthFacility['total']);
                    $activeSheet->mergeCells('C'.$rowCtr.':K'.$rowCtr);
                    $activeSheet->getStyle('B'.$rowCtr.':L'.$rowCtr)->applyFromArray(array(
                        'fill' => array(
                            'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                            'color' => array('rgb' => 'E2EFDD')
                        ),
                        'borders' => array(
                            'allborders' => array(
                                'style' => \PHPExcel_Style_Border::BORDER_THIN
                            )
                        ),
                    ));
                    $rowCtr++;
                    //

                    //
                    $activeSheet->getStyle('B'.$lastHealthFacility['rowStart'].':B'.($rowCtr-1))->applyFromArray(array(
                        'borders' => array(
                            'allborders' => array(
                                'style' => \PHPExcel_Style_Border::BORDER_THIN
                            )
                        )
                    ));
                    $activeSheet->mergeCells('B'.$lastHealthFacility['rowStart'].':B'.($rowCtr-1));
                    $activeSheet->getStyle('B'.$lastHealthFacility['rowStart'])->applyFromArray(array(
                        'alignment' => array(
                            'vertical' => \PHPExcel_Style_Alignment::VERTICAL_CENTER,
                            'horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
                        ),
                        'fill' => array(
                            'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                            'color' => array('rgb' => 'ACB9CA')
                        ),
                    ));

                    $activeSheet->setCellValue('B'.$rowCtr, 'Total');
                    $activeSheet->getStyle('B'.$rowCtr)->applyFromArray(array(
                        'alignment' => array(
                            'horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_RIGHT,
                        )
                    ));

                    $activeSheet->setCellValue('L'.$rowCtr, $lastHealthFacility['total']);
                    $activeSheet->mergeCells('C'.$rowCtr.':K'.$rowCtr);
                    $activeSheet->getStyle('B'.$rowCtr.':L'.$rowCtr)->applyFromArray(array(
                        'fill' => array(
                            'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                            'color' => array('rgb' => 'ACB9CA')
                        ),
                        'borders' => array(
                            'allborders' => array(
                                'style' => \PHPExcel_Style_Border::BORDER_THIN
                            )
                        )
                    ));
                    $rowCtr++;
                    //

                    $activeSheet->getStyle('A'.$lastCompany['rowStart'].':A'.($rowCtr-1))->applyFromArray(array(
                        'borders' => array(
                            'allborders' => array(
                                'style' => \PHPExcel_Style_Border::BORDER_THIN
                            )
                        )
                    ));
                    $activeSheet->mergeCells('A'.$lastCompany['rowStart'].':A'.($rowCtr-1));
                    $activeSheet->getStyle('A'.$lastCompany['rowStart'])->applyFromArray(array(
                        'alignment' => array(
                            'vertical' => \PHPExcel_Style_Alignment::VERTICAL_CENTER,
                            'horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
                        ),
                        'fill' => array(
                            'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                            'color' => array('rgb' => 'DBDBDB')
                        ),
                    ));

                    $activeSheet->setCellValue('A'.$rowCtr, 'Total');
                    $activeSheet->getStyle('A'.$rowCtr)->applyFromArray(array(
                        'alignment' => array(
                            'horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_RIGHT,

                        )
                    ));

                    $activeSheet->setCellValue('L'.$rowCtr, $lastCompany['total']);
                    $activeSheet->mergeCells('B'.$rowCtr.':K'.$rowCtr);
                    $activeSheet->getStyle('A'.$rowCtr.':L'.$rowCtr)->applyFromArray(array(
                        'fill' => array(
                            'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                            'color' => array('rgb' => 'DBDBDB')
                        ),
                        'borders' => array(
                            'allborders' => array(
                                'style' => \PHPExcel_Style_Border::BORDER_THIN
                            )
                        )
                    ));
                    $rowCtr++;
                }



                $activeSheet->setCellValue('A'.$rowCtr, $record['healthFacility']);
                $activeSheet->setCellValue('B'.$rowCtr, $record['referringHealthFacility']);
                $activeSheet->setCellValue('C'.$rowCtr, $record['referringProvider']);

                $lastProvider = array(
                    'name' =>  $record['referringProvider'],
                    'rowStart' => $rowCtr,
                    'total' => 0
                );
                $lastHealthFacility = array(
                    'name' =>  $record['referringHealthFacility'],
                    'rowStart' => $rowCtr,
                    'total' => 0
                );
                $lastCompany = array(
                    'name' =>  $record['healthFacility'],
                    'rowStart' => $rowCtr,
                    'total' => 0
                );

            } else if ($lastHealthFacility['name'] != $record['referringHealthFacility']) {

                if ($lastHealthFacility['rowStart'] > 0) {

                    //
                    $activeSheet->getStyle('C'.$lastProvider['rowStart'].':C'.($rowCtr-1))->applyFromArray(array(
                        'borders' => array(
                            'allborders' => array(
                                'style' => \PHPExcel_Style_Border::BORDER_THIN
                            )
                        )
                    ));
                    $activeSheet->mergeCells('C'.$lastProvider['rowStart'].':C'.($rowCtr-1));
                    $activeSheet->getStyle('C'.$lastProvider['rowStart'])->applyFromArray(array(
                        'alignment' => array(
                            'vertical' => \PHPExcel_Style_Alignment::VERTICAL_CENTER,
                            'horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
                        ),
                        'fill' => array(
                            'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                            'color' => array('rgb' => 'E2EFDD')
                        ),
                        'borders' => array(
                            'outline' => array(
                                'style' => \PHPExcel_Style_Border::BORDER_THIN
                            )
                        )
                    ));

                    $activeSheet->setCellValue('C'.$rowCtr, 'Total');
                    $activeSheet->getStyle('C'.$rowCtr)->applyFromArray(array(
                        'alignment' => array(
                            'horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_RIGHT,

                        )
                    ));

                    $activeSheet->setCellValue('L'.$rowCtr, $lastProvider['total']);
                    $activeSheet->mergeCells('D'.$rowCtr.':K'.$rowCtr);
                    $activeSheet->getStyle('C'.$rowCtr.':L'.$rowCtr)->applyFromArray(array(
                        'fill' => array(
                            'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                            'color' => array('rgb' => 'E2EFDD')
                        ),
                        'borders' => array(
                            'allborders' => array(
                                'style' => \PHPExcel_Style_Border::BORDER_THIN
                            )
                        )
                    ));
                    $rowCtr++;
                    //
                    $activeSheet->getStyle('B'.$lastHealthFacility['rowStart'].':B'.($rowCtr-1))->applyFromArray(array(
                        'borders' => array(
                            'allborders' => array(
                                'style' => \PHPExcel_Style_Border::BORDER_THIN
                            )
                        )
                    ));
                    $activeSheet->mergeCells('B'.$lastHealthFacility['rowStart'].':B'.($rowCtr-1));
                    $activeSheet->getStyle('B'.$lastHealthFacility['rowStart'])->applyFromArray(array(
                        'alignment' => array(
                            'vertical' => \PHPExcel_Style_Alignment::VERTICAL_CENTER,
                            'horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
                        ),
                        'fill' => array(
                            'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                            'color' => array('rgb' => 'ACB9CA')
                        ),
                    ));

                    $activeSheet->setCellValue('B'.$rowCtr, 'Total');
                    $activeSheet->getStyle('B'.$rowCtr)->applyFromArray(array(
                        'alignment' => array(
                            'horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_RIGHT,

                        )
                    ));

                    $activeSheet->setCellValue('L'.$rowCtr, $lastHealthFacility['total']);
                    $activeSheet->mergeCells('C'.$rowCtr.':K'.$rowCtr);
                    $activeSheet->getStyle('B'.$rowCtr.':L'.$rowCtr)->applyFromArray(array(
                        'fill' => array(
                            'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                            'color' => array('rgb' => 'ACB9CA')
                        ),
                        'borders' => array(
                            'allborders' => array(
                                'style' => \PHPExcel_Style_Border::BORDER_THIN
                            )
                        )
                    ));
                    $rowCtr++;
                }



                $activeSheet->setCellValue('B'.$rowCtr, $record['referringHealthFacility']);
                $activeSheet->setCellValue('C'.$rowCtr, $record['referringProvider']);
                $lastHealthFacility = array(
                    'name' =>  $record['referringHealthFacility'],
                    'rowStart' => $rowCtr,
                    'total' => 0
                );
                $lastProvider = array(
                    'name' =>  $record['referringProvider'],
                    'rowStart' => $rowCtr,
                    'total' => 0
                );

            } else if ($lastProvider['name'] != $record['referringProvider']) {

                if ($lastProvider['rowStart'] > 0) {

                    $activeSheet->getStyle('C'.$lastProvider['rowStart'].':C'.($rowCtr-1))->applyFromArray(array(
                        'borders' => array(
                            'allborders' => array(
                                'style' => \PHPExcel_Style_Border::BORDER_THIN
                            )
                        )
                    ));
                    $activeSheet->mergeCells('C'.$lastProvider['rowStart'].':C'.($rowCtr-1));
                    $activeSheet->getStyle('C'.$lastProvider['rowStart'])->applyFromArray(array(
                        'alignment' => array(
                            'vertical' => \PHPExcel_Style_Alignment::VERTICAL_CENTER,
                            'horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
                        ),
                        'fill' => array(
                            'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                            'color' => array('rgb' => 'E2EFDD')
                        ),
                    ));

                    $activeSheet->setCellValue('C'.$rowCtr, 'Total');
                    $activeSheet->getStyle('C'.$rowCtr)->applyFromArray(array(
                        'alignment' => array(
                            'horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_RIGHT,

                        )
                    ));
                    $activeSheet->setCellValue('L'.$rowCtr, $lastProvider['total']);
                    $activeSheet->mergeCells('D'.$rowCtr.':K'.$rowCtr);
                    $activeSheet->getStyle('C'.$rowCtr.':L'.$rowCtr)->applyFromArray(array(
                        'fill' => array(
                            'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                            'color' => array('rgb' => 'E2EFDD')
                        ),
                        'borders' => array(
                            'allborders' => array(
                                'style' => \PHPExcel_Style_Border::BORDER_THIN
                            )
                        )
                    ));
                    $rowCtr++;
                }

                $activeSheet->setCellValue('C'.$rowCtr, $record['referringProvider']);

                $lastProvider = array(
                    'name' =>  $record['referringProvider'],
                    'rowStart' => $rowCtr,
                    'total' => 0
                );

            }
            $lastProvider['total']++;
            $lastCompany['total']++;
            $lastHealthFacility['total']++;


            $activeSheet->setCellValue('D'.$rowCtr, $record['patientName']);
            $activeSheet->setCellValue('E'.$rowCtr, $record['referral_date']);
            $activeSheet->setCellValue('F'.$rowCtr, $record['receive_date']);
            $activeSheet->setCellValue('G'.$rowCtr, $record['chartType']);
            $activeSheet->setCellValue('H'.$rowCtr, $record['chartStatus']);
            $activeSheet->setCellValue('I'.$rowCtr, $record['sold']);
            $activeSheet->setCellValue('J'.$rowCtr, $record['agent']);
            $activeSheet->setCellValue('K'.$rowCtr, $record['cpapSetupSold']);
            $activeSheet->setCellValue('L'.$rowCtr, 1);
        }
        $rowCtr++;

        if ($lastCompany['rowStart'] > 0) {

            //
            $activeSheet->getStyle('C'.$lastProvider['rowStart'].':C'.($rowCtr-1))->applyFromArray(array(
                'borders' => array(
                    'allborders' => array(
                        'style' => \PHPExcel_Style_Border::BORDER_THIN
                    )
                )
            ));
            $activeSheet->mergeCells('C'.$lastProvider['rowStart'].':C'.($rowCtr-1));
            $activeSheet->getStyle('C'.$lastProvider['rowStart'])->applyFromArray(array(
                'alignment' => array(
                    'vertical' => \PHPExcel_Style_Alignment::VERTICAL_CENTER,
                    'horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER,

                ),
                'fill' => array(
                    'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                    'color' => array('rgb' => 'E2EFDD')
                ),
            ));

            $activeSheet->setCellValue('C'.$rowCtr, 'Total');
            $activeSheet->getStyle('C'.$rowCtr)->applyFromArray(array(
                'alignment' => array(
                    'horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_RIGHT,
                ),

            ));

            $activeSheet->setCellValue('L'.$rowCtr, $lastHealthFacility['total']);
            $activeSheet->mergeCells('C'.$rowCtr.':K'.$rowCtr);
            $activeSheet->getStyle('B'.$rowCtr.':L'.$rowCtr)->applyFromArray(array(
                'fill' => array(
                    'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                    'color' => array('rgb' => 'E2EFDD')
                ),
                'borders' => array(
                    'allborders' => array(
                        'style' => \PHPExcel_Style_Border::BORDER_THIN
                    )
                ),
            ));
            $rowCtr++;
            //

            //
            $activeSheet->getStyle('B'.$lastHealthFacility['rowStart'].':B'.($rowCtr-1))->applyFromArray(array(
                'borders' => array(
                    'allborders' => array(
                        'style' => \PHPExcel_Style_Border::BORDER_THIN
                    )
                )
            ));
            $activeSheet->mergeCells('B'.$lastHealthFacility['rowStart'].':B'.($rowCtr-1));
            $activeSheet->getStyle('B'.$lastHealthFacility['rowStart'])->applyFromArray(array(
                'alignment' => array(
                    'vertical' => \PHPExcel_Style_Alignment::VERTICAL_CENTER,
                    'horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
                ),
                'fill' => array(
                    'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                    'color' => array('rgb' => 'ACB9CA')
                ),
            ));

            $activeSheet->setCellValue('B'.$rowCtr, 'Total');
            $activeSheet->getStyle('B'.$rowCtr)->applyFromArray(array(
                'alignment' => array(
                    'horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_RIGHT,
                )
            ));

            $activeSheet->setCellValue('L'.$rowCtr, $lastHealthFacility['total']);
            $activeSheet->mergeCells('C'.$rowCtr.':K'.$rowCtr);
            $activeSheet->getStyle('B'.$rowCtr.':L'.$rowCtr)->applyFromArray(array(
                'fill' => array(
                    'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                    'color' => array('rgb' => 'ACB9CA')
                ),
                'borders' => array(
                    'allborders' => array(
                        'style' => \PHPExcel_Style_Border::BORDER_THIN
                    )
                )
            ));
            $rowCtr++;
            //

            $activeSheet->getStyle('A'.$lastCompany['rowStart'].':A'.($rowCtr-1))->applyFromArray(array(
                'borders' => array(
                    'allborders' => array(
                        'style' => \PHPExcel_Style_Border::BORDER_THIN
                    )
                )
            ));
            $activeSheet->mergeCells('A'.$lastCompany['rowStart'].':A'.($rowCtr-1));
            $activeSheet->getStyle('A'.$lastCompany['rowStart'])->applyFromArray(array(
                'alignment' => array(
                    'vertical' => \PHPExcel_Style_Alignment::VERTICAL_CENTER,
                    'horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
                ),
                'fill' => array(
                    'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                    'color' => array('rgb' => 'DBDBDB')
                ),
            ));

            $activeSheet->setCellValue('A'.$rowCtr, 'Total');
            $activeSheet->getStyle('A'.$rowCtr)->applyFromArray(array(
                'alignment' => array(
                    'horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_RIGHT,

                )
            ));

            $activeSheet->setCellValue('L'.$rowCtr, $lastHealthFacility['total']);
            $activeSheet->mergeCells('C'.$rowCtr.':K'.$rowCtr);
            $activeSheet->getStyle('B'.$rowCtr.':L'.$rowCtr)->applyFromArray(array(
                'fill' => array(
                    'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                    'color' => array('rgb' => 'DBDBDB')
                ),
                'borders' => array(
                    'allborders' => array(
                        'style' => \PHPExcel_Style_Border::BORDER_THIN
                    )
                )
            ));
        }

        $rowCtr++;
        $activeSheet->setCellValue('L'.$rowCtr, 'Total Records: ' . $totalCount);

        $page_title = 'Marketing Referral Report';

        $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;
    }

    //Pending Payment Report
    /**
     * @Route("/pending_payment", name="report_pending_payment")
     */
    public function pendingPaymentAction() {

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

        $page_title = 'Pending Payment Report';
        return $this->render('@RxConnexion/Report/PendingPayment/index.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/pending-payment/pending-payment.js')
        ));
    }

//    /**
//     * @Route(
//     *      "/pending_payment/preview",
//     *      name = "report_pending_payment_preview"
//     * )
//     */
//    public function pendingPayment_previewAction() {
//
//        $authService = $this->get('rx_connexion.authService');
//        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
//        if(!$authService->isUserHasAccesses(array('Admin Report Pending Payment Preview'))) return $authService->redirectToHome();
//
//        ini_set('memory_limit', '2048M');
//        set_time_limit(0);
//
//        $em = $this->getDoctrine()->getManager();
//        $records = $em->getRepository('RxConnexionBundle:PatientChartPaymentEntity')->reportPendingPayment($this->get('session')->get('userData'));
//
//        $page_title = 'Pending Payment Report';
//        return $this->render('@RxConnexion/Report/PendingPayment/preview.html.twig', array(
////            'title' => $page_title,
////            'page_title' => $page_title,
//            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
//            'javascripts' => array('rxconnexion/admin/js/report/report_preview.js'),
////            'records' => $records
//        ));
//    }
//
//    /**
//     * @Route(
//     *      "/pending_payment/export_to_pdf",
//     *      name = "report_pending_payment_export_to_pdf"
//     * )
//     */
//    public function pendingPayment_export_to_pdfAction() {
//
//        $authService = $this->get('rx_connexion.authService');
//        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
//        if(!$authService->isUserHasAccesses(array('Admin Report Pending Payment Pdf'))) return $authService->redirectToHome();
//
//        ini_set('memory_limit', '2048M');
//        set_time_limit(0);
//
//        $em = $this->getDoctrine()->getManager();
//        $records = $em->getRepository('RxConnexionBundle:PatientChartPaymentEntity')->reportPendingPayment($this->get('session')->get('userData'));
//
//        $page_title = 'Pending Payment Report';
//        $content = $this->renderView('@RxConnexion/Report/PendingPayment/preview2.wkpdf.twig', array());
//
//        $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content);
//
//        $pdfResponse = array(
//            'success' => true,
//            'msg' => 'PDF was successfully generated.',
//            'pdfBase64' => base64_encode($xml)
//        );
//        if($pdfResponse['success']) {
//            $pdfContent = $pdfResponse['pdfBase64'];
//            return new Response(base64_decode($pdfContent), 200, array(
//                'Content-Type' => 'application/pdf',
//                'Content-Disposition'   => 'attachment; filename="Pending Payment Report' . date('m/d/Y') . ' Details.pdf"'
//            ));
//        } else {
//            $this->get('session')->getFlashBag()->set('error_messages', $pdfResponse['msg']);
//            return $this->redirect($this->generateUrl('report_pending_payment', 302));
//        }
//    }
//
//    /**
//     * @Route(
//     *      "/pending_payment/export_to_excel",
//     *      name = "report_pending_payment_export_to_excel"
//     * )
//     */
//    public function pendingPayment_export_to_excelAction() {
//
//        $authService = $this->get('rx_connexion.authService');
//        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
//        if(!$authService->isUserHasAccesses(array('Admin Report Pending Payment Excel'))) return $authService->redirectToHome();
//
//        ini_set('memory_limit', '2048M');
//        set_time_limit(0);
//
//        $em = $this->getDoctrine()->getManager();
//        $records = $em->getRepository('RxConnexionBundle:PatientChartPaymentEntity')->reportPendingPayment($this->get('session')->get('userData'));
//
//        $columnRange = range('A', 'L');
//        $cellsData = array(
//            array('cell' => 'A1', 'data' => 'Health Facility'),
//            array('cell' => 'B1', 'data' => 'Chart'),
//            array('cell' => 'C1', 'data' => 'Chart Date'),
//            array('cell' => 'D1', 'data' => 'Full Name'),
//            array('cell' => 'E1', 'data' => 'Status')
//        );
//        $rowCtr = 1;
//        $totalCount = 0;
//
//        foreach($records as $record) {
//
//            $rowCtr++;
//            $totalCount++;
//
//            $cellsData[] = array('cell' => "A$rowCtr", 'data' => $record['health_facility_desc']);
//            $cellsData[] = array('cell' => "B$rowCtr", 'data' => $record['chart_type_desc']);
//            $cellsData[] = array('cell' => "C$rowCtr", 'data' => $record['chart_date']);
//            $cellsData[] = array('cell' => "D$rowCtr", 'data' => $record['provider_fullName']);
//            $cellsData[] = array('cell' => "E$rowCtr", 'data' => $record['chart_status_desc']);
//        }
//
//        $rowCtr++;
//        $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Total Records: ' . $totalCount);
//
//
//        $page_title = 'Pending Payment Report';
//        return $this->export_to_excel($columnRange, $cellsData, $page_title);
//    }

    //Sales Report
    /**
     * @Route("/sales", name="report_sales")
     */
    public function salesAction() {

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

        $page_title = 'Sales Report';
        return $this->render('@RxConnexion/Report/Sales/index.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/sales/sales.js')
        ));
    }

    /**
     * @Route(
     *      "/sales/preview",
     *      name = "report_sales_preview"
     * )
     */
    public function sales_previewAction() {

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientChartPaymentEntity')->reportSales($this->get('session')->get('userData'));

        $page_title = 'Sales Report';
        return $this->render('@RxConnexion/Report/Sales/preview.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'javascripts' => array('rxconnexion/admin/js/report/report_preview.js'),
            'records' => $records
        ));
    }

    /**
     * @Route(
     *      "/sales/export_to_pdf",
     *      name = "report_sales_export_to_pdf"
     * )
     */
    public function sales_export_to_pdfAction() {

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientChartPaymentEntity')->reportSales($this->get('session')->get('userData'));

        $page_title = 'Sales Report';
        $content = $this->renderView('@RxConnexion/Report/Sales/preview.wkpdf.twig', array(
            'page_title' => $page_title,
            'records' => $records
        ));

        $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content, array(
            'orientation'=>'Landscape',
            'dpi' => 72,
            // 'disable-smart-shrinking',
            'zoom' => 'LINUX' == strtoupper(PHP_OS) ? 0.78 : 1
        ));

        $pdfResponse = array(
            'success' => true,
            'msg' => 'PDF was successfully generated.',
            'pdfBase64' => base64_encode($xml)
        );
        if($pdfResponse['success']) {
            $pdfContent = $pdfResponse['pdfBase64'];
            return new Response(base64_decode($pdfContent), 200, array(
                'Content-Type' => 'application/pdf',
                'Content-Disposition'   => 'attachment; filename="Sales Report' . date('m/d/Y') . ' Details.pdf"'
            ));
        } else {
            $this->get('session')->getFlashBag()->set('error_messages', $pdfResponse['msg']);
            return $this->redirect($this->generateUrl('report_sales', 302));
        }
    }

    /**
     * @Route(
     *      "/sales/export_to_excel",
     *      name = "report_sales_export_to_excel"
     * )
     */
    public function sales_export_to_excelAction() {

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientChartPaymentEntity')->reportSales($this->get('session')->get('userData'));

        $columnRange = range('A', 'L');
        $cellsData = array(
            array('cell' => 'A1', 'data' => 'Health Facility'),
            array('cell' => 'B1', 'data' => 'Chart'),
            array('cell' => 'C1', 'data' => 'Chart Date'),
            array('cell' => 'D1', 'data' => 'Full Name'),
            array('cell' => 'E1', 'data' => 'Status')
        );
        $rowCtr = 1;
        $totalCount = 0;

        foreach($records as $record) {

            $rowCtr++;
            $totalCount++;

            $cellsData[] = array('cell' => "A$rowCtr", 'data' => $record['health_facility_desc']);
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => $record['chart_type_desc']);
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => $record['chart_date']);
            $cellsData[] = array('cell' => "D$rowCtr", 'data' => $record['provider_fullName']);
            $cellsData[] = array('cell' => "E$rowCtr", 'data' => $record['chart_status_desc']);
        }

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


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

    //Productivity Report
    /**
     * @Route("/productivity", name="report_productivity")
     */
    public function productivityAction() {

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

        $session = $this->get('session');
        $userData = $session->get('userData');
        $em = $this->getDoctrine()->getManager();
        $encounterType = $em->getRepository('RxConnexionBundle:ChartTypeEntity')->chartTypeForMultiple();
        $branch = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->branchesForMultiple($userData);
        $clinicians = $em->getRepository('RxConnexionBundle:ProviderEntity')->clinicianForMultiple();

        $page_title = 'Productivity Report';
        return $this->render('@RxConnexion/Report/Productivity/index.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'encounterType' => $encounterType,
            'branch' => $branch,
            'clinician' => $clinicians,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/productivity/productivity.js')
        ));
    }

    /**
     * @Route(
     *      "/productivity/preview/{date_from}/{date_to}/{branch_id}/{exam_type_id}/{clinician}",
     *      name = "report_productivity_preview"
     * )
     */
    public function productivity_previewAction($date_from, $date_to, $branch_id, $exam_type_id, $clinician) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Productivity Clinical Preview'))) return $authService->redirectToHome();

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

        $em = $this->getDoctrine()->getManager();
        $productivity = $em->getRepository('RxConnexionBundle:PatientChartEntity')->productivityReport(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'branch' => $branch_id,
            'encounter_type' => $exam_type_id,
            'clinician' => $clinician,
        ));

        $page_title = 'Productivity Report';
        return $this->render('@RxConnexion/Report/Productivity/preview.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'javascripts' => array('rxconnexion/admin/js/report/report_preview.js'),
            'records' => $productivity,
            'dateFrom' => $date_from,
            'dateTo' => $date_to,
            'branchId' => $branch_id,
            'examTypeId' => $exam_type_id
        ));
    }

    /**
     * @Route(
     *      "/productivity/export_to_pdf/{date_from}/{date_to}/{branch_id}/{exam_type_id}/{clinician}",
     *      name = "report_productivity_export_to_pdf"
     * )
     */
    public function productivity_export_to_pdfAction($date_from, $date_to, $branch_id, $exam_type_id, $clinician) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Productivity Clinical Pdf'))) return $authService->redirectToHome();

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientChartEntity')->productivityReport(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'branch' => $branch_id,
            'encounter_type' => $exam_type_id,
            'clinician' => $clinician,
        ));

        $page_title = 'Productivity Report';
        $content = $this->renderView('@RxConnexion/Report/Productivity/preview.wkpdf.twig', array(
            'page_title' => $page_title,
            'records' => $records
        ));

        $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content, array(
            'orientation'=>'Landscape',
            'dpi' => 72,
            // 'disable-smart-shrinking',
            'zoom' => 'LINUX' == strtoupper(PHP_OS) ? 0.78 : 1
        ));

        $pdfResponse = array(
            'success' => true,
            'msg' => 'PDF was successfully generated.',
            'pdfBase64' => base64_encode($xml)
        );
        if($pdfResponse['success']) {
            $pdfContent = $pdfResponse['pdfBase64'];
            return new Response(base64_decode($pdfContent), 200, array(
                'Content-Type' => 'application/pdf',
                'Content-Disposition'   => 'attachment; filename="Productivity Report' . date('m/d/Y') . ' Details.pdf"'
            ));
        } else {
            $this->get('session')->getFlashBag()->set('error_messages', $pdfResponse['msg']);
            return $this->redirect($this->generateUrl('report_productivity', 302));
        }
    }

    /**
     * @Route(
     *      "/productivity/export_to_excel/{date_from}/{date_to}/{branch_id}/{exam_type_id}/{clinician}",
     *      name = "report_productivity_export_to_excel"
     * )
     */
    public function productivity_export_to_excelAction($date_from, $date_to, $branch_id, $exam_type_id, $clinician) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Productivity Clinical Excel'))) return $authService->redirectToHome();

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

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

        $columnRange = range('A', 'Z');

        $phpExcelObject = $this->get('phpexcel')->createPHPExcelObject();
        $activeSheet = $phpExcelObject->setActiveSheetIndex(0);
        $activeSheet->setCellValue('A1', 'Productivity Report : From '.$date_from.' To '.$date_to);

        $activeSheet->getStyle('A1')->applyFromArray(array(
            'fill' => array(
                'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                'color' => array('rgb' => 'ADD8E6')
            ),
            'borders' => array(
                'allborders' => array(
                    'style' => \PHPExcel_Style_Border::BORDER_THIN
                )
            )
        ));

        $records = $em->getRepository('RxConnexionBundle:PatientChartEntity')->productivityReport(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'branch' => $branch_id,
            'encounter_type' => $exam_type_id,
            'clinician' => $clinician
        ));


        $rowCtr = 3;
        $providersColumn = 'B';
        $TotalsColumn = 'B';
        foreach ($records as $record) {

            $rowCtr++;
            $activeSheet->setCellValue('A'.$rowCtr, $record['description']);
            $activeSheet->getStyle('A'.$rowCtr.':AE'.$rowCtr)->applyFromArray(array(
                'fill' => array(
                    'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                    'color' => array('rgb' => 'C3CFEF')
                ),
            ));

            $rowCtr++;
            $activeSheet->setCellValue('A'.$rowCtr, 'Activity / Services')->getStyle( 'A'.$rowCtr )->getFont()->setBold( true );
            $activeSheet->getStyle('A'.$rowCtr.':Z'.$rowCtr)->applyFromArray(array(
                'fill' => array(
                    'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                    'color' => array('rgb' => 'ADD8E6')
                ),
                'borders' => array(
                    'allborders' => array(
                        'style' => \PHPExcel_Style_Border::BORDER_THIN
                    )
                )
            ));
            foreach ($record['providers'] as $providers) {
                $activeSheet->setCellValue($providersColumn.$rowCtr, $providers['name'])->getStyle( $providersColumn.$rowCtr )->getFont()->setBold( true );
                $providersColumn++;
            }
            $activeSheet->setCellValue($providersColumn.$rowCtr, 'Total')->getStyle( $TotalsColumn.$rowCtr )->getFont()->setBold( true );

            $subTotal = 0;
            foreach ($record['chartTypes'] as $chartTypes) {
                $rowCtr++;
                $activeSheet->setCellValue('A'.$rowCtr, $chartTypes['description'])->getStyle( $TotalsColumn.$rowCtr )->getFont()->setBold( true );
                $activeSheet->getStyle('A'.$rowCtr)->applyFromArray(array(
                    'fill' => array(
                        'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                        'color' => array('rgb' => '9396B5')
                    ),
                    'borders' => array(
                        'allborders' => array(
                            'style' => \PHPExcel_Style_Border::BORDER_THIN
                        )
                    )
                ));


                $providerTotals = 0;
                foreach ($record['providers'] as $pv) {
                    foreach ($chartTypes['providers'] as $ct) {
                        if($ct['id'] == $pv['id']) {
                            $providerTotals = $providerTotals + $ct['count'];
                        }
                    }
                }

                $totals = 0;
                foreach ($record['providers'] as $pv) {
                    $ifZero = 0;
                    $percentage = 0;
                    foreach ($chartTypes['providers'] as $ct) {
                        if($ct['id'] == $pv['id']) {
                            $activeSheet->setCellValue($TotalsColumn.$rowCtr, $ct['count'])->getStyle( $TotalsColumn.$rowCtr )->getFont()->setBold( true );
                            $ifZero = $ct['count'];
                            $totals = $totals + $ct['count'];
                            $percentage = ($ct['count']/$providerTotals) * 100;
                            $subTotal = $subTotal + $ct['count'];
                        }
                    }
                    $activeSheet->setCellValue($TotalsColumn.$rowCtr, $ifZero.' ('.round($percentage).' %)')->getStyle( $TotalsColumn.$rowCtr )->getFont()->setBold( true );
                    $TotalsColumn++;
                }

                $activeSheet->setCellValue($TotalsColumn.$rowCtr, $totals)->getStyle( $TotalsColumn.$rowCtr )->getFont()->setBold( true );
                $activeSheet->getStyle($TotalsColumn.$rowCtr)->applyFromArray(array(
                    'fill' => array(
                        'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                        'color' => array('rgb' => '428AF5')
                    ),
                ));

                $TotalsColumn = 'B';
            }

            $rowCtr++;
            $activeSheet->setCellValue('A'.$rowCtr, 'Total')->getStyle( 'A'.$rowCtr )->getFont()->setBold( true );

            $columnTotal = 'B';
            foreach ($record['providers'] as $provider) {
                $bottomTotal = 0;
                $totalPercentage = 0;
                foreach ($record['chartTypes'] as $chartTypes) {
                    foreach ($chartTypes['providers'] as $pr) {
                        if ($pr['id'] == $provider['id']) {
                            $bottomTotal = $bottomTotal + $pr['count'];
                            $totalPercentage = ($bottomTotal / $subTotal) * 100;
                        }


                    }
                }
                $activeSheet->setCellValue($columnTotal.$rowCtr, $bottomTotal.' ('.round($totalPercentage).'%)')->getStyle( $columnTotal.$rowCtr )->getFont()->setBold( true );
                $activeSheet->getStyle($columnTotal.$rowCtr)->applyFromArray(array(
                    'fill' => array(
                        'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                        'color' => array('rgb' => '428AF5')
                    ),
                ));
                $columnTotal++;
            }
            $activeSheet->setCellValue($columnTotal.$rowCtr, $subTotal)->getStyle( $columnTotal.$rowCtr )->getFont()->setBold( true );
            $activeSheet->getStyle($columnTotal.$rowCtr)->applyFromArray(array(
                'fill' => array(
                    'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                    'color' => array('rgb' => '088C1C')
                ),
            ));

            $rowCtr++;
            $providersColumn = 'B';
        }

        $page_title = 'Productivity Report (Clinical)';
        $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;
    }


    //Productivity Clinician Report
    /**
     * @Route("/productivity_clinician", name="report_clinician_productivity")
     */
    public function productivityClinicianAction() {

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

        $session = $this->get('session');
        $userData = $session->get('userData');
        $em = $this->getDoctrine()->getManager();
        $encounterType = $em->getRepository('RxConnexionBundle:ChartTypeEntity')->chartTypeForMultiple();
        $branch = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->branchesForMultiple($userData);
        $clinicians = $em->getRepository('RxConnexionBundle:ProviderEntity')->clinicianForMultiple();

        $page_title = 'Clinician Productivity Report';
        return $this->render('@RxConnexion/Report/ProductivityClinician/index.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'encounterType' => $encounterType,
            'branch' => $branch,
            'clinician' => $clinicians,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/productivityClinician/productivityClinician.js')
        ));
    }

    /**
     * @Route(
     *      "/productivity_clinician/preview/{date_from}/{date_to}/{branch_id}/{exam_type_id}/{clinician}",
     *      name = "report_clinician_productivity_preview"
     * )
     */
    public function productivityClinician_previewAction($date_from, $date_to, $branch_id, $exam_type_id, $clinician) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Productivity Clinician Preview'))) return $authService->redirectToHome();

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

        $em = $this->getDoctrine()->getManager();
        $productivity = $em->getRepository('RxConnexionBundle:PatientChartEntity')->productivityClinicianReport(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'branch' => $branch_id,
            'encounter_type' => $exam_type_id,
            'clinician' => $clinician,
        ));

        $productivitySummary = $em->getRepository('RxConnexionBundle:PatientChartEntity')->productivityClinicianSummary(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'branch' => $branch_id,
            'encounter_type' => $exam_type_id,
            'clinician' => $clinician,
        ));

        $productivitySummaryHf = $em->getRepository('RxConnexionBundle:PatientChartEntity')->productivityClinicianSummaryHf(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'branch' => $branch_id,
            'encounter_type' => $exam_type_id,
            'clinician' => $clinician,
        ));


        $page_title = 'Clinician Productivity Report';
        return $this->render('@RxConnexion/Report/ProductivityClinician/preview.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'javascripts' => array('rxconnexion/admin/js/report/report_preview.js'),
            'records' => $productivity,
            'summary' => $productivitySummary,
            'summaryHf' => $productivitySummaryHf,
            'dateFrom' => $date_from,
            'dateTo' => $date_to,
            'branchId' => $branch_id,
            'examTypeId' => $exam_type_id
        ));
    }

    /**
     * @Route(
     *      "/productivity_clinician/export_to_pdf/{date_from}/{date_to}/{branch_id}/{exam_type_id}/{clinician}",
     *      name = "report_clinician_productivity_export_to_pdf"
     * )
     */
    public function productivityClinician_export_to_pdfAction($date_from, $date_to, $branch_id, $exam_type_id, $clinician) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Productivity Clinician Pdf'))) return $authService->redirectToHome();

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientChartEntity')->productivityClinicianReport(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'branch' => $branch_id,
            'encounter_type' => $exam_type_id,
            'clinician' => $clinician,
        ));

        $page_title = 'Clinician Productivity Report';
        $content = $this->renderView('@RxConnexion/Report/ProductivityClinician/preview.wkpdf.twig', array(
            'page_title' => $page_title,
            'records' => $records
        ));

        $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content, array(
            'orientation'=>'Landscape',
            'dpi' => 72,
            // 'disable-smart-shrinking',
            'zoom' => 'LINUX' == strtoupper(PHP_OS) ? 0.78 : 1
        ));

        $pdfResponse = array(
            'success' => true,
            'msg' => 'PDF was successfully generated.',
            'pdfBase64' => base64_encode($xml)
        );
        if($pdfResponse['success']) {
            $pdfContent = $pdfResponse['pdfBase64'];
            return new Response(base64_decode($pdfContent), 200, array(
                'Content-Type' => 'application/pdf',
                'Content-Disposition'   => 'attachment; filename="Productivity Report' . date('m/d/Y') . ' Details.pdf"'
            ));
        } else {
            $this->get('session')->getFlashBag()->set('error_messages', $pdfResponse['msg']);
            return $this->redirect($this->generateUrl('report_productivity', 302));
        }
    }

    /**
     * @Route(
     *      "/productivity_clinician/export_to_excel/{date_from}/{date_to}/{branch_id}/{exam_type_id}/{clinician}",
     *      name = "report_clinician_productivity_export_to_excel"
     * )
     */
    public function productivityClinician_export_to_excelAction($date_from, $date_to, $branch_id, $exam_type_id, $clinician) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Productivity Clinician Excel'))) return $authService->redirectToHome();

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

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

        $columnRange = range('A', 'Z');

        $phpExcelObject = $this->get('phpexcel')->createPHPExcelObject();
        $activeSheet = $phpExcelObject->setActiveSheetIndex(0);
        $activeSheet->setCellValue('A1', 'Productivity Clinician Report : From '.$date_from.' To '.$date_to);

        $activeSheet->getStyle('A1')->applyFromArray(array(
            'fill' => array(
                'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                'color' => array('rgb' => 'ADD8E6')
            ),
            'borders' => array(
                'allborders' => array(
                    'style' => \PHPExcel_Style_Border::BORDER_THIN
                )
            )
        ));

        $records = $em->getRepository('RxConnexionBundle:PatientChartEntity')->productivityClinicianReport(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'branch' => $branch_id,
            'encounter_type' => $exam_type_id,
            'clinician' => $clinician
        ));


        $rowCtr = 3;
        $providersColumn = 'B';
        $TotalsColumn = 'B';
        foreach ($records as $record) {

            $rowCtr++;
            $activeSheet->setCellValue('A'.$rowCtr, $record['description']);
            $activeSheet->getStyle('A'.$rowCtr.':AE'.$rowCtr)->applyFromArray(array(
                'fill' => array(
                    'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                    'color' => array('rgb' => 'C3CFEF')
                ),
            ));

            $rowCtr++;
            $activeSheet->setCellValue('A'.$rowCtr, 'Activity / Services')->getStyle( 'A'.$rowCtr )->getFont()->setBold( true );
            $activeSheet->getStyle('A'.$rowCtr.':Z'.$rowCtr)->applyFromArray(array(
                'fill' => array(
                    'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                    'color' => array('rgb' => 'ADD8E6')
                ),
                'borders' => array(
                    'allborders' => array(
                        'style' => \PHPExcel_Style_Border::BORDER_THIN
                    )
                )
            ));
            foreach ($record['providers'] as $providers) {
                $activeSheet->setCellValue($providersColumn.$rowCtr, $providers['name'])->getStyle( $providersColumn.$rowCtr )->getFont()->setBold( true );
                $providersColumn++;
            }
            $activeSheet->setCellValue($providersColumn.$rowCtr, 'Total')->getStyle( $TotalsColumn.$rowCtr )->getFont()->setBold( true );

            $subTotal = 0;
            foreach ($record['chartTypes'] as $chartTypes) {
                $rowCtr++;
                $activeSheet->setCellValue('A'.$rowCtr, $chartTypes['description'])->getStyle( $TotalsColumn.$rowCtr )->getFont()->setBold( true );
                $activeSheet->getStyle('A'.$rowCtr)->applyFromArray(array(
                    'fill' => array(
                        'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                        'color' => array('rgb' => '9396B5')
                    ),
                    'borders' => array(
                        'allborders' => array(
                            'style' => \PHPExcel_Style_Border::BORDER_THIN
                        )
                    )
                ));


                $providerTotals = 0;
                foreach ($record['providers'] as $pv) {
                    foreach ($chartTypes['providers'] as $ct) {
                        if($ct['id'] == $pv['id']) {
                            $providerTotals = $providerTotals + $ct['count'];
                        }
                    }
                }

                $totals = 0;
                foreach ($record['providers'] as $pv) {
                    $ifZero = 0;
                    $percentage = 0;
                    foreach ($chartTypes['providers'] as $ct) {
                        if($ct['id'] == $pv['id']) {
                            $activeSheet->setCellValue($TotalsColumn.$rowCtr, $ct['count'])->getStyle( $TotalsColumn.$rowCtr )->getFont()->setBold( true );
                            $ifZero = $ct['count'];
                            $totals = $totals + $ct['count'];
                            $percentage = ($ct['count']/$providerTotals) * 100;
                            $subTotal = $subTotal + $ct['count'];
                        }
                    }
                    $activeSheet->setCellValue($TotalsColumn.$rowCtr, $ifZero.' ('.round($percentage).' %)')->getStyle( $TotalsColumn.$rowCtr )->getFont()->setBold( true );
                    $TotalsColumn++;
                }

                $activeSheet->setCellValue($TotalsColumn.$rowCtr, $totals)->getStyle( $TotalsColumn.$rowCtr )->getFont()->setBold( true );
                $activeSheet->getStyle($TotalsColumn.$rowCtr)->applyFromArray(array(
                    'fill' => array(
                        'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                        'color' => array('rgb' => '428AF5')
                    ),
                ));

                $TotalsColumn = 'B';
            }

            $rowCtr++;
            $activeSheet->setCellValue('A'.$rowCtr, 'Total')->getStyle( 'A'.$rowCtr )->getFont()->setBold( true );

            $columnTotal = 'B';
            foreach ($record['providers'] as $provider) {
                $bottomTotal = 0;
                $totalPercentage = 0;
                foreach ($record['chartTypes'] as $chartTypes) {
                    foreach ($chartTypes['providers'] as $pr) {
                        if ($pr['id'] == $provider['id']) {
                            $bottomTotal = $bottomTotal + $pr['count'];
                            $totalPercentage = ($bottomTotal / $subTotal) * 100;
                        }


                    }
                }
                $activeSheet->setCellValue($columnTotal.$rowCtr, $bottomTotal.' ('.round($totalPercentage).'%)')->getStyle( $columnTotal.$rowCtr )->getFont()->setBold( true );
                $activeSheet->getStyle($columnTotal.$rowCtr)->applyFromArray(array(
                    'fill' => array(
                        'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                        'color' => array('rgb' => '428AF5')
                    ),
                ));
                $columnTotal++;
            }
            $activeSheet->setCellValue($columnTotal.$rowCtr, $subTotal)->getStyle( $columnTotal.$rowCtr )->getFont()->setBold( true );
            $activeSheet->getStyle($columnTotal.$rowCtr)->applyFromArray(array(
                'fill' => array(
                    'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                    'color' => array('rgb' => '088C1C')
                ),
            ));

            $rowCtr++;
            $providersColumn = 'B';
        }

        $page_title = 'Clinician Productivity Report';
        $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;
    }


    //Productivity Report (Billing)
    /**
     * @Route("/productivity_billing", name="report_productivity_billing")
     */
    public function productivityBillingAction() {

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

        $page_title = 'Productivity (Billing) Report';
        return $this->render('@RxConnexion/Report/ProductivityBilling/index.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/productivityBilling/productivityBilling.js')
        ));
    }

    /**
     * @Route(
     *      "/productivity_billing/preview/{date_from}/{date_to}",
     *      name = "report_productivity_billing_preview"
     * )
     */
    public function productivityBilling_previewAction($date_from, $date_to) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Productivity Billing Preview'))) return $authService->redirectToHome();

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

        $em = $this->getDoctrine()->getManager();
        $productivityBilling = $em->getRepository('RxConnexionBundle:PatientChartEntity')->productivityBillingReport(array(
            'date_from' => $date_from,
            'date_to' => $date_to
        ));

        $page_title = 'Productivity Report (Billing)';
        return $this->render('@RxConnexion/Report/ProductivityBilling/preview.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'javascripts' => array('rxconnexion/admin/js/report/report_preview.js'),
            'records' => $productivityBilling,
            'dateFrom' => $date_from,
            'dateTo' => $date_to,
        ));
    }

    /**
     * @Route(
     *      "/productivity_billing/export_to_pdf/{date_from}/{date_to}",
     *      name = "report_productivity_billing_export_to_pdf"
     * )
     */
    public function productivityBilling_export_to_pdfAction($date_from, $date_to) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Productivity Billing Pdf'))) return $authService->redirectToHome();

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientChartEntity')->productivityBillingReport(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
        ));

        $page_title = 'Productivity Report';
        $content = $this->renderView('@RxConnexion/Report/ProductivityBilling/preview.wkpdf.twig', array(
            'page_title' => $page_title,
            'records' => $records
        ));

        $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content, array(
            'orientation'=>'Landscape',
            'dpi' => 72,
            // 'disable-smart-shrinking',
            'zoom' => 'LINUX' == strtoupper(PHP_OS) ? 0.78 : 1
        ));

        $pdfResponse = array(
            'success' => true,
            'msg' => 'PDF was successfully generated.',
            'pdfBase64' => base64_encode($xml)
        );
        if($pdfResponse['success']) {
            $pdfContent = $pdfResponse['pdfBase64'];
            return new Response(base64_decode($pdfContent), 200, array(
                'Content-Type' => 'application/pdf',
                'Content-Disposition'   => 'attachment; filename="Productivity Report (Billing)' . date('m/d/Y') . ' Details.pdf"'
            ));
        } else {
            $this->get('session')->getFlashBag()->set('error_messages', $pdfResponse['msg']);
            return $this->redirect($this->generateUrl('report_productivity_billing', 302));
        }
    }

    /**
     * @Route(
     *      "/productivity_billing/export_to_excel/{date_from}/{date_to}",
     *      name = "report_productivity_billing_export_to_excel"
     * )
     */
    public function productivityBilling_export_to_excelAction($date_from, $date_to) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Productivity Billing Excel'))) return $authService->redirectToHome();

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

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

        $columnRange = range('A', 'Z');

        $phpExcelObject = $this->get('phpexcel')->createPHPExcelObject();
        $activeSheet = $phpExcelObject->setActiveSheetIndex(0);
        $activeSheet->setCellValue('A1', 'Productivity Billing Report : From '.$date_from.' To '.$date_to);

        $activeSheet->getStyle('A1')->applyFromArray(array(
            'fill' => array(
                'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                'color' => array('rgb' => 'ADD8E6')
            ),
            'borders' => array(
                'allborders' => array(
                    'style' => \PHPExcel_Style_Border::BORDER_THIN
                )
            )
        ));

        $records = $em->getRepository('RxConnexionBundle:PatientChartEntity')->productivityBillingReport(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
        ));

        $rowCtr = 3;
        $auBillingColumn = 'B';
        $TotalsColumn = 'B';
        $rowCtr++;

        $rowCtr++;
        $activeSheet->setCellValue('A'.$rowCtr, 'Activity / Services')->getStyle( 'A'.$rowCtr )->getFont()->setBold( true );

        foreach ($records as $record) {
            foreach ($record['auBilling'] as $userBilling) {
                $activeSheet->setCellValue($auBillingColumn.$rowCtr, $userBilling['name'])->getStyle( $auBillingColumn.$rowCtr )->getFont()->setBold( true );
                $auBillingColumn++;
            }
        }
        $activeSheet->setCellValue($auBillingColumn.$rowCtr, 'Total Actual Number')->getStyle( $auBillingColumn.$rowCtr )->getFont()->setBold( true );

        $activeSheet->getStyle('A'.$rowCtr.':'.$auBillingColumn.$rowCtr)->applyFromArray(array(
            'fill' => array(
                'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                'color' => array('rgb' => 'ADD8E6')
            ),
            'borders' => array(
                'allborders' => array(
                    'style' => \PHPExcel_Style_Border::BORDER_THIN
                )
            )
        ));
        foreach ($records as $record2) {
            foreach ($record2['chartTypes'] as $chartTypes) {
                $rowCtr++;
                $activeSheet->setCellValue('A'.$rowCtr, $chartTypes['description'])->getStyle( $TotalsColumn.$rowCtr )->getFont()->setBold( true );
                $activeSheet->getStyle('A'.$rowCtr)->applyFromArray(array(
                    'fill' => array(
                        'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                        'color' => array('rgb' => '9396B5')
                    ),
                    'borders' => array(
                        'allborders' => array(
                            'style' => \PHPExcel_Style_Border::BORDER_THIN
                        )
                    )
                ));

                foreach ($record2['auBilling'] as $auB) {
                    $ifZero = 0;
                    foreach ($chartTypes['auBilling'] as $ct) {
                        if($ct['auBilling_id'] == $auB['id']) {
                            $activeSheet->setCellValue($TotalsColumn.$rowCtr, $ct['totalCount'])->getStyle( $TotalsColumn.$rowCtr )->getFont()->setBold( true );
                            $ifZero = $ct['totalCount'];
                        }
                    }
                    $activeSheet->setCellValue($TotalsColumn.$rowCtr, $ifZero)->getStyle( $TotalsColumn.$rowCtr )->getFont()->setBold( true );
                    $TotalsColumn++;
                }

                $totalCount = 0;
                foreach ($record2['auBilling'] as $auB) {

                    foreach ($chartTypes['auBilling'] as $ct) {
                        if($ct['auBilling_id'] == $auB['id']) {
                            $totalCount = $totalCount + $ct['totalCount'];
                        }
                    }
                    $activeSheet->setCellValue($TotalsColumn.$rowCtr, $totalCount)->getStyle( $TotalsColumn.$rowCtr )->getFont()->setBold( true );
                }
                $TotalsColumn = 'B';

            }
        }

        $page_title = 'Productivity Billing Report';
        $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;
    }

    //Productivity CBT Encounters Report
    /**
     * @Route("/productivity_cbt_encounter", name="report_productivity_cbt_encounter")
     */
    public function productivityCbtEncounterAction() {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Productivity CBT Encounter'))) return $authService->redirectToHome();

        $page_title = 'Productivity CBT Encounter Report';
        return $this->render('@RxConnexion/Report/ProductivityCBTEncounter/index.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/productivityCbtEncounter/productivityCbtEncounter.js')
        ));
    }

    /**
     * @Route(
     *      "/productivity_cbt_encounter/preview/{date_from}/{date_to}",
     *      name = "report_productivity_cbt_encounter_preview"
     * )
     */
    public function productivityCbtEncounter_previewAction($date_from, $date_to) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Productivity CBT Encounter Preview'))) return $authService->redirectToHome();

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

        $em = $this->getDoctrine()->getManager();
        $productivityCbtEncounter = $em->getRepository('RxConnexionBundle:PatientChartEntity')->productivityCbtEncounter(array(
            'date_from' => $date_from,
            'date_to' => $date_to
        ));

        $page_title = 'Productivity CBT Encounter Report';
        return $this->render('@RxConnexion/Report/ProductivityCBTEncounter/preview.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'javascripts' => array('rxconnexion/admin/js/report/report_preview.js'),
            'records' => $productivityCbtEncounter,
            'dateFrom' => $date_from,
            'dateTo' => $date_to,
        ));
    }

    /**
     * @Route(
     *      "/productivity_cbt_encounter/export_to_pdf/{date_from}/{date_to}",
     *      name = "report_productivity_cbt_encounter_export_to_pdf"
     * )
     */
    public function productivityCbtEncounter_export_to_pdfAction($date_from, $date_to) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Productivity CBT Encounter Pdf'))) return $authService->redirectToHome();

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientChartEntity')->productivityCbtEncounter(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
        ));

        $page_title = 'Productivity CBT Encounter Report';
        $content = $this->renderView('@RxConnexion/Report/ProductivityCBTEncounter/preview.wkpdf.twig', array(
            'page_title' => $page_title,
            'records' => $records,
            'dateFrom' => $date_from,
            'dateTo' => $date_to,
        ));

        $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content, array(
            'orientation'=>'Landscape',
            'dpi' => 72,
            // 'disable-smart-shrinking',
            'zoom' => 'LINUX' == strtoupper(PHP_OS) ? 0.78 : 1
        ));

        $pdfResponse = array(
            'success' => true,
            'msg' => 'PDF was successfully generated.',
            'pdfBase64' => base64_encode($xml)
        );
        if($pdfResponse['success']) {
            $pdfContent = $pdfResponse['pdfBase64'];
            return new Response(base64_decode($pdfContent), 200, array(
                'Content-Type' => 'application/pdf',
                'Content-Disposition'   => 'attachment; filename="Productivity CBT Encounter Report' . date('m/d/Y') . ' Details.pdf"'
            ));
        } else {
            $this->get('session')->getFlashBag()->set('error_messages', $pdfResponse['msg']);
            return $this->redirect($this->generateUrl('report_productivity_cbt_encounter', 302));
        }
    }

    /**
     * @Route(
     *      "/productivity_cbt_encounter/export_to_excel/{date_from}/{date_to}",
     *      name = "report_productivity_cbt_encounter_export_to_excel"
     * )
     */
    public function productivityCbtEncounter_export_to_excelAction($date_from, $date_to) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Productivity CBT Encounter Excel'))) return $authService->redirectToHome();

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientChartEntity')->productivityCbtEncounter(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
        ));

        $columnRange = range('A', 'Z');

        $phpExcelObject = $this->get('phpexcel')->createPHPExcelObject();
        $activeSheet = $phpExcelObject->setActiveSheetIndex(0);
        $activeSheet->setCellValue('A1', 'Productivity CBT Encounter Report : From '.$date_from.' To '.$date_to);

        $activeSheet->getStyle('A1')->applyFromArray(array(
            'fill' => array(
                'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                'color' => array('rgb' => 'ADD8E6')
            ),
            'borders' => array(
                'allborders' => array(
                    'style' => \PHPExcel_Style_Border::BORDER_THIN
                )
            )
        ));

        $rowCtr = 4;
        $activeSheet->setCellValue('A'.$rowCtr, 'Activity');
        $activeSheet->setCellValue('B'.$rowCtr, 'Processed');
        $activeSheet->getStyle('A'.$rowCtr.':B'.$rowCtr)->applyFromArray(array(
            'fill' => array(
                'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                'color' => array('rgb' => 'C3CFEF')
            ),
        ));

        $rowCtr++;
        foreach ($records['encounterProcessed'] as $encounterProcessedRecord) {
            $rowCtr++;
            $activeSheet->setCellValue('A'.$rowCtr, $encounterProcessedRecord['chartType']);
            $activeSheet->setCellValue('B'.$rowCtr, $encounterProcessedRecord['processCount']);
        }
        $rowCtr++;
        foreach ($records['endorsed'] as $endrosedRecord) {
            $activeSheet->setCellValue('A'.$rowCtr, 'Endorsed');
            $activeSheet->setCellValue('B'.$rowCtr, $endrosedRecord['endorsedCount']);
        }

        $page_title = 'Prod. CBT(Encounter) Report';
        $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;
    }

    //Productivity CBT Scheduling Report
    /**
     * @Route("/productivity_cbt_scheduling", name="report_productivity_cbt_scheduling")
     */
    public function productivityCbtSchedulingAction() {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Productivity CBT Scheduling'))) return $authService->redirectToHome();

        $page_title = 'Productivity CBT Scheduling Report';
        return $this->render('@RxConnexion/Report/ProductivityCBTScheduling/index.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/productivityCbtEncounter/productivityCbtEncounter.js')
        ));
    }

    /**
     * @Route(
     *      "/productivity_cbt_scheduling/preview/{date_from}/{date_to}",
     *      name = "report_productivity_cbt_scheduling_preview"
     * )
     */
    public function productivityCbtScheduling_previewAction($date_from, $date_to) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Productivity CBT Scheduling Preview'))) return $authService->redirectToHome();

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

        $em = $this->getDoctrine()->getManager();
        $productivityCbtScheduling = $em->getRepository('RxConnexionBundle:PatientChartEntity')->productivityCbtScheduling(array(
            'date_from' => $date_from,
            'date_to' => $date_to
        ));

        $page_title = 'Productivity CBT Scheduling Report';
        return $this->render('@RxConnexion/Report/ProductivityCBTScheduling/preview.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'javascripts' => array('rxconnexion/admin/js/report/report_preview.js'),
            'records' => $productivityCbtScheduling,
            'dateFrom' => $date_from,
            'dateTo' => $date_to,
        ));
    }

    /**
     * @Route(
     *      "/productivity_cbt_scheduling/export_to_pdf/{date_from}/{date_to}",
     *      name = "report_productivity_cbt_scheduling_export_to_pdf"
     * )
     */
    public function productivityCbtScheduling_export_to_pdfAction($date_from, $date_to) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Productivity CBT Scheduling Pdf'))) return $authService->redirectToHome();

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientChartEntity')->productivityCbtScheduling(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
        ));

        $page_title = 'Productivity CBT Scheduling Report';
        $content = $this->renderView('@RxConnexion/Report/ProductivityCBTEncounter/preview.wkpdf.twig', array(
            'page_title' => $page_title,
            'records' => $records,
            'dateFrom' => $date_from,
            'dateTo' => $date_to,
        ));

        $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content, array(
            'orientation'=>'Landscape',
            'dpi' => 72,
            // 'disable-smart-shrinking',
            'zoom' => 'LINUX' == strtoupper(PHP_OS) ? 0.78 : 1
        ));

        $pdfResponse = array(
            'success' => true,
            'msg' => 'PDF was successfully generated.',
            'pdfBase64' => base64_encode($xml)
        );
        if($pdfResponse['success']) {
            $pdfContent = $pdfResponse['pdfBase64'];
            return new Response(base64_decode($pdfContent), 200, array(
                'Content-Type' => 'application/pdf',
                'Content-Disposition'   => 'attachment; filename="Productivity CBT Scheduling Report' . date('m/d/Y') . ' Details.pdf"'
            ));
        } else {
            $this->get('session')->getFlashBag()->set('error_messages', $pdfResponse['msg']);
            return $this->redirect($this->generateUrl('report_productivity_cbt_scheduling', 302));
        }
    }

    /**
     * @Route(
     *      "/productivity_cbt_scheduling/export_to_excel/{date_from}/{date_to}",
     *      name = "report_productivity_cbt_scheduling_export_to_excel"
     * )
     */
    public function productivityCbtScheduling_export_to_excelAction($date_from, $date_to) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Productivity CBT Scheduling Excel'))) return $authService->redirectToHome();

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientChartEntity')->productivityCbtScheduling(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
        ));

        $columnRange = range('A', 'Z');

        $phpExcelObject = $this->get('phpexcel')->createPHPExcelObject();
        $activeSheet = $phpExcelObject->setActiveSheetIndex(0);
        $activeSheet->setCellValue('A1', 'Productivity CBT Scheduling Report : From '.$date_from.' To '.$date_to);

        $activeSheet->getStyle('A1')->applyFromArray(array(
            'fill' => array(
                'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                'color' => array('rgb' => 'ADD8E6')
            ),
            'borders' => array(
                'allborders' => array(
                    'style' => \PHPExcel_Style_Border::BORDER_THIN
                )
            )
        ));

        $rowCtr = 4;
        $activeSheet->setCellValue('A'.$rowCtr, 'Activity');
        $activeSheet->setCellValue('B'.$rowCtr, 'BOOKED');
        $activeSheet->setCellValue('C'.$rowCtr, 'Total Actual Number');
        $activeSheet->setCellValue('D'.$rowCtr, 'Target');
        $activeSheet->getStyle('A'.$rowCtr.':D'.$rowCtr)->applyFromArray(array(
            'fill' => array(
                'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                'color' => array('rgb' => 'C3CFEF')
            ),
        ));

        $rowCtr++;
        foreach ($records as $record) {
            $activeSheet->setCellValue('A'.$rowCtr, $record['chartType']);
            $activeSheet->setCellValue('B'.$rowCtr, $record['totalBookedCount']);
            $activeSheet->setCellValue('C'.$rowCtr, $record['totalCount']);
            if($record['chartType'] == 'HSAT') {
                $activeSheet->setCellValue('D'.$rowCtr, round(($record['totalBookedCount'] / 240) * 100, 2).'%');
            }
            $rowCtr++;
        }

        $page_title = 'Prod. CBT(Scheduling) Report';
        $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;
    }


    //Fax Summary Report
    /**
     * @Route("/report_productivity_new_referral", name="report_productivity_new_referral")
     */
    public function productivityReferralNewAction() {

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

        $page_title = 'Fax Summary Report';
        return $this->render('@RxConnexion/Report/ProductivityNewReferral/index.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/productivity_new_referral/productivity_new_referral.js')
        ));
    }

    /**
     * @Route(
     *      "/productivity_new_referral/preview/{date_from}/{date_to}",
     *      name = "report_productivity_new_referral_preview"
     * )
     */
    public function productivityReferralNew_previewAction($date_from, $date_to) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Fax Summary Preview'))) return $authService->redirectToHome();

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

        $em = $this->getDoctrine()->getManager();
        $productivityNewReferral = $em->getRepository('RxConnexionBundle:ReferralEntity')->productivityNewReferralReport(array(
            'date_from' => $date_from,
            'date_to' => $date_to
        ));
        $productivityStaffReferral = $em->getRepository('RxConnexionBundle:ReferralEntity')->productivityStaffReferralReport(array(
            'date_from' => $date_from,
            'date_to' => $date_to
        ));
        $page_title = 'Productivity Referral Report';
        return $this->render('@RxConnexion/Report/ProductivityNewReferral/preview.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'javascripts' => array('rxconnexion/admin/js/report/report_preview.js'),
            'branch' => $productivityNewReferral,
            'staff' => $productivityStaffReferral,
        ));
    }

    /**
     * @Route(
     *      "/productivity_new_referral/export_to_pdf/{date_from}/{date_to}",
     *      name = "report_productivity_new_referral_export_to_pdf"
     * )
     */
    public function productivityReferralNew_export_to_pdfAction($date_from, $date_to) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Fax Summary Pdf'))) return $authService->redirectToHome();

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

        $em = $this->getDoctrine()->getManager();
        $productivityNewReferral = $em->getRepository('RxConnexionBundle:ReferralEntity')->productivityNewReferralReport(array(
            'date_from' => $date_from,
            'date_to' => $date_to
        ));
        $productivityStaffReferral = $em->getRepository('RxConnexionBundle:ReferralEntity')->productivityStaffReferralReport(array(
            'date_from' => $date_from,
            'date_to' => $date_to
        ));

        $page_title = 'Productivity Referral Report';
        $content = $this->renderView('@RxConnexion/Report/ProductivityNewReferral/preview.wkpdf.twig', array(
            'page_title' => $page_title,
            'branch' => $productivityNewReferral,
            'staff' => $productivityStaffReferral,
        ));

        $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content, array(
            'orientation'=>'Landscape',
            'dpi' => 72,
            // 'disable-smart-shrinking',
            'zoom' => 'LINUX' == strtoupper(PHP_OS) ? 0.78 : 1
        ));

        $pdfResponse = array(
            'success' => true,
            'msg' => 'PDF was successfully generated.',
            'pdfBase64' => base64_encode($xml)
        );
        if($pdfResponse['success']) {
            $pdfContent = $pdfResponse['pdfBase64'];
            return new Response(base64_decode($pdfContent), 200, array(
                'Content-Type' => 'application/pdf',
                'Content-Disposition'   => 'attachment; filename="Productivity Fax Summary Report' . date('m/d/Y') . ' Details.pdf"'
            ));
        } else {
            $this->get('session')->getFlashBag()->set('error_messages', $pdfResponse['msg']);
            return $this->redirect($this->generateUrl('report_productivity_new_referral', 302));
        }
    }

    /**
     * @Route(
     *      "/productivity_new_referral/export_to_excel/{date_from}/{date_to}",
     *      name = "report_productivity_new_referral_export_to_excel"
     * )
     */
    public function productivityReferralNew_export_to_excelAction($date_from, $date_to) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Fax Summary Excel'))) return $authService->redirectToHome();

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

        $em = $this->getDoctrine()->getManager();
        $cellsData[] = array('cell' => 'A1', 'data' => 'Productivity Report');

        $records = $em->getRepository('RxConnexionBundle:ReferralEntity')->productivityNewReferralReport(array(
            'date_from' => $date_from,
            'date_to' => $date_to
        ));

        $records2 = $em->getRepository('RxConnexionBundle:ReferralEntity')->productivityStaffReferralReport(array(
            'date_from' => $date_from,
            'date_to' => $date_to
        ));

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

        $activeSheet->setCellValue('A1', 'Fax Summary Report : From '.$date_from.' To '.$date_to);

        $activeSheet->getStyle('A1')->applyFromArray(array(
            'fill' => array(
                'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                'color' => array('rgb' => 'ADD8E6')
            ),
            'borders' => array(
                'allborders' => array(
                    'style' => \PHPExcel_Style_Border::BORDER_THIN
                )
            )
        ));

        $activeSheet->setCellValue('A3', 'Branch');
        $activeSheet->setCellValue('B3', 'Received');
        $activeSheet->setCellValue('C3', 'Encoded');
        $activeSheet->setCellValue('D3', 'Duplicate');
        $activeSheet->setCellValue('E3', 'Existing');
        $activeSheet->setCellValue('F3', 'Unable to Process');
        $activeSheet->getStyle('A3:F3')->applyFromArray(array(
            'fill' => array(
                'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                'color' => array('rgb' => 'ADD8E6')
            ),
            'borders' => array(
                'allborders' => array(
                    'style' => \PHPExcel_Style_Border::BORDER_THIN
                )
            )
        ));

        $rowCtr = 3;

        foreach($records as $record) {
            $rowCtr++;
            $activeSheet->setCellValue('A'.$rowCtr, isset($record['description']) ? $record['description'] : '');
            $activeSheet->setCellValue('B'.$rowCtr, isset($record['faxReceived']) ? $record['faxReceived'] : '0');
            $activeSheet->setCellValue('C'.$rowCtr, isset($record['referralCount']) ? $record['referralCount'] : '0');
            $activeSheet->setCellValue('D'.$rowCtr, isset($record['faxIsDuplicatedCount']) ? $record['faxIsDuplicatedCount'] : '0');
            $activeSheet->setCellValue('E'.$rowCtr, isset($record['faxIsExistingCount']) ? $record['faxIsExistingCount'] : '0');
            $activeSheet->setCellValue('F'.$rowCtr, isset($record['faxIsUnableToProcessCount']) ? $record['faxIsUnableToProcessCount'] : '0');
        }

        $rowCtr = 14;
        $rowCtr++;
        $activeSheet->setCellValue('A15', 'Staff');
        $activeSheet->setCellValue('B15', 'Received');
        $activeSheet->setCellValue('C15', 'Encoded');
        $activeSheet->setCellValue('D15', 'Duplicate');
        $activeSheet->setCellValue('E15', 'Existing');
        $activeSheet->setCellValue('F15', 'Unable to Process');
        $activeSheet->getStyle('A15:F15')->applyFromArray(array(
            'fill' => array(
                'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                'color' => array('rgb' => 'ADD8E6')
            ),
            'borders' => array(
                'allborders' => array(
                    'style' => \PHPExcel_Style_Border::BORDER_THIN
                )
            )
        ));

        foreach($records2 as $record2) {
            $rowCtr++;
            $activeSheet->setCellValue('A'.$rowCtr, isset($record2['fullName']) ? $record2['fullName'] : '');
            $activeSheet->setCellValue('B'.$rowCtr, isset($record2['faxCount']) ? $record2['faxCount'] : '0');
            $activeSheet->setCellValue('C'.$rowCtr, isset($record2['referralCount']) ? $record2['referralCount'] : '0');
            $activeSheet->setCellValue('D'.$rowCtr, isset($record2['faxIsDuplicatedCount']) ? $record2['faxIsDuplicatedCount'] : '0');
            $activeSheet->setCellValue('E'.$rowCtr, isset($record2['faxIsExistingCount']) ? $record2['faxIsExistingCount'] : '0');
            $activeSheet->setCellValue('F'.$rowCtr, isset($record2['faxIsUnableToProcessCount']) ? $record2['faxIsUnableToProcessCount'] : '0');
        }

        $page_title = 'Fax Summary Report';

        $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;
    }

    //KEY PERFORMANCE INDICATOR
    /**
     * @Route("/report_kpi", name="report_kpi")
     */
    public function keyPerformanceIndicatorAction() {

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

        $page_title = 'Key Performance Indicator Report';
        return $this->render('@RxConnexion/Report/KeyPerformanceIndicator/index.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/kpi/kpi.js')
        ));
    }

    /**
     * @Route(
     *      "/kpi/preview/{date_from}/{date_to}/{staff_id}",
     *      name = "report_kpi_preview"
     * )
     */
    public function keyPerformanceIndicator_previewAction($date_from, $date_to, $staff_id) {

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

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

        $em = $this->getDoctrine()->getManager();
        $kpi = $em->getRepository('RxConnexionBundle:PatientChartEntity')->keyPerformanceIndicatorReport(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'account_user' => $staff_id
        ));

        $page_title = 'Key Performance Indicator Report';
        return $this->render('@RxConnexion/Report/KeyPerformanceIndicator/preview.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'javascripts' => array('rxconnexion/admin/js/report/report_preview.js'),
            'records' => $kpi
        ));
    }

    /**
     * @Route(
     *      "/kpi/export_to_pdf/{date_from}/{date_to}/{staff_id}",
     *      name = "report_kpi_export_to_pdf"
     * )
     */
    public function keyPerformanceIndicator_export_to_pdfAction($date_from, $date_to, $staff_id) {

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

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

        $em = $this->getDoctrine()->getManager();
        $kpi = $em->getRepository('RxConnexionBundle:PatientChartEntity')->keyPerformanceIndicatorReport(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'account_user' => $staff_id
        ));

        $page_title = 'Productivity Referral Report';
        $content = $this->renderView('@RxConnexion/Report/KeyPerformanceIndicator/preview.wkpdf.twig', array(
            'page_title' => $page_title,
            'records' => $kpi
        ));

        $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content, array(
            'orientation'=>'Landscape',
            'dpi' => 72,
            // 'disable-smart-shrinking',
            'zoom' => 'LINUX' == strtoupper(PHP_OS) ? 0.78 : 1
        ));

        $pdfResponse = array(
            'success' => true,
            'msg' => 'PDF was successfully generated.',
            'pdfBase64' => base64_encode($xml)
        );
        if($pdfResponse['success']) {
            $pdfContent = $pdfResponse['pdfBase64'];
            return new Response(base64_decode($pdfContent), 200, array(
                'Content-Type' => 'application/pdf',
                'Content-Disposition'   => 'attachment; filename="KPI Report' . date('m/d/Y') . ' Details.pdf"'
            ));
        } else {
            $this->get('session')->getFlashBag()->set('error_messages', $pdfResponse['msg']);
            return $this->redirect($this->generateUrl('report_productivity_new_referral', 302));
        }
    }

    /**
     * @Route(
     *      "/kpi/export_to_excel/{date_from}/{date_to}/{staff_id}",
     *      name = "report_kpi_export_to_excel"
     * )
     */
    public function keyPerformanceIndicator_export_to_excelAction($date_from, $date_to, $staff_id) {

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

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

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

        $columnRange = range('A', 'Z');

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

        $records = $em->getRepository('RxConnexionBundle:ReferralEntity')->productivityNewReferralReport();

        $rowCtr = 4;
        foreach ($records as $record) {
            $cellsData[] = array('cell' => 'A3', 'data' => $record['description']);

            //COLUMNS
            $columnIndex = 1;
            foreach($record['providers'] as $clinicians) {
                $cellsData[] = array('cell' => 'A4', 'data' => 'Activity/Services');
                $cellsData[] = array('cell' => $columnRange[$columnIndex++].'4', 'data' => ''.$clinicians['name']);
            }

            //ROWS
            foreach ($record['chartTypes'] as $chartTypes) {
                $cellsData[] = array('cell' => "A$rowCtr", 'data' => $chartTypes['description']);
                foreach ($record['providers'] as $providers) {
                    foreach ($record['chartTypes'] as $chartType) {

                    }
                }
            }
        }

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

    //Marketing Report
    /**
     * @Route("/marketing", name="report_marketing")
     */
    public function marketingAction() {

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

        $session = $this->get('session');
        $userData = $session->get('userData');
        $em = $this->getDoctrine()->getManager();
        $branch = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->branchesForMultiple($userData);
        $company = $em->getRepository('RxConnexionBundle:CompanyEntity')->companiesForMultiple($userData);

        $page_title = 'Marketing Report';
        return $this->render('@RxConnexion/Report/Marketing/index.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'branch' => $branch,
            'company' => $company,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/marketing/marketing.js')
        ));
    }

    /**
     * @Route(
     *      "/marketing/preview/{date_from}/{date_to}/{company_id}/{branch_id}/{receive_date_from}/{receive_date_to}/{patient_id}/{referring_affiliate_id}/{referring_physician_id}/{agent_id}",
     *      name = "report_marketing_preview"
     * )
     */
    public function marketing_previewAction($date_from, $date_to, $company_id, $branch_id, $receive_date_from, $receive_date_to, $patient_id, $referring_affiliate_id, $referring_physician_id, $agent_id) {

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

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:SalesAgentEntity')->reportMarketing(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company_id,
            'branch' => $branch_id,
            'receive_date_from' => $receive_date_from,
            'receive_date_to' => $receive_date_to,
            'patient' => $patient_id,
            'referring_affiliate' => $referring_affiliate_id,
            'referring_physician' => $referring_physician_id,
            'agent' => $agent_id,
            'userData' => $userData
        ));

        $page_title = 'Marketing Report';
        return $this->render('@RxConnexion/Report/Marketing/preview.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'javascripts' => array('rxconnexion/admin/js/report/report_preview.js'),
            'records' => $records
        ));
    }

    /**
     * @Route(
     *      "/marketing/export_to_pdf/{date_from}/{date_to}/{company_id}/{branch_id}/{receive_date_from}/{receive_date_to}/{patient_id}/{referring_affiliate_id}/{referring_physician_id}/{agent_id}",
     *      name = "report_marketing_export_to_pdf"
     * )
     */
        public function marketing_export_to_pdfAction($date_from, $date_to, $company_id, $branch_id, $receive_date_from, $receive_date_to, $patient_id, $referring_affiliate_id, $referring_physician_id, $agent_id) {

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

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:SalesAgentEntity')->reportMarketing(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company_id,
            'branch' => $branch_id,
            'receive_date_from' => $receive_date_from,
            'receive_date_to' => $receive_date_to,
            'patient' => $patient_id,
            'referring_affiliate' => $referring_affiliate_id,
            'referring_physician' => $referring_physician_id,
            'agent' => $agent_id,
            'userData' => $userData
        ));

        $page_title = 'Marketing Report';
        $content = $this->renderView('@RxConnexion/Report/Marketing/preview.wkpdf.twig', array(
            'page_title' => $page_title,
            'records' => $records
        ));

        $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content, array(
            'orientation'=>'Landscape',
            'dpi' => 72,
            // 'disable-smart-shrinking',
            'zoom' => 'LINUX' == strtoupper(PHP_OS) ? 0.78 : 1
        ));

        $pdfResponse = array(
            'success' => true,
            'msg' => 'PDF was successfully generated.',
            'pdfBase64' => base64_encode($xml)
        );
        if($pdfResponse['success']) {
            $pdfContent = $pdfResponse['pdfBase64'];
            return new Response(base64_decode($pdfContent), 200, array(
                'Content-Type' => 'application/pdf',
                'Content-Disposition'   => 'attachment; filename="Marketing Report' . date('m/d/Y') . ' Details.pdf"'
            ));
        } else {
            $this->get('session')->getFlashBag()->set('error_messages', $pdfResponse['msg']);
            return $this->redirect($this->generateUrl('report_referral', 302));
        }
    }

    /**
     * @Route(
     *      "/marketing/export_to_excel/{date_from}/{date_to}/{company_id}/{branch_id}/{receive_date_from}/{receive_date_to}/{patient_id}/{referring_affiliate_id}/{referring_physician_id}/{agent_id}",
     *      name = "report_marketing_export_to_excel"
     * )
     */
    public function marketing_export_to_excelAction($date_from, $date_to, $company_id, $branch_id, $receive_date_from, $receive_date_to, $patient_id, $referring_affiliate_id, $referring_physician_id, $agent_id) {

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

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

        $phpExcelObject = $this->get('phpexcel')->createPHPExcelObject();
        $activeSheet = $phpExcelObject->setActiveSheetIndex(0);
        $activeSheet->setCellValue('A1', 'Marketing Report');

        $activeSheet->getStyle('A1')->applyFromArray(array(
            'fill' => array(
                'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                'color' => array('rgb' => 'ADD8E6')
            ),
            'borders' => array(
                'allborders' => array(
                    'style' => \PHPExcel_Style_Border::BORDER_THIN
                )
            )
        ));
        $activeSheet->getStyle('A1')->getFont()->setBold( true );

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:SalesAgentEntity')->reportMarketing(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company_id,
            'branch' => $branch_id,
            'receive_date_from' => $receive_date_from,
            'receive_date_to' => $receive_date_to,
            'patient' => $patient_id,
            'referring_affiliate' => $referring_affiliate_id,
            'referring_physician' => $referring_physician_id,
            'agent' => $agent_id,
            'userData' => $userData
        ));

        $activeSheet->setCellValue('A2', 'Referral Date');
        $activeSheet->setCellValue('B2', 'Receive Date');
        $activeSheet->setCellValue('C2', 'Patient');
        $activeSheet->setCellValue('D2', 'Patient Services');
        $activeSheet->setCellValue('E2', 'Company');
        $activeSheet->setCellValue('F2', 'Branch');
        $activeSheet->setCellValue('G2', 'Referring Physician');
        $activeSheet->setCellValue('H2', 'Referring Affiliate');
        $activeSheet->setCellValue('I2', 'Latest Encounter');
        $activeSheet->setCellValue('J2', 'Latest Encounter Status');
        $activeSheet->setCellValue('K2', 'Letter Type');
        $activeSheet->setCellValue('L2', 'Letter Status');
        $activeSheet->setCellValue('M2', 'Agent');
        $activeSheet->setCellValue('N2', 'Invoice No.');
        $activeSheet->setCellValue('O2', 'Billing Date');
        $activeSheet->setCellValue('P2', 'Rate');
        $activeSheet->getStyle('A2:P2')->applyFromArray(array(
            'fill' => array(
                'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                'color' => array('rgb' => 'C3CFEF')
            ),
        ));
        $activeSheet->getStyle('A3:P3')->getFont()->setBold( true );

        $rowCtr = 3;
        $totalCount = 0;

        foreach($records['marketing'] as $record) {
            $explodedPs = explode(',', $record['patientServices']);
            $rowCtr++;
            $totalCount++;
            $activeSheet->setCellValue('A'.$rowCtr, $record['referral_date']);
            $activeSheet->setCellValue('B'.$rowCtr, $record['receive_date']);
            $activeSheet->setCellValue('C'.$rowCtr, $record['patient']);
            foreach ($explodedPs as $ps) {
                $patientService = explode('|', $ps);
                $activeSheet->setCellValue('D'.$rowCtr, isset($patientService[1]) ? $patientService[1] : '');
                $rowCtr++;
            }
            $activeSheet->setCellValue('E'.$rowCtr, $record['companyDesc']);
            $activeSheet->setCellValue('F'.$rowCtr, $record['branch']);
            $activeSheet->setCellValue('G'.$rowCtr, $record['referring_physician']);
            $activeSheet->setCellValue('H'.$rowCtr, $record['referring_affiliate']);
            $activeSheet->setCellValue('I'.$rowCtr, $record['chartTypeDesc']);
            $activeSheet->setCellValue('J'.$rowCtr, $record['chartStatusDesc']);
            $activeSheet->setCellValue('K'.$rowCtr, $record['letterType']);
            $activeSheet->setCellValue('L'.$rowCtr, $record['letterStatus']);
            $activeSheet->setCellValue('M'.$rowCtr, $record['sales_agent']);
            $activeSheet->setCellValue('N'.$rowCtr, $record['invoice_no']);
            $activeSheet->setCellValue('O'.$rowCtr, $record['billingDate']);
            $activeSheet->setCellValue('P'.$rowCtr, $record['rate']);
        }

        $rowCtr++;
        $activeSheet->setCellValue('A'.$rowCtr, 'Total Records: ' . $totalCount);

        $rowCtr++;
        $rowCtr++;
        $activeSheet->setCellValue('A'.$rowCtr, 'Summary');
        $activeSheet->getStyle('A'.$rowCtr)->applyFromArray(array(
            'fill' => array(
                'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                'color' => array('rgb' => 'ADD8E6')
            ),
            'borders' => array(
                'allborders' => array(
                    'style' => \PHPExcel_Style_Border::BORDER_THIN
                )
            )
        ));
        $activeSheet->getStyle('A'.$rowCtr)->getFont()->setBold( true );

        $rowCtr++;
        $activeSheet->setCellValue('A'.$rowCtr, 'Agent');
        $activeSheet->setCellValue('B'.$rowCtr, 'Total');
        $activeSheet->getStyle('A'.$rowCtr.':B'.$rowCtr)->applyFromArray(array(
            'fill' => array(
                'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                'color' => array('rgb' => 'C3CFEF')
            ),
        ));
        $activeSheet->getStyle('A'.$rowCtr.':B'.$rowCtr)->getFont()->setBold( true );

        foreach($records['soldCount'] as $record) {

            $rowCtr++;
            $totalCount++;
            $activeSheet->setCellValue('A'.$rowCtr, $record['sales_agent']);
            $activeSheet->setCellValue('B'.$rowCtr, $record['rate']);
        }

        $page_title = 'Marketing Report';
        $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;
    }

    //Booked per Encounter Report
    /**
     * @Route("/booked_per_encounter", name="report_booked_per_encounter")
     */
    public function bookedPerEncounterReportAction() {

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

        $page_title = 'Booked per Encounter Report';
        return $this->render('@RxConnexion/Report/BookedPerEncounterReport/index.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/bookedperencounter/bookedPerEncounter.js')
        ));
    }

    /**
     * @Route(
     *      "/booked_per_encounter/preview/{date_from}/{date_to}/{accountUser}/{encounterType}",
     *      name = "report_booked_per_encounter_preview"
     * )
     */
    public function bookedPerEncounter_previewAction($date_from, $date_to, $accountUser, $encounterType) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Booked Encounter Preview'))) return $authService->redirectToHome();

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientChartEntity')->reportBookedperEncounterReport(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'accountUser' => $accountUser,
            'encounterType' => $encounterType,
        ));

        $page_title = 'Booked per Encounter Report';
        return $this->render('@RxConnexion/Report/BookedPerEncounterReport/preview.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'javascripts' => array('rxconnexion/admin/js/report/report_preview.js'),
            'records' => $records
        ));
    }

    /**
     * @Route(
     *      "/booked_per_encounter/export_to_pdf/{date_from}/{date_to}/{accountUser}/{encounterType}",
     *      name = "report_booked_per_encounter_export_to_pdf"
     * )
     */
    public function bookedPerEncounter_export_to_pdfAction($date_from, $date_to, $accountUser, $encounterType) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Booked Encounter Pdf'))) return $authService->redirectToHome();

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientChartEntity')->reportBookedperEncounterReport(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'accountUser' => $accountUser,
            'encounterType' => $encounterType,
        ));

        $page_title = 'Booked per Encounter Report';
        $content = $this->renderView('@RxConnexion/Report/BookedPerEncounterReport/preview.wkpdf.twig', array(
            'page_title' => $page_title,
            'records' => $records
        ));

        $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content, array(
            'orientation'=>'Landscape',
            'dpi' => 72,
            // 'disable-smart-shrinking',
            'zoom' => 'LINUX' == strtoupper(PHP_OS) ? 0.78 : 1
        ));

        $pdfResponse = array(
            'success' => true,
            'msg' => 'PDF was successfully generated.',
            'pdfBase64' => base64_encode($xml)
        );
        if($pdfResponse['success']) {
            $pdfContent = $pdfResponse['pdfBase64'];
            return new Response(base64_decode($pdfContent), 200, array(
                'Content-Type' => 'application/pdf',
                'Content-Disposition'   => 'attachment; filename="Booked per Encounter Report' . date('m/d/Y') . ' Details.pdf"'
            ));
        } else {
            $this->get('session')->getFlashBag()->set('error_messages', $pdfResponse['msg']);
            return $this->redirect($this->generateUrl('report_referral', 302));
        }
    }

    /**
     * @Route(
     *      "/booked_per_encounter/export_to_excel/{date_from}/{date_to}/{accountUser}/{encounterType}",
     *      name = "report_booked_per_encounter_export_to_excel"
     * )
     */
    public function bookedPerEncounter_export_to_excelAction($date_from, $date_to, $accountUser, $encounterType) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Booked Encounter Excel'))) return $authService->redirectToHome();

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientChartEntity')->reportBookedperEncounterReport(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'accountUser' => $accountUser,
            'encounterType' => $encounterType,
        ));

        $columnRange = range('A', 'Z');
        $cellsData = array(
            array('cell' => 'A1', 'data' => 'User'),
            array('cell' => 'B1', 'data' => 'Encounter Type'),
            array('cell' => 'C1', 'data' => 'Count'),
        );
        $rowCtr = 1;
        $totalCount = 0;

        foreach($records as $record) {

            $rowCtr++;
            $totalCount++;

            $cellsData[] = array('cell' => "A$rowCtr", 'data' => $record['accountUser']);
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => $record['encounterType']);
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => $record['encounterStatusCount']);
        }

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


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

    //Count of Endorsed per Encounter and User Report
    /**
     * @Route("/endorsed_per_encounter_and_user", name="report_endorsed_per_encounter_and_user")
     */
    public function endorsedPerEncounterAndUserReportAction() {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Endorsed per Encounter and User'))) return $authService->redirectToHome();

        $page_title = 'User Endorsed Report';
        return $this->render('@RxConnexion/Report/EndorsedPerEncounterAndUserReport/index.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/endorsedPatientEncounterPerUser/endorsedPatientEncounterPerUser.js')
        ));
    }

    /**
     * @Route(
     *      "/endorsed_per_encounter_and_user/preview/{date_from}/{date_to}/{accountUser}",
     *      name = "report_endorsed_per_encounter_and_user_preview"
     * )
     */
    public function endorsedPerEncounterAndUser_previewAction($date_from, $date_to, $accountUser) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report User Endorsed Preview'))) return $authService->redirectToHome();

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:TicketEntity')->reportEndorsedPatientEncounterPerUser(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'accountUser' => $accountUser
        ));

        $page_title = 'User Endorsed Report';
        return $this->render('@RxConnexion/Report/EndorsedPerEncounterAndUserReport/preview.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'javascripts' => array('rxconnexion/admin/js/report/report_preview.js'),
            'records' => $records
        ));
    }

    /**
     * @Route(
     *      "/endorsed_per_encounter_and_user/export_to_pdf/{date_from}/{date_to}/{accountUser}",
     *      name = "report_endorsed_per_encounter_and_user_export_to_pdf"
     * )
     */
    public function endorsedPerEncounterAndUser_export_to_pdfAction($date_from, $date_to, $accountUser) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report User Endorsed Pdf'))) return $authService->redirectToHome();

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:TicketEntity')->reportEndorsedPatientEncounterPerUser(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'accountUser' => $accountUser
        ));

        $page_title = 'User Endorsed Report';
        $content = $this->renderView('@RxConnexion/Report/EndorsedPerEncounterAndUserReport/preview.wkpdf.twig', array(
            'page_title' => $page_title,
            'records' => $records
        ));

        $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content, array(
            'orientation'=>'Landscape',
            'dpi' => 72,
            // 'disable-smart-shrinking',
            'zoom' => 'LINUX' == strtoupper(PHP_OS) ? 0.78 : 1
        ));

        $pdfResponse = array(
            'success' => true,
            'msg' => 'PDF was successfully generated.',
            'pdfBase64' => base64_encode($xml)
        );
        if($pdfResponse['success']) {
            $pdfContent = $pdfResponse['pdfBase64'];
            return new Response(base64_decode($pdfContent), 200, array(
                'Content-Type' => 'application/pdf',
                'Content-Disposition'   => 'attachment; filename="Endorsed per Encounter and User Report' . date('m/d/Y') . ' Details.pdf"'
            ));
        } else {
            $this->get('session')->getFlashBag()->set('error_messages', $pdfResponse['msg']);
            return $this->redirect($this->generateUrl('report_referral', 302));
        }
    }

    /**
     * @Route(
     *      "/endorsed_per_encounter_and_user/export_to_excel/{date_from}/{date_to}/{accountUser}",
     *      name = "report_endorsed_per_encounter_and_user_export_to_excel"
     * )
     */
    public function endorsedPerEncounterAndUser_export_to_excelAction($date_from, $date_to, $accountUser) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report User Endorsed Excel'))) return $authService->redirectToHome();

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:TicketEntity')->reportEndorsedPatientEncounterPerUser(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'accountUser' => $accountUser
        ));

        $columnRange = range('A', 'Z');
        $cellsData = array(
            array('cell' => 'A1', 'data' => 'Endorsed To'),
            array('cell' => 'B1', 'data' => 'Patients Count'),
        );
        $rowCtr = 1;
        $totalCount = 0;

        foreach($records as $record) {

            $rowCtr++;
            $totalCount++;

            $cellsData[] = array('cell' => "A$rowCtr", 'data' => $record['accountUser']);
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => $record['countOfEndorsedPatients']);
        }

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


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


    //Status under Rebooking Report
    /**
     * @Route("/status_rebooking", name="report_status_rebooking")
     */
    public function statusUnderRebookingReportAction() {

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

        $page_title = 'Status Rebooking Report';
        return $this->render('@RxConnexion/Report/StatusRebooking/index.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/statusUnderRebooking/statusUnderRebooking.js')
        ));
    }

    /**
     * @Route(
     *      "/status_rebooking/preview/{date_from}/{date_to}/{accountUser}",
     *      name = "report_status_rebooking_preview"
     * )
     */
    public function statusUnderRebooking_previewAction($date_from, $date_to, $accountUser) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Status Rebooking Preview'))) return $authService->redirectToHome();

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientChartEntity')->reportStatusUnderRebookingReport(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'accountUser' => $accountUser
        ));

        $accountUsers = $em->getRepository('RxConnexionBundle:AccountUserEntity')->findAll();

        $page_title = 'Status Rebooking Report';
        return $this->render('@RxConnexion/Report/StatusRebooking/preview.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'javascripts' => array('rxconnexion/admin/js/report/report_preview.js'),
            'records' => $records,
            'accountUsers' => $accountUsers
        ));
    }

    /**
     * @Route(
     *      "/status_rebooking/export_to_pdf/{date_from}/{date_to}/{accountUser}",
     *      name = "report_status_rebooking_export_to_pdf"
     * )
     */
    public function statusUnderRebooking_export_to_pdfAction($date_from, $date_to, $accountUser) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Status Rebooking Pdf'))) return $authService->redirectToHome();

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientChartEntity')->reportStatusUnderRebookingReport(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'accountUser' => $accountUser
        ));

        $page_title = 'Status Rebooking Report';
        $content = $this->renderView('@RxConnexion/Report/StatusRebooking/preview.wkpdf.twig', array(
            'page_title' => $page_title,
            'records' => $records
        ));

        $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content, array(
            'orientation'=>'Landscape',
            'dpi' => 72,
            // 'disable-smart-shrinking',
            'zoom' => 'LINUX' == strtoupper(PHP_OS) ? 0.78 : 1
        ));

        $pdfResponse = array(
            'success' => true,
            'msg' => 'PDF was successfully generated.',
            'pdfBase64' => base64_encode($xml)
        );
        if($pdfResponse['success']) {
            $pdfContent = $pdfResponse['pdfBase64'];
            return new Response(base64_decode($pdfContent), 200, array(
                'Content-Type' => 'application/pdf',
                'Content-Disposition'   => 'attachment; filename="Status Rebooking Report' . date('m/d/Y') . ' Details.pdf"'
            ));
        } else {
            $this->get('session')->getFlashBag()->set('error_messages', $pdfResponse['msg']);
            return $this->redirect($this->generateUrl('report_referral', 302));
        }
    }

    /**
     * @Route(
     *      "/status_rebooking/export_to_excel/{date_from}/{date_to}/{accountUser}",
     *      name = "report_status_rebooking_export_to_excel"
     * )
     */
    public function statusUnderRebooking_export_to_excelAction($date_from, $date_to, $accountUser) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Status Rebooking Excel'))) return $authService->redirectToHome();

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientChartEntity')->reportStatusUnderRebookingReport(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'accountUser' => $accountUser,
        ));

        $columnRange = range('A', 'Z');
        $cellsData = array(
            array('cell' => 'A1', 'data' => 'User'),
            array('cell' => 'B1', 'data' => 'Status'),
            array('cell' => 'C1', 'data' => 'Count'),
        );
        $rowCtr = 1;
        $totalCount = 0;

        foreach($records as $record) {

            $rowCtr++;
            $totalCount++;

            $cellsData[] = array('cell' => "A$rowCtr", 'data' => $record['accountUser']);
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => $record['chartStatus']);
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => $record['statusCount']);
        }

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


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

    //Count Patients Referring Health Facility - Providers
    /**
     * @Route("/count_patient_referring_provider", name="report_count_patient_referring_provider")
     */
    public function countPatientReferringProviderReportAction() {

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

        $page_title = 'Patient Referring Affiliate Report';
        return $this->render('@RxConnexion/Report/PatientReferringHealthFacilityCount/index.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/patient_referring_health_facility_count/patient_referring_health_facility_count.js')
        ));
    }

    /**
     * @Route(
     *      "/count_patient_referring_provider/preview/{referring_health_facility_id}",
     *      name = "report_count_patient_referring_provider_preview"
     * )
     */
    public function countPatientReferringProvider_previewAction($referring_health_facility_id) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Patient Referring Provider Preview'))) return $authService->redirectToHome();

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:ReferringHealthFacilityProviderEntity')->patientCountProviderReport(array(
            'referring_health_facility' => $referring_health_facility_id,
        ));

        $page_title = 'Patient Referring Affiliate Report';
        return $this->render('@RxConnexion/Report/PatientReferringHealthFacilityCount/preview.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'javascripts' => array('rxconnexion/admin/js/report/report_preview.js'),
            'records' => $records,
        ));
    }

    /**
     * @Route(
     *      "/count_patient_referring_provider/export_to_pdf/{referring_health_facility_id}",
     *      name = "report_count_patient_referring_provider_export_to_pdf"
     * )
     */
    public function countPatientReferringProvider_export_to_pdfAction($referring_health_facility_id) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Patient Referring Provider Pdf'))) return $authService->redirectToHome();

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:ReferringHealthFacilityProviderEntity')->patientCountProviderReport(array(
            'referring_health_facility' => $referring_health_facility_id,
        ));

        $page_title = 'Patient Referring Affiliate Report';
        $content = $this->renderView('@RxConnexion/Report/PatientReferringHealthFacilityCount/preview.wkpdf.twig', array(
            'page_title' => $page_title,
            'records' => $records
        ));

        $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content, array(
            'orientation'=>'Landscape',
            'dpi' => 72,
            // 'disable-smart-shrinking',
            'zoom' => 'LINUX' == strtoupper(PHP_OS) ? 0.78 : 1
        ));

        $pdfResponse = array(
            'success' => true,
            'msg' => 'PDF was successfully generated.',
            'pdfBase64' => base64_encode($xml)
        );
        if($pdfResponse['success']) {
            $pdfContent = $pdfResponse['pdfBase64'];
            return new Response(base64_decode($pdfContent), 200, array(
                'Content-Type' => 'application/pdf',
                'Content-Disposition'   => 'attachment; filename="Patient Referring Affiliate Report' . date('m/d/Y') . ' Details.pdf"'
            ));
        } else {
            $this->get('session')->getFlashBag()->set('error_messages', $pdfResponse['msg']);
            return $this->redirect($this->generateUrl('report_referral', 302));
        }
    }

    /**
     * @Route(
     *      "/count_patient_referring_provider/export_to_excel/{referring_health_facility_id}",
     *      name = "report_count_patient_referring_provider_export_to_excel"
     * )
     */
    public function countPatientReferringProvider_export_to_excelAction($referring_health_facility_id) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Patient Referring Provider Excel'))) return $authService->redirectToHome();

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:ReferringHealthFacilityProviderEntity')->patientCountProviderReport(array(
            'referring_health_facility' => $referring_health_facility_id,
        ));

        $columnRange = range('A', 'Z');

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

        $activeSheet->setCellValue('A1', 'Referring Affiliate');
        $activeSheet->setCellValue('B1', 'Patients');

        $activeSheet->getStyle('A1:B1')->applyFromArray(array(
            'fill' => array(
                'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                'color' => array('rgb' => 'ADD8E6')
            ),
            'borders' => array(
                'allborders' => array(
                    'style' => \PHPExcel_Style_Border::BORDER_THIN
                )
            )
        ));

        $rowCtr = 1;
        $totalCount = 0;
        foreach($records as $key => $record) {

            $rowCtr++;
            $totalCount++;

            $activeSheet->setCellValue("A$rowCtr", $record['description'])->getStyle( "A$rowCtr" )->getFont()->setBold( true );
            foreach($record['referringProviders'] as $referringProviders) {
                $rowCtr++;
                $activeSheet->setCellValue("A$rowCtr", $referringProviders['name']);
                foreach ($record['total'] as $total) {
                    if($referringProviders['id'] == $total['id']) {
                        $activeSheet->setCellValue("B$rowCtr", !empty($record['total']) ? $total['count'] : 0);
                    }
                }

            }
            $rowCtr++;
        }

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


        $page_title = 'Patient Counts Report';

        $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;
    }

    //Invoice Report
    /**
     * @Route("/invoice", name="report_invoice")
     */
    public function invoiceReportAction() {

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

        $session = $this->get('session');
        $userData = $session->get('userData');
        $em = $this->getDoctrine()->getManager();
        $company = $em->getRepository('RxConnexionBundle:CompanyEntity')->companiesForMultiple($userData);
        $branch = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->branchesForBillingMultiple($userData);

        $page_title = 'Invoice Report';
        return $this->render('@RxConnexion/Report/Invoice/index.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'company' => $company,
            'branch' => $branch,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/invoice/invoice.js?v=1.0.3')
        ));
    }

    /**
     * @Route(
     *      "/invoice/preview/{date_from}/{date_to}/{company}/{branch}/{branchAddress}/{patient}/{status}/{type}/{term}",
     *      name = "report_invoice_preview"
     * )
     */
    public function invoice_previewAction($date_from, $date_to, $company, $branch, $branchAddress, $patient, $status, $type, $term) {

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

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientBillingEntity')->reportInvoice(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company,
            'branch' => $branch,
            'branchAddress' => $branchAddress,
            'patient' => $patient,
            'status' => $status,
            'type' => $type,
            'term' => $term,
            'userData' => $userData
        ));
        $records2 = $em->getRepository('RxConnexionBundle:PatientBillingEntity')->reportInvoiceSummary(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company,
            'branch' => $branch,
            'branchAddress' => $branchAddress,
            'patient' => $patient,
            'status' => $status,
            'type' => $type,
            'term' => $term,
            'userData' => $userData,
        ));
        $records3 = $em->getRepository('RxConnexionBundle:PatientBillingEntity')->reportInvoiceSummary(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company,
            'branch' => $branch,
            'branchAddress' => $branchAddress,
            'patient' => $patient,
            'status' => $status,
            'type' => $type,
            'term' => $term,
            'userData' => $userData,
        ));

        $page_title = 'Invoice Report';
        return $this->render('@RxConnexion/Report/Invoice/preview.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'javascripts' => array('rxconnexion/admin/js/report/report_preview.js'),
            'records' => $records,
            'records2' => $records2,
            'records3' => $records3,
            'dateFrom' => $date_from,
            'dateTo' => $date_to,
        ));
    }

    /**
     * @Route(
     *      "/invoice/export_to_pdf/{date_from}/{date_to}/{company}/{branch}/{branchAddress}/{patient}/{status}/{type}/{term}",
     *      name = "report_invoice_export_to_pdf"
     * )
     */
    public function invoice_export_to_pdfAction($date_from, $date_to, $company, $branch, $branchAddress, $patient, $status, $type, $term) {

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

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientBillingEntity')->reportInvoice(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company,
            'branch' => $branch,
            'branchAddress' => $branchAddress,
            'patient' => $patient,
            'status' => $status,
            'type' => $type,
            'term' => $term,
            'userData' => $userData
        ));
        $records2 = $em->getRepository('RxConnexionBundle:PatientBillingEntity')->reportInvoiceSummary(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company,
            'branch' => $branch,
            'branchAddress' => $branchAddress,
            'patient' => $patient,
            'status' => $status,
            'type' => $type,
            'term' => $term,
            'userData' => $userData,
        ));
        $records3 = $em->getRepository('RxConnexionBundle:PatientBillingEntity')->reportInvoiceSummary(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company,
            'branch' => $branch,
            'branchAddress' => $branchAddress,
            'patient' => $patient,
            'status' => $status,
            'type' => $type,
            'term' => $term,
            'userData' => $userData,
        ));


        $page_title = 'Invoice Report';
        $content = $this->renderView('@RxConnexion/Report/Invoice/preview.wkpdf.twig', array(
            'page_title' => $page_title,
            'records' => $records,
            'records2' => $records2,
            'records3' => $records3,
            'dateFrom' => $date_from,
            'dateTo' => $date_to,
        ));

        $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content, array(
            'orientation'=>'Landscape',
            'dpi' => 72,
            // 'disable-smart-shrinking',
            'zoom' => 'LINUX' == strtoupper(PHP_OS) ? 0.78 : 1
        ));

        $pdfResponse = array(
            'success' => true,
            'msg' => 'PDF was successfully generated.',
            'pdfBase64' => base64_encode($xml)
        );
        if($pdfResponse['success']) {
            $pdfContent = $pdfResponse['pdfBase64'];
            return new Response(base64_decode($pdfContent), 200, array(
                'Content-Type' => 'application/pdf',
                'Content-Disposition'   => 'attachment; filename="Invoice Report' . date('m/d/Y') . ' Details.pdf"'
            ));
        } else {
            $this->get('session')->getFlashBag()->set('error_messages', $pdfResponse['msg']);
            return $this->redirect($this->generateUrl('report_referral', 302));
        }
    }

    /**
     * @Route(
     *      "/invoice/export_to_excel/{date_from}/{date_to}/{company}/{branch}/{branchAddress}/{patient}/{status}/{type}/{term}",
     *      name = "report_invoice_export_to_excel"
     * )
     */
    public function invoice_export_to_excelAction($date_from, $date_to, $company, $branch, $branchAddress, $patient, $status, $type, $term) {

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

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientBillingEntity')->reportInvoice(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company,
            'branch' => $branch,
            'branchAddress' => $branchAddress,
            'patient' => $patient,
            'status' => $status,
            'type' => $type,
            'term' => $term,
            'userData' => $userData
        ));
        $records2 = $em->getRepository('RxConnexionBundle:PatientBillingEntity')->reportInvoiceSummary(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company,
            'branch' => $branch,
            'branchAddress' => $branchAddress,
            'patient' => $patient,
            'status' => $status,
            'type' => $type,
            'term' => $term,
            'userData' => $userData,
        ));
        $records3 = $em->getRepository('RxConnexionBundle:PatientBillingEntity')->reportInvoiceSummary(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company,
            'branch' => $branch,
            'branchAddress' => $branchAddress,
            'patient' => $patient,
            'status' => $status,
            'type' => $type,
            'term' => $term,
            'userData' => $userData,
        ));

        $columnRange = range('A', 'Z');
        $cellsData = array(
            array('cell' => 'A1', 'data' => 'Invoice No.'),
            array('cell' => 'B1', 'data' => 'Date'),
            array('cell' => 'C1', 'data' => 'Patient'),
            array('cell' => 'D1', 'data' => 'Company'),
            array('cell' => 'E1', 'data' => 'Branch'),
            array('cell' => 'F1', 'data' => 'Branch Address'),
            array('cell' => 'G1', 'data' => 'Amount'),
            array('cell' => 'H1', 'data' => 'Amount Paid'),
            array('cell' => 'I1', 'data' => 'Amount Refunded'),
            array('cell' => 'J1', 'data' => 'Balance'),
            array('cell' => 'K1', 'data' => 'Status'),
            array('cell' => 'L1', 'data' => 'Note'),
        );
        $rowCtr = 1;
        $totalCount = 0;
        $totalBalance = 0;

        foreach($records as $record) {

            $rowCtr++;
            $totalCount++;
            $totalBalance += $record['amtDue'];

            $cellsData[] = array('cell' => "A$rowCtr", 'data' => $record['invoiceNo']);
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => $record['billingDate']);
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => $record['patient']);
            $cellsData[] = array('cell' => "D$rowCtr", 'data' => $record['companyDesc']);
            $cellsData[] = array('cell' => "E$rowCtr", 'data' => $record['healthFacility']);
            $cellsData[] = array('cell' => "F$rowCtr", 'data' => $record['healthFacilityAddress']);
            $cellsData[] = array('cell' => "G$rowCtr", 'data' => number_format($record['amtDue'],2,'.',','));
            $cellsData[] = array('cell' => "H$rowCtr", 'data' => number_format($record['amtPaid'],2,'.',','));
            $cellsData[] = array('cell' => "I$rowCtr", 'data' => number_format($record['amtRefunded'],2,'.',','));
            $cellsData[] = array('cell' => "J$rowCtr", 'data' => number_format($record['amtBalance'],2,'.',','));
            $cellsData[] = array('cell' => "K$rowCtr", 'data' => $record['billingStatus']);
            $cellsData[] = array('cell' => "L$rowCtr", 'data' => $record['note']);
        }

        //SUMMARY
        $rowCtr++;
        $rowCtr++;
        $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Summary: ');
        $rowCtr++;
        $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Branch');
        $cellsData[] = array('cell' => "B$rowCtr", 'data' => 'Count ');
        $cellsData[] = array('cell' => "C$rowCtr", 'data' => 'Invoice');

        $invoiceSummaryTotal = 0;
        $invoiceSummaryAmtDue = 0;
        foreach($records2['invoiceSummary'] as $record2) {
            $invoiceSummaryTotal = $invoiceSummaryTotal + $record2['totalCount'];
            $invoiceSummaryAmtDue = $invoiceSummaryAmtDue + $record2['totalAmtDue'];
            $rowCtr++;
            $cellsData[] = array('cell' => "A$rowCtr", 'data' => $record2['healthFacility']);
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => number_format($record2['totalCount'],2,'.',','));
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => number_format($record2['totalAmtDue'],2,'.',','));
        }

        $rowCtr++;
        $cellsData[] = array('cell' => "B$rowCtr", 'data' => 'Total: ' . $invoiceSummaryTotal);
        $cellsData[] = array('cell' => "C$rowCtr", 'data' => number_format($invoiceSummaryAmtDue,2,'.',','));

        //FINANCING COMPANY SUMMARY
        $rowCtr++;
        $rowCtr++;
        $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Financing Company Summary: ');
        $rowCtr++;
        $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Branch');
        $cellsData[] = array('cell' => "B$rowCtr", 'data' => 'Count ');
        $cellsData[] = array('cell' => "C$rowCtr", 'data' => 'Invoice');

        $invoiceSummaryFinancingTotal = 0;
        $invoiceSummaryFinancingAmtDue = 0;
        foreach($records2['financing'] as $record3) {
            $invoiceSummaryFinancingTotal = $invoiceSummaryFinancingTotal + $record3['totalCount'];
            $invoiceSummaryFinancingAmtDue = $invoiceSummaryFinancingAmtDue + $record3['totalAmtDue'];
            $rowCtr++;
            $cellsData[] = array('cell' => "A$rowCtr", 'data' => $record3['healthFacility']);
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => number_format($record3['totalCount'],2,'.',','));
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => number_format($record3['totalAmtDue'],2,'.',','));
        }

        $rowCtr++;
        $cellsData[] = array('cell' => "B$rowCtr", 'data' => 'Total: ' . $invoiceSummaryFinancingTotal);
        $cellsData[] = array('cell' => "C$rowCtr", 'data' => number_format($invoiceSummaryFinancingAmtDue,2,'.',','));

        //Long Term
        $longTermCount = 0;
        $longTermTotalPrice = 0;

        $rowCtr++;
        $rowCtr++;
        $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Long Term Summary');
        $rowCtr++;
        $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Branch');
        $cellsData[] = array('cell' => "B$rowCtr", 'data' => 'Count ');
        $cellsData[] = array('cell' => "C$rowCtr", 'data' => 'Total Amount');
        foreach($records3['longTerm'] as $longTerm) {
            $longTermCount = $longTermCount + $longTerm['longTermCount'];
            $longTermTotalPrice = $longTermTotalPrice + $longTerm['price'];
            $rowCtr++;
            $cellsData[] = array('cell' => "A$rowCtr", 'data' => $longTerm['billingBranch']);
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => number_format($longTerm['longTermCount'],2,'.',','));
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => number_format($longTerm['price'],2,'.',','));
        }
        $rowCtr++;
        $cellsData[] = array('cell' => "B$rowCtr", 'data' => 'Total: ' . $longTermCount);
        $cellsData[] = array('cell' => "C$rowCtr", 'data' => 'Total: ' . number_format($longTermTotalPrice,2,'.',','));


        $rentToOwnCount = 0;
        $rentToOwnTotalPrice = 0;

        $rowCtr++;
        $rowCtr++;
        $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Rent to Own Summary');
        $rowCtr++;
        $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Branch');
        $cellsData[] = array('cell' => "B$rowCtr", 'data' => 'Count ');
        $cellsData[] = array('cell' => "C$rowCtr", 'data' => 'Total Amount');
        foreach($records3['rentToOwn'] as $rentToOwn) {
            $rentToOwnCount = $rentToOwnCount + $rentToOwn['rentToCount'];
            $rentToOwnTotalPrice = $rentToOwnTotalPrice + $rentToOwn['price'];
            $rowCtr++;
            $cellsData[] = array('cell' => "A$rowCtr", 'data' => $rentToOwn['billingBranch']);
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => number_format($rentToOwn['rentToCount'],2,'.',','));
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => number_format($rentToOwn['price'],2,'.',','));
        }
        $rowCtr++;
        $cellsData[] = array('cell' => "B$rowCtr", 'data' => 'Total: ' . $rentToOwnCount);
        $cellsData[] = array('cell' => "C$rowCtr", 'data' => 'Total: ' . number_format($rentToOwnTotalPrice,2,'.',','));

        $accessoryCount = 0;
        $accessoryTotalPrice = 0;

        $rowCtr++;
        $rowCtr++;
        $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Accessory Summary');
        $rowCtr++;
        $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Branch');
        $cellsData[] = array('cell' => "B$rowCtr", 'data' => 'Count ');
        $cellsData[] = array('cell' => "C$rowCtr", 'data' => 'Total Amount');
        foreach($records2['accessory'] as $accessory) {

            $accessoryCount = $accessoryCount + $accessory['accessoryCount'];
            $accessoryTotalPrice = $accessoryTotalPrice + $accessory['price'];

            $rowCtr++;
            $cellsData[] = array('cell' => "A$rowCtr", 'data' => $accessory['billingBranch']);
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => number_format($accessory['accessoryCount'],2,'.',','));
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => number_format($accessory['price'],2,'.',','));
        }
        $rowCtr++;
        $cellsData[] = array('cell' => "B$rowCtr", 'data' => 'Total: ' . $accessoryCount);
        $cellsData[] = array('cell' => "C$rowCtr", 'data' => number_format($accessoryTotalPrice,2,'.',','));

        $cpapPackageCount = 0;
        $cpapPackageTotalPrice = 0;

        $rowCtr++;
        $rowCtr++;
        $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'CPAP Package Summary');
        $rowCtr++;
        $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Branch');
        $cellsData[] = array('cell' => "B$rowCtr", 'data' => 'Count ');
        $cellsData[] = array('cell' => "C$rowCtr", 'data' => 'Total Amount');
        foreach($records3['cpapPackage'] as $cpapPackage) {

            $cpapPackageCount = $cpapPackageCount + $cpapPackage['cpapPackageCount'];
            $cpapPackageTotalPrice = $cpapPackageTotalPrice + $cpapPackage['price'];

            $rowCtr++;
            $cellsData[] = array('cell' => "A$rowCtr", 'data' => $cpapPackage['billingBranch']);
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => number_format($cpapPackage['cpapPackageCount'],2,'.',','));
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => number_format($cpapPackage['price'],2,'.',','));
        }
        $rowCtr++;
        $cellsData[] = array('cell' => "B$rowCtr", 'data' => 'Total: ' . $cpapPackageCount);
        $cellsData[] = array('cell' => "C$rowCtr", 'data' => number_format($cpapPackageTotalPrice,2,'.',','));

        $medicalSuppliesCount = 0;
        $medicalSuppliesTotalPrice = 0;

        $rowCtr++;
        $rowCtr++;
        $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Medical Supplies Summary');
        $rowCtr++;
        $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Branch');
        $cellsData[] = array('cell' => "B$rowCtr", 'data' => 'Count ');
        $cellsData[] = array('cell' => "C$rowCtr", 'data' => 'Total Amount');
        foreach($records3['medicalSupplies'] as $medicalSupplies) {

            $medicalSuppliesCount = $medicalSuppliesCount + $medicalSupplies['medicalSuppliesCount'];
            $medicalSuppliesTotalPrice = $medicalSuppliesTotalPrice + $medicalSupplies['price'];

            $rowCtr++;
            $cellsData[] = array('cell' => "A$rowCtr", 'data' => $medicalSupplies['billingBranch']);
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => number_format($medicalSupplies['medicalSuppliesCount'],2,'.',','));
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => number_format($medicalSupplies['price'],2,'.',','));
        }
        $rowCtr++;
        $cellsData[] = array('cell' => "B$rowCtr", 'data' => 'Total: ' . $medicalSuppliesCount);
        $cellsData[] = array('cell' => "C$rowCtr", 'data' => number_format($medicalSuppliesTotalPrice,2,'.',','));


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

    //AR Report
    /**
     * @Route("/ar", name="report_ar")
     */
    public function arReportAction() {

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

        $session = $this->get('session');
        $userData = $session->get('userData');
        $em = $this->getDoctrine()->getManager();
        $company = $em->getRepository('RxConnexionBundle:CompanyEntity')->companiesForMultiple($userData);
        $branch = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->branchesForBillingMultiple($userData);

        $page_title = 'Account Receivable Report';
        return $this->render('@RxConnexion/Report/AccountsReceivable/index.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'company' => $company,
            'branch' => $branch,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/accountsReceivable/accountsReceivable.js?v=1.0.3')
        ));
    }

    /**
     * @Route(
     *      "/ar/preview/{interval}/{branch}/{patient}/{branch_address}/{company}",
     *      name = "report_ar_preview"
     * )
     */
    public function ar_previewAction($interval, $branch, $patient, $branch_address, $company) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Accounts Receivable Preview'))) return $authService->redirectToHome();

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientBillingEntity')->arReport(array(
            'interval' => $interval,
            'branch' => $branch,
            'patient' => $patient,
            'branch_address' => $branch_address,
            'company' => $company,
            'userData' => $userData,
        ));
        $records2 = $em->getRepository('RxConnexionBundle:PatientBillingEntity')->arReportSummary(array(
            'interval' => $interval,
            'branch' => $branch,
            'patient' => $patient,
            'branch_address' => $branch_address,
            'company' => $company,
            'userData' => $userData,
        ));

        $page_title = 'Accounts Receivable Report';
        return $this->render('@RxConnexion/Report/AccountsReceivable/preview.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'javascripts' => array('rxconnexion/admin/js/report/report_preview.js'),
            'records' => $records,
            'records2' => $records2,
            'interval' => $interval
        ));
    }

    /**
     * @Route(
     *      "/ar/export_to_pdf/{interval}/{branch}/{patient}/{branch_address}/{company}",
     *      name = "report_ar_export_to_pdf"
     * )
     */
    public function ar_export_to_pdfAction($interval, $branch, $patient, $branch_address, $company) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Accounts Receivable Pdf'))) return $authService->redirectToHome();

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientBillingEntity')->arReport(array(
            'interval' => $interval,
            'branch' => $branch,
            'patient' => $patient,
            'branch_address' => $branch_address,
            'company' => $company,
            'userData' => $userData,
        ));
        $records2 = $em->getRepository('RxConnexionBundle:PatientBillingEntity')->arReportSummary(array(
            'interval' => $interval,
            'branch' => $branch,
            'patient' => $patient,
            'branch_address' => $branch_address,
            'company' => $company,
            'userData' => $userData,
        ));

        $page_title = 'Accounts Receivable Report';
        $content = $this->renderView('@RxConnexion/Report/AccountsReceivable/preview.wkpdf.twig', array(
            'page_title' => $page_title,
            'records' => $records,
            'records2' => $records2,
            'interval' => $interval
        ));

        $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content, array(
            'orientation'=>'Landscape',
            'dpi' => 72,
            // 'disable-smart-shrinking',
            'zoom' => 'LINUX' == strtoupper(PHP_OS) ? 0.78 : 1
        ));

        $pdfResponse = array(
            'success' => true,
            'msg' => 'PDF was successfully generated.',
            'pdfBase64' => base64_encode($xml)
        );
        if($pdfResponse['success']) {
            $pdfContent = $pdfResponse['pdfBase64'];
            return new Response(base64_decode($pdfContent), 200, array(
                'Content-Type' => 'application/pdf',
                'Content-Disposition'   => 'attachment; filename="Accounts Receivable Report' . date('m/d/Y') . ' Details.pdf"'
            ));
        } else {
            $this->get('session')->getFlashBag()->set('error_messages', $pdfResponse['msg']);
            return $this->redirect($this->generateUrl('report_referral', 302));
        }
    }

    /**
     * @Route(
     *      "/ar/export_to_excel/{interval}/{branch}/{patient}/{branch_address}/{company}",
     *      name = "report_ar_export_to_excel"
     * )
     */
    public function ar_export_to_excelAction($interval, $branch, $patient, $branch_address, $company) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Accounts Receivable Excel'))) return $authService->redirectToHome();

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientBillingEntity')->arReport(array(
            'interval' => $interval,
            'branch' => $branch,
            'patient' => $patient,
            'branch_address' => $branch_address,
            'company' => $company,
            'userData' => $userData,
        ));
        $records2 = $em->getRepository('RxConnexionBundle:PatientBillingEntity')->arReportSummary(array(
            'interval' => $interval,
            'branch' => $branch,
            'patient' => $patient,
            'branch_address' => $branch_address,
            'company' => $company,
            'userData' => $userData,
        ));

        $columnRange = range('A', 'Z');
        $cellsData = array(
            array('cell' => 'A1', 'data' => 'Patient Name'),
            array('cell' => 'B1', 'data' => 'Payer'),
            array('cell' => 'C1', 'data' => 'Billing Branch'),
            array('cell' => 'D1', 'data' => 'Billing Branch Address'),
            array('cell' => 'E1', 'data' => 'Company'),
            array('cell' => 'F1', 'data' => 'Account Phase'),
            array('cell' => 'G1', 'data' => 'Invoice No.'),
            array('cell' => 'H1', 'data' => 'Date'),
            array('cell' => 'I1', 'data' => 'Reference No.'),
            array('cell' => 'J1', 'data' => 'Last Payment'),
            array('cell' => 'K1', 'data' => 'Last Payment Amount'),
            array('cell' => 'L1', 'data' => 'Outstanding Balance'),
            array('cell' => 'M1', 'data' => 'Total Invoice'),
            array('cell' => 'N1', 'data' => 'Next Due Date (Payment Plan)'),
            array('cell' => 'O1', 'data' => 'Demand Letter Date'),
            array('cell' => 'P1', 'data' => 'Date Claim to Insurance'),
            array('cell' => 'Q1', 'data' => 'Date Last Called'),
            array('cell' => 'R1', 'data' => 'Endorsed To'),
            array('cell' => 'S1', 'data' => 'Note'),
        );
        $rowCtr = 1;
        $totalCount = 0;
        $totalBalance = 0;
        $accountPhase = null;
        $secs = null;
        $days = null;

        foreach($records as $record) {

            $secs = strtotime(date("m/d/Y")) - strtotime($record['billingDate']);
            $days = $secs / 86400;

            if($days <= 29) {
                $accountPhase = 'Current';
            } else if($days <= 59) {
                $accountPhase = '30 Days';
            } else if($days <= 89) {
                $accountPhase = '60 Days';
            } else if($days <= 119) {
                $accountPhase = '90 Days';
            } else {
                $accountPhase = '120 Days or More';
            }

            $rowCtr++;
            $totalCount++;
            $totalBalance += $record['amtBalance'];

            $cellsData[] = array('cell' => "A$rowCtr", 'data' => $record['patient']);
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => $record['payer']);
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => $record['healthFacility_desc']);
            $cellsData[] = array('cell' => "D$rowCtr", 'data' => $record['healthFacilityForAddress_desc']);
            $cellsData[] = array('cell' => "E$rowCtr", 'data' => $record['notNullHealthFacility_companyDesc']);
            $cellsData[] = array('cell' => "F$rowCtr", 'data' => $accountPhase);
            $cellsData[] = array('cell' => "G$rowCtr", 'data' => $record['invoiceNo']);
            $cellsData[] = array('cell' => "H$rowCtr", 'data' => $record['billingDate']);
            $cellsData[] = array('cell' => "I$rowCtr", 'data' => $record['id']);
            $cellsData[] = array('cell' => "J$rowCtr", 'data' => $record['lastPaymentDate']);
            $cellsData[] = array('cell' => "K$rowCtr", 'data' => number_format($record['lastPaymentAmt'],2,'.',','));
            $cellsData[] = array('cell' => "L$rowCtr", 'data' => number_format($record['amtBalance'],2,'.',','));
            $cellsData[] = array('cell' => "M$rowCtr", 'data' => number_format($record['amtDue'],2,'.',','));
            $cellsData[] = array('cell' => "N$rowCtr", 'data' => $record['patientBilling_nextDue']);
            $cellsData[] = array('cell' => "O$rowCtr", 'data' => $record['patientBilling_demandLetterDate']);
            $cellsData[] = array('cell' => "P$rowCtr", 'data' => $record['patientBilling_insuranceClaimDate']);
            $cellsData[] = array('cell' => "Q$rowCtr", 'data' => $record['lastCalled']);
            $cellsData[] = array('cell' => "R$rowCtr", 'data' => $record['billing_endorsedTo']);
            $cellsData[] = array('cell' => "S$rowCtr", 'data' => strip_tags($record['note']));
        }

        $rowCtr++;
        $rowCtr++;
        $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Account Receivable (Summary): ');
        $rowCtr++;
        $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Billing Branch');
        $cellsData[] = array('cell' => "B$rowCtr", 'data' => 'Count ');
        $cellsData[] = array('cell' => "C$rowCtr", 'data' => 'Accounts Receivable ');
        foreach($records2 as $record2) {
            $rowCtr++;
            $cellsData[] = array('cell' => "A$rowCtr", 'data' => $record2['healthFacility']);
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => number_format($record2['totalCount'],2,'.',','));
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => number_format($record2['totalBalance'],2,'.',','));
        }
        $rowCtr++;
        $cellsData[] = array('cell' => "B$rowCtr", 'data' => 'Total: ' . $totalCount);
        $cellsData[] = array('cell' => "C$rowCtr", 'data' => 'Total: ' . number_format($totalBalance,2,'.',','));


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

    //Specialist Report
    /**
     * @Route("/specialist_referral_tracker", name="report_specialist_referral_tracker")
     */
    public function specialistReferralTrackerReportAction() {

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

        $session = $this->get('session');
        $userData = $session->get('userData');
        $em = $this->getDoctrine()->getManager();
        $company = $em->getRepository('RxConnexionBundle:CompanyEntity')->companiesForMultiple($userData);
        $branch = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->branchesForMultiple($userData);

        $page_title = 'Specialist Referral Report';
        return $this->render('@RxConnexion/Report/SpecialistReferralTracker/index.html.twig', array(
            'title' => $page_title,
            'company' => $company,
            'branch' => $branch,
            'page_title' => $page_title,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/specialistReferralTracker/specialistReferralTracker.js?v=1.0.2')
        ));
    }

    /**
     * @Route(
     *      "/specialist_referral_tracker/preview/{company}/{branch}/{servicing_branch}/{service}/{patient}/{specialist}/{type}",
     *      name = "report_specialist_referral_tracker_preview"
     * )
     */
    public function specialistReferralTracker_previewAction($company, $branch, $servicing_branch, $service, $patient, $specialist, $type) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Specialist Referral Tracker Preview'))) return $authService->redirectToHome();

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:ReferralEntity')->reportSpecialistReferralTracker(array(
            'company' => $company,
            'branch' => $branch,
            'servicing_branch' => $servicing_branch,
            'service' => $service,
            'patient' => $patient,
            'specialist' => $specialist,
            'type' => $type,
            'userData' => $userData
        ));

        $page_title = 'Specialist Referral Report';
        return $this->render('@RxConnexion/Report/SpecialistReferralTracker/preview.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'javascripts' => array('rxconnexion/admin/js/report/report_preview.js'),
            'records' => $records,
        ));
    }

    /**
     * @Route(
     *      "/specialist_referral_tracker/export_to_pdf/{company}/{branch}/{servicing_branch}/{service}/{patient}/{specialist}/{type}",
     *      name = "report_specialist_referral_tracker_export_to_pdf"
     * )
     */
    public function specialistReferralTracker_export_to_pdfAction($company, $branch, $servicing_branch, $service, $patient, $specialist, $type) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Specialist Referral Tracker Pdf'))) return $authService->redirectToHome();

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:ReferralEntity')->reportSpecialistReferralTracker(array(
            'company' => $company,
            'branch' => $branch,
            'servicing_branch' => $servicing_branch,
            'service' => $service,
            'patient' => $patient,
            'specialist' => $specialist,
            'type' => $type,
            'userData' => $userData
        ));

        $page_title = 'Specialist Referral Report';
        $content = $this->renderView('@RxConnexion/Report/SpecialistReferralTracker/preview.wkpdf.twig', array(
            'page_title' => $page_title,
            'records' => $records
        ));

        $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content, array(
            'orientation'=>'Landscape',
            'dpi' => 72,
            // 'disable-smart-shrinking',
            'zoom' => 'LINUX' == strtoupper(PHP_OS) ? 0.78 : 1
        ));

        $pdfResponse = array(
            'success' => true,
            'msg' => 'PDF was successfully generated.',
            'pdfBase64' => base64_encode($xml)
        );
        if($pdfResponse['success']) {
            $pdfContent = $pdfResponse['pdfBase64'];
            return new Response(base64_decode($pdfContent), 200, array(
                'Content-Type' => 'application/pdf',
                'Content-Disposition'   => 'attachment; filename="Specialist Referral Report' . date('m/d/Y') . ' Details.pdf"'
            ));
        } else {
            $this->get('session')->getFlashBag()->set('error_messages', $pdfResponse['msg']);
            return $this->redirect($this->generateUrl('report_referral', 302));
        }
    }

    /**
     * @Route(
     *      "/specialist_referral_tracker/export_to_excel/{company}/{branch}/{servicing_branch}/{service}/{patient}/{specialist}/{type}",
     *      name = "report_specialist_referral_tracker_export_to_excel"
     * )
     */
    public function specialistReferralTracker_export_to_excelAction($company, $branch, $servicing_branch, $service, $patient, $specialist, $type) {

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

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:ReferralEntity')->reportSpecialistReferralTracker(array(
            'company' => $company,
            'branch' => $branch,
            'servicing_branch' => $servicing_branch,
            'service' => $service,
            'patient' => $patient,
            'specialist' => $specialist,
            'type' => $type,
            'userData' => $userData
        ));

        $columnRange = range('A', 'Z');
        $cellsData = array(
            array('cell' => 'A1', 'data' => 'Patient'),
            array('cell' => 'B1', 'data' => 'Patient Type'),
            array('cell' => 'C1', 'data' => 'Referring Branch'),
            array('cell' => 'D1', 'data' => 'Clinician'),
            array('cell' => 'E1', 'data' => 'Diagnosis'),
            array('cell' => 'F1', 'data' => 'Encounter Type'),
            array('cell' => 'G1', 'data' => 'Encounter Date'),
            array('cell' => 'H1', 'data' => 'Encounter Status'),
            array('cell' => 'I1', 'data' => 'BMI'),
            array('cell' => 'J1', 'data' => 'O2 Saturation'),
            array('cell' => 'K1', 'data' => 'Initial AHI'),
            array('cell' => 'L1', 'data' => 'Current AHI'),
            array('cell' => 'M1', 'data' => 'Servicing Branch'),
            array('cell' => 'N1', 'data' => 'Service'),
            array('cell' => 'O1', 'data' => 'Specialist'),
            array('cell' => 'P1', 'data' => 'Encounter Type'),
            array('cell' => 'Q1', 'data' => 'Encounter Date'),
            array('cell' => 'R1', 'data' => 'Encounter Status'),
            array('cell' => 'S1', 'data' => 'Note'),
        );
        $rowCtr = 1;
        $totalCount = 0;

        foreach($records as $record) {

            $rowCtr++;
            $totalCount++;

            $cellsData[] = array('cell' => "A$rowCtr", 'data' => $record['patientName']);
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => $record['patientType']);
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => $record['healthFacility']);
            $cellsData[] = array('cell' => "D$rowCtr", 'data' => $record['providerFullName']);
            $cellsData[] = array('cell' => "E$rowCtr", 'data' => $record['diagnosisDesc']);
            $cellsData[] = array('cell' => "F$rowCtr", 'data' => $record['chartType']);
            $cellsData[] = array('cell' => "G$rowCtr", 'data' => $record['chartDate']);
            $cellsData[] = array('cell' => "H$rowCtr", 'data' => $record['chartStatus']);
            $cellsData[] = array('cell' => "I$rowCtr", 'data' => $record['bmi']);
            $cellsData[] = array('cell' => "J$rowCtr", 'data' => $record['otwo_saturation']);
            $cellsData[] = array('cell' => "K$rowCtr", 'data' => $record['init_ahi']);
            $cellsData[] = array('cell' => "L$rowCtr", 'data' => $record['ahi']);
            $cellsData[] = array('cell' => "M$rowCtr", 'data' => $record['servicingHealthFacility']);
            $cellsData[] = array('cell' => "N$rowCtr", 'data' => $record['serviceDesc']);
            $cellsData[] = array('cell' => "O$rowCtr", 'data' => $record['specialistFullName']);
            $cellsData[] = array('cell' => "P$rowCtr", 'data' => $record['sp_chartType']);
            $cellsData[] = array('cell' => "Q$rowCtr", 'data' => $record['sp_chartDate']);
            $cellsData[] = array('cell' => "R$rowCtr", 'data' => $record['sp_chartStatus']);
            $cellsData[] = array('cell' => "S$rowCtr", 'data' => strip_tags($record['note']));
        }

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


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

    //Appointment History Report
    /**
     * @Route("/appointment_history_report", name="report_appointment_history")
     */
    public function appointmentHistoryReportAction() {

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

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

        $em = $this->getDoctrine()->getManager();
        $company = $em->getRepository('RxConnexionBundle:CompanyEntity')->companiesForMultiple($userData);
        $branch = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->branchesForMultiple($userData);

        $page_title = 'Appointment History Report';
        return $this->render('@RxConnexion/Report/AppointmentHistory/index.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'company' => $company,
            'branch' => $branch,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/appointmentHistory/appointmentHistory.js')
        ));
    }

    /**
     * @Route(
     *      "/appointment_history_report/preview/{date_from}/{date_to}/{company}/{branch}/{patient}/{chartType}/{clinician}",
     *      name = "report_appointment_history_preview"
     * )
     */
    public function appointmentHistory_previewAction($date_from, $date_to, $company, $branch, $patient, $chartType, $clinician) {

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

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientChartEntity')->reportAppointmentHistory(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company,
            'branch' => $branch,
            'patient' => $patient,
            'chartType' => $chartType,
            'clinician' => $clinician,
            'userData' => $userData
        ));

        $patient = array(
            'name' => null,
            'rowspan' => 0,
            'key' => 0,
            'total' => 0
        );

        foreach ($records as $key => $appointmentHistory) {

            if($patient['name'] != $appointmentHistory['patientName'] && $key > 0) {
                $records[$patient['key']]['rowPatient'] = array(
                    'name' => $patient['name'],
                    'rowspan' => $patient['rowspan'],
                );

                $patient['key'] = $key;
                $patient['rowspan'] = 0;
            }


            $patient['name'] = $appointmentHistory['patientName'];

            $patient['rowspan']++;
        }

        $records[$patient['key']]['rowPatient'] = array(
            'name' => $patient['name'],
            'rowspan' => $patient['rowspan'],
        );

        $page_title = 'Appointment History Report';
        return $this->render('@RxConnexion/Report/AppointmentHistory/preview.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'javascripts' => array('rxconnexion/admin/js/report/report_preview.js'),
            'records' => $records,
        ));
    }

    /**
     * @Route(
     *      "/appointment_history_report/export_to_pdf/{date_from}/{date_to}/{company}/{branch}/{patient}/{chartType}/{clinician}",
     *      name = "report_appointment_history_export_to_pdf"
     * )
     */
    public function appointmentHistory_export_to_pdfAction($date_from, $date_to, $company, $branch, $patient, $chartType, $clinician) {

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

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientChartEntity')->reportAppointmentHistory(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company,
            'branch' => $branch,
            'patient' => $patient,
            'chartType' => $chartType,
            'clinician' => $clinician,
            'userData' => $userData
        ));

        $patient = array(
            'name' => null,
            'rowspan' => 0,
            'key' => 0,
            'total' => 0
        );

        foreach ($records as $key => $appointmentHistory) {

            if($patient['name'] != $appointmentHistory['patientName'] && $key > 0) {
                $records[$patient['key']]['rowPatient'] = array(
                    'name' => $patient['name'],
                    'rowspan' => $patient['rowspan'],
                );

                $patient['key'] = $key;
                $patient['rowspan'] = 0;

            }


            $patient['name'] = $appointmentHistory['patientName'];

            $patient['rowspan']++;
        }

        $records[$patient['key']]['rowPatient'] = array(
            'name' => $patient['name'],
            'rowspan' => $patient['rowspan'],
        );

        $page_title = 'Appointment History Report';
        $content = $this->renderView('@RxConnexion/Report/AppointmentHistory/preview.wkpdf.twig', array(
            'page_title' => $page_title,
            'records' => $records
        ));

        $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content, array(
            'orientation'=>'Landscape',
            'dpi' => 72,
            // 'disable-smart-shrinking',
            'zoom' => 'LINUX' == strtoupper(PHP_OS) ? 0.78 : 1
        ));

        $pdfResponse = array(
            'success' => true,
            'msg' => 'PDF was successfully generated.',
            'pdfBase64' => base64_encode($xml)
        );
        if($pdfResponse['success']) {
            $pdfContent = $pdfResponse['pdfBase64'];
            return new Response(base64_decode($pdfContent), 200, array(
                'Content-Type' => 'application/pdf',
                'Content-Disposition'   => 'attachment; filename="Appointment History Report' . date('m/d/Y') . ' Details.pdf"'
            ));
        } else {
            $this->get('session')->getFlashBag()->set('error_messages', $pdfResponse['msg']);
            return $this->redirect($this->generateUrl('appointment_history', 302));
        }
    }

    /**
     * @Route(
     *      "/appointment_history_report/export_to_excel/{date_from}/{date_to}/{company}/{branch}/{patient}/{chartType}/{clinician}",
     *      name = "report_appointment_history_export_to_excel"
     * )
     */
    public function appointmentHistory_export_to_excelAction($date_from, $date_to, $company, $branch, $patient, $chartType, $clinician) {

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

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientChartEntity')->reportAppointmentHistory(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company,
            'branch' => $branch,
            'patient' => $patient,
            'chartType' => $chartType,
            'clinician' => $clinician,
            'userData' => $userData
        ));

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

        $activeSheet->setCellValue('A1', 'Patient');
        $activeSheet->setCellValue('B1', 'Encounter Type');
        $activeSheet->setCellValue('C1', 'Encounter Date');
        $activeSheet->setCellValue('D1', 'Encounter Status');
        $activeSheet->setCellValue('E1', 'Note');
        $activeSheet->getStyle('A1:E1')->applyFromArray(array(
            'fill' => array(
                'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                'color' => array('rgb' => 'ADD8E6')
            ),
            'borders' => array(
                'allborders' => array(
                    'style' => \PHPExcel_Style_Border::BORDER_THIN
                )
            )
        ));

        $rowCtr = 1;

        $patient = array(
            'name' => null,
            'rowStart' => null,
            'total' => 0
        );



        foreach($records as $record) {

            $rowCtr++;

            if ($patient['name'] != $record['patientName']) {

                if ($patient['rowStart'] > 0) {

                    $activeSheet->getStyle('A'.$patient['rowStart'].':A'.($rowCtr-1))->applyFromArray(array(
                        'borders' => array(
                            'allborders' => array(
                                'style' => \PHPExcel_Style_Border::BORDER_THIN
                            )
                        )
                    ));
                    $activeSheet->mergeCells('A'.$patient['rowStart'].':A'.($rowCtr-1));
                    $activeSheet->getStyle('A'.$patient['rowStart'])->applyFromArray(array(
                        'alignment' => array(
                            'vertical' => \PHPExcel_Style_Alignment::VERTICAL_CENTER,
                            'horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
                        ),
                        'fill' => array(
                            'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                            'color' => array('rgb' => 'DBDBDB')
                        ),
                    ));

                }

                $activeSheet->setCellValue('A'.$rowCtr, $record['patientName']);

                $patient = array(
                    'name' =>  $record['patientName'],
                    'rowStart' => $rowCtr,
                    'total' => 0
                );

            }

            $activeSheet->setCellValue('B'.$rowCtr, $record['chartType']);
            $activeSheet->setCellValue('C'.$rowCtr, $record['chartDate']);
            $activeSheet->setCellValue('D'.$rowCtr, $record['chartStatus']);
            $activeSheet->setCellValue('E'.$rowCtr, $record['note']);
        }

        $rowCtr++;

        if ($patient['rowStart'] > 0) {

            $activeSheet->getStyle('A'.$patient['rowStart'].':A'.($rowCtr-1))->applyFromArray(array(
                'borders' => array(
                    'allborders' => array(
                        'style' => \PHPExcel_Style_Border::BORDER_THIN
                    )
                )
            ));
            $activeSheet->mergeCells('A'.$patient['rowStart'].':A'.($rowCtr-1));
            $activeSheet->getStyle('A'.$patient['rowStart'])->applyFromArray(array(
                'alignment' => array(
                    'vertical' => \PHPExcel_Style_Alignment::VERTICAL_CENTER,
                    'horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
                ),
                'fill' => array(
                    'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                    'color' => array('rgb' => 'DBDBDB')
                ),
            ));
        }

        $page_title = 'Appointment History Report';

        $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;
    }

    //Status Report
    /**
     * @Route("/status_report", name="report_status")
     */
    public function statusReportAction() {

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

        $page_title = 'Status Report';
        return $this->render('@RxConnexion/Report/StatusReport/index.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/statusReport/statusReport.js?v=1.0.1')
        ));
    }

    /**
     * @Route(
     *      "/status/data",
     *      name = "report_status_data"
     * )
     */
    public function statusReportData(Request $request) {
        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Status'))) return $authService->redirectToHome();

        ini_set('memory_limit', '2048M');
        set_time_limit(0);
        $result = array();

        $dateFrom = $request->request->get('dateFrom');
        $dateTo = $request->request->get('dateTo');

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:ReferralEntity')->reportStatus(array(
            'date_from' => $dateFrom ? $dateFrom : date('m/01/Y'),
            'date_to' => $dateTo ? $dateTo :  date('m/d/Y'),
        ));

        $result['success'] = true;
        $result['data'] = $records;

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/patient_progress/redirect/preview/{date_from}/{date_to}/{branch_desc}/{billing_branch_desc}/{patient}/{type}",
     *      defaults = {
     *          "date_from":  "null",
     *          "date_to":  "null",
     *          "branch_desc":  "null",
     *          "billing_branch_desc":  "null",
     *          "patient":  "null",
     *          "type":  "null",
     *      },
     *
     *      name = "report_referral_redirect_preview",
     *
     * )
     */
    public function referral_redirect_previewAction($date_from, $date_to, $branch_desc, $billing_branch_desc, $patient, $type) {

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

        $patientBranch = 'null';
        if($branch_desc != null && $branch_desc != 'null') {
            $branch = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->findOneBy(array(
                'description' => strip_tags($branch_desc)
            ));

            $patientBranch = $branch->getId();
        }

        $patientBillingBranch = 'null';
        if($billing_branch_desc != null && $billing_branch_desc != 'null') {
            $billingBranch = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->findOneBy(array(
                'description' => strip_tags($billing_branch_desc)
            ));

            $patientBillingBranch = $billingBranch->getId();
        }


        //Sales Report
        $chartType = 'null';
        if(strip_tags($type) == 'CPAP Evaluation') {
            $chartTypes = $em->getRepository('RxConnexionBundle:ChartTypeEntity')->findOneBy(array(
                'description' => 'CPAP End Eval'
            ));

            $chartType = $chartTypes->getId();
            $chartStatus = 'null';
        } else if(strip_tags($type) == 'Sold') {
            $chartTypes = $em->getRepository('RxConnexionBundle:ChartTypeEntity')->findOneBy(array(
                'description' => 'CPAP Setup Sold'
            ));

            $chartType = $chartTypes->getId();
            $chartStatus = 'null';
        } else {
            $chartStatus = 'null';
        }

        //Referral Report
        if(strip_tags($type) == 'Declined' || strip_tags($type) == 'No Show' || strip_tags($type) == 'Cancelled') {
            $chartStatus = strip_tags($type);
        }

        return $this->redirect($this->generateUrl('patient_progress_preview', array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'receive_date_from' => 'null',
            'receive_date_to' => 'null',
            'patient' => $patient,
            'company' => 'null',
            'branch' => $patientBranch,
            'billingBranch' => $patientBillingBranch,
            'chartType' => $chartType,
            'chartStatus' => $chartStatus,
            'cpap_date_from' => 'null',
            'cpap_date_to' => 'null',
            'cpap_status' => 'null',
            'cpap_sold_date_from' => 'null',
            'cpap_sold_date_to' => 'null',
            'cpap_sold_status' => 'null',
            'hsat_date_from' => 'null',
            'hsat_date_to' => 'null',
            'hsat_status' => 'null',
            'hsat_mobile_date_from' => 'null',
            'hsat_mobile_date_to' => 'null',
            'hsat_mobile_status' => 'null',
            'oximetry_date_from' => 'null',
            'oximetry_date_to' => 'null',
            'oximetry_status' => 'null',
            'hsat_ri_date_from' => 'null',
            'hsat_ri_date_to' => 'null',
            'hsat_ri_status' => 'null',
            'cpap_eval_date_from' => 'null',
            'cpap_eval_date_to' => 'null',
            'cpap_eval_status' => 'null',
            'chart_type_cycle' => 'null',
            'clinician' => 'null',
            'booked' => 'null',
            'unbooked' => 'null',
        )), 302);
    }


    /**
     * @Route(
     *      "/patient_progress/redirect/cycle/preview/{date_from}/{date_to}/{company}/{branch}/{clinician}/{chartTypeCycle}",
     *      defaults = {
     *          "date_from" = null,
     *          "date_to" = null,
     *          "company" = null,
     *          "branch" = null,
     *          "clinician" = null,
     *          "chartTypeCycle" = null,
     *      },
     *
     *      name = "report_cycle_redirect_preview",
     *
     * )
     */
    public function cycle_redirect_previewAction($date_from, $date_to, $company, $branch, $clinician, $chartTypeCycle) {

        return $this->redirect($this->generateUrl('patient_progress_preview', array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'receive_date_from' => 'null',
            'receive_date_to' => 'null',
            'patient' => 'null',
            'company' => $company,
            'branch' => $branch,
            'billingBranch' => 'null',
            'chartType' => 'null',
            'chartStatus' => 'null',
            'cpap_date_from' => 'null',
            'cpap_date_to' => 'null',
            'cpap_status' => 'null',
            'cpap_sold_date_from' => 'null',
            'cpap_sold_date_to' => 'null',
            'cpap_sold_status' => 'null',
            'hsat_date_from' => 'null',
            'hsat_date_to' => 'null',
            'hsat_status' => 'null',
            'hsat_mobile_date_from' => 'null',
            'hsat_mobile_date_to' => 'null',
            'hsat_mobile_status' => 'null',
            'oximetry_date_from' => 'null',
            'oximetry_date_to' => 'null',
            'oximetry_status' => 'null',
            'hsat_ri_date_from' => 'null',
            'hsat_ri_date_to' => 'null',
            'hsat_ri_status' => 'null',
            'cpap_eval_date_from' => 'null',
            'cpap_eval_date_to' => 'null',
            'cpap_eval_status' => 'null',
            'chart_type_cycle' => $chartTypeCycle,
            'clinician' => $clinician,
            'booked' => 'null',
            'unbooked' => 'null'
        )), 302);
    }

    /**
     * @Route(
     *      "/patient_progress/redirect/management_dashboard/preview/{date_from}/{date_to}/{company}/{branch}/{clinician}/{chart_type}/{chart_status}/{invoices}",
     *      defaults = {
     *          "date_from" = null,
     *          "date_to" = null,
     *          "company" = null,
     *          "branch" = null,
     *          "clinician" = null,
     *          "chart_type" = null,
     *          "chart_status" = null,
     *          "invoices" = null,
     *      },
     *
     *      name = "report_management_dashboard_redirect_preview",
     *
     * )
     */
    public function management_dashboard_redirect_previewAction($date_from, $date_to, $company, $branch, $clinician, $chart_type, $chart_status, $invoices) {

        $chartStatus_hsat = 'All';
        $chartStatus_hsat_mobile = 'All';
        $chartStatus_hri = 'All';
        $chartStatus_cpap = 'All';
        $chartStatus_cpap_sold = 'All';
        $chartStatus_eval = 'All';
        $chartStatus_end_eval = 'All';
        if(strip_tags($chart_type) == 'HSAT') {
            $chartStatus_hsat = strip_tags($chart_status);
        }

        if(strip_tags($chart_type) == 'HSAT (Mobile)') {
            $chartStatus_hsat_mobile = strip_tags($chart_status);
        }

        if(strip_tags($chart_type) == 'HSAT Results Interpretation') {
            $chartStatus_hri = strip_tags($chart_status);
        }

        if(strip_tags($chart_type) == 'CPAP Setup') {
            $chartStatus_cpap = strip_tags($chart_status);
        }

        if(strip_tags($chart_type) == 'CPAP Setup Sold') {
            $chartStatus_cpap_sold = strip_tags($chart_status);
        }

        if(strip_tags($chart_type) == 'CPAP Eval') {
            $chartStatus_eval = strip_tags($chart_status);
        }

        if(strip_tags($chart_type) == 'CPAP End Eval') {
            $chartStatus_end_eval = strip_tags($chart_status);
        }

        if($invoices) {

        }

        return $this->redirect($this->generateUrl('patient_progress_preview', array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'receive_date_from' => 'null',
            'receive_date_to' => 'null',
            'patient' => 'null',
            'company' => $company,
            'branch' => $branch,
            'billingBranch' => 'null',
            'chartType' => 'null',
            'chartStatus' => 'null',
            'cpap_date_from' => 'null',
            'cpap_date_to' => 'null',
            'cpap_status' => $chartStatus_cpap,
            'cpap_sold_date_from' => 'null',
            'cpap_sold_date_to' => 'null',
            'cpap_sold_status' => $chartStatus_cpap_sold,
            'hsat_date_from' => 'null',
            'hsat_date_to' => 'null',
            'hsat_status' => $chartStatus_hsat,
            'hsat_mobile_date_from' => 'null',
            'hsat_mobile_date_to' => 'null',
            'hsat_mobile_status' => $chartStatus_hsat_mobile,
            'oximetry_date_from' => 'null',
            'oximetry_date_to' => 'null',
            'oximetry_status' => 'null',
            'hsat_ri_date_from' => 'null',
            'hsat_ri_date_to' => 'null',
            'hsat_ri_status' => $chartStatus_hri,
            'cpap_eval_date_from' => 'null',
            'cpap_eval_date_to' => 'null',
            'cpap_eval_status' => $chartStatus_eval,
            'chart_type_cycle' => 'null',
            'clinician' => $clinician,
            'booked' => 'null',
            'unbooked' => 'null',
        )), 302);
    }

    /**
     * @Route(
     *      "/patient_progress/redirect/link/preview/{date_from}/{date_to}/{receive_date_from}/{receive_date_to}/{branch}/{clinician}/{booked}/{unbooked}",
     *      defaults = {
     *          "date_from" = null,
     *          "date_to" = null,
     *          "receive_date_from" = null,
     *          "receive_date_to" = null,
     *          "branch" = null,
     *          "clinician" = null,
     *          "booked" = null,
     *          "unbooked" = null,
     *      },
     *
     *      name = "report_link_patient_progress_report_redirect_preview",
     *
     * )
     */
    public function branch_patient_progress_report_redirect_previewAction($date_from, $date_to, $receive_date_from, $receive_date_to, $branch, $clinician, $booked, $unbooked) {

        return $this->redirect($this->generateUrl('patient_progress_preview', array(
            'date_from' => $date_from != 'null' ? $date_from : 'null',
            'date_to' => $date_to != 'null' ? $date_to : 'null',
            'receive_date_from' => $receive_date_from != 'null' ? $receive_date_from : 'null',
            'receive_date_to' => $receive_date_to != 'null' ? $receive_date_to : 'null',
            'patient' => 'null',
            'company' => 'null',
            'branch' => $branch != 'null' ? $branch : 'null',
            'billingBranch' => 'null',
            'chartType' => 'null',
            'chartStatus' => 'null',
            'cpap_date_from' => 'null',
            'cpap_date_to' => 'null',
            'cpap_status' => 'null',
            'cpap_sold_date_from' => 'null',
            'cpap_sold_date_to' => 'null',
            'cpap_sold_status' => 'null',
            'hsat_date_from' => 'null',
            'hsat_date_to' => 'null',
            'hsat_status' => 'null',
            'hsat_mobile_date_from' => 'null',
            'hsat_mobile_date_to' => 'null',
            'hsat_mobile_status' => 'null',
            'oximetry_date_from' => 'null',
            'oximetry_date_to' => 'null',
            'oximetry_status' => 'null',
            'hsat_ri_date_from' => 'null',
            'hsat_ri_date_to' => 'null',
            'hsat_ri_status' => 'null',
            'cpap_eval_date_from' => 'null',
            'cpap_eval_date_to' => 'null',
            'cpap_eval_status' => 'null',
            'chart_type_cycle' => 'null',
            'clinician' => $clinician != 'null' ? $clinician : 'null',
            'booked' => $booked != 'null' ? $booked : 'null',
            'unbooked' => $unbooked != 'null' ? $unbooked : 'null',
        )), 302);
    }

    //Patient Progress Summary Report
    /**
     * @Route("/patient_progress", name="report_patient_progress")
     */
    public function patientProgressReportAction() {

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

        $em = $this->getDoctrine()->getManager();
        $encounterStatus = $em->getRepository('RxConnexionBundle:PatientChartEntity')->findEncounterTypeStatus();
        $cpapStatus = $em->getRepository('RxConnexionBundle:ChartStatusEntity')->findPatientProgressReportStatus();

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

        $branch = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->branchesForMultiple($userData);
        $company = $em->getRepository('RxConnexionBundle:CompanyEntity')->companiesForMultiple($userData);

        $page_title = 'Patient Progress Report';
        return $this->render('@RxConnexion/Report/PatientProgress/index.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'chartStatus' => $encounterStatus,
            'cpapStatus' => $cpapStatus,
            'branch' => $branch,
            'company' => $company,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/patientProgress/patientProgress.js?v=1.0.3')
        ));
    }

    /**
     * @Route(
     *      "/patient_progress/preview/{date_from}/{date_to}/{receive_date_from}/{receive_date_to}/{patient}/{company}/{branch}/{billingBranch}/{chartType}/{chartStatus}/{cpap_date_from}/{cpap_date_to}/{cpap_status}/{cpap_sold_date_from}/{cpap_sold_date_to}/{cpap_sold_status}/{hsat_date_from}/{hsat_date_to}/{hsat_status}/{hsat_mobile_date_from}/{hsat_mobile_date_to}/{hsat_mobile_status}/{oximetry_date_from}/{oximetry_date_to}/{oximetry_status}/{hsat_ri_date_from}/{hsat_ri_date_to}/{hsat_ri_status}/{cpap_eval_date_from}/{cpap_eval_date_to}/{cpap_eval_status}/{chart_type_cycle}/{clinician}/{booked}/{unbooked}",
         *      name = "patient_progress_preview"
     * )
     */
    public function patientProgress_previewAction($date_from, $date_to, $receive_date_from, $receive_date_to, $patient, $company, $branch, $billingBranch, $chartType, $chartStatus, $cpap_date_from, $cpap_date_to, $cpap_status, $cpap_sold_date_from, $cpap_sold_date_to, $cpap_sold_status, $hsat_date_from,$hsat_date_to,$hsat_status,$hsat_mobile_date_from,$hsat_mobile_date_to,$hsat_mobile_status, $oximetry_date_from,$oximetry_date_to,$oximetry_status,$hsat_ri_date_from,$hsat_ri_date_to,$hsat_ri_status,$cpap_eval_date_from,$cpap_eval_date_to,$cpap_eval_status,$chart_type_cycle,$clinician,$booked,$unbooked) {

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

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

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

        $hsatChartType = $em->getRepository('RxConnexionBundle:ChartTypeEntity')->findOneBy(array(
            'description' => 'HSAT'
        ));

        $hsatMobileChartType = $em->getRepository('RxConnexionBundle:ChartTypeEntity')->findOneBy(array(
            'description' => 'HSAT (Mobile)'
        ));

        $hsatResultInterpretationChartType = $em->getRepository('RxConnexionBundle:ChartTypeEntity')->findOneBy(array(
            'description' => 'HSAT Results Interpretation'
        ));

        $oximetryChartType = $em->getRepository('RxConnexionBundle:ChartTypeEntity')->findOneBy(array(
            'description' => 'Oximetry'
        ));

        $cpapSetupChartType = $em->getRepository('RxConnexionBundle:ChartTypeEntity')->findOneBy(array(
            'description' => 'CPAP Setup'
        ));

        $cpapSetupSoldChartType = $em->getRepository('RxConnexionBundle:ChartTypeEntity')->findOneBy(array(
            'description' => 'CPAP Setup Sold'
        ));

        $cpapEvalChartType = $em->getRepository('RxConnexionBundle:ChartTypeEntity')->findOneBy(array(
            'description' => 'CPAP Eval'
        ));

        $cpapEndEvalChartType = $em->getRepository('RxConnexionBundle:ChartTypeEntity')->findOneBy(array(
            'description' => 'CPAP End Eval'
        ));

        $branchDesc = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->findOneBy(array(
           'id' => $branch
        ));

        $providerDesc = $em->getRepository('RxConnexionBundle:ProviderEntity')->findOneBy(array(
            'id' => $clinician
        ));


        $records = $em->getRepository('RxConnexionBundle:ReferralEntity')->reportPatientProgress(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'receive_date_from' => $receive_date_from,
            'receive_date_to' => $receive_date_to,
            'patient' => $patient,
            'company' => $company,
            'branch' => $branch,
            'billingHealthFacility' => $billingBranch,
            'chartType' => $chartType,
            'chartStatus' => $chartStatus,
            'cpap_date_from' => $cpap_date_from,
            'cpap_date_to' => $cpap_date_to,
            'cpap_status' => $cpap_status,
            'cpap_sold_date_from' => $cpap_sold_date_from,
            'cpap_sold_date_to' => $cpap_sold_date_to,
            'cpap_sold_status' => $cpap_sold_status,
            'hsat_date_from' => $hsat_date_from,
            'hsat_date_to' => $hsat_date_to,
            'hsat_status' => $hsat_status,
            'hsat_mobile_date_from' => $hsat_mobile_date_from,
            'hsat_mobile_date_to' => $hsat_mobile_date_to,
            'hsat_mobile_status' => $hsat_mobile_status,
            'oximetry_date_from' => $oximetry_date_from,
            'oximetry_date_to' => $oximetry_date_to,
            'oximetry_status' => $oximetry_status,
            'hsat_ri_date_from' => $hsat_ri_date_from,
            'hsat_ri_date_to' => $hsat_ri_date_to,
            'hsat_ri_status' => $hsat_ri_status,
            'cpap_eval_date_from' => $cpap_eval_date_from,
            'cpap_eval_date_to' => $cpap_eval_date_to,
            'cpap_eval_status' => $cpap_eval_status,
            'chart_type_cycle' => $chart_type_cycle,
            'clinician' => $clinician,
            'booked' => $booked,
            'unbooked' => $unbooked,
        ));

        $summary = $em->getRepository('RxConnexionBundle:ReferralEntity')->reportPatientProgressSummary(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'receive_date_from' => $receive_date_from,
            'receive_date_to' => $receive_date_to,
            'patient' => $patient,
            'company' => $company,
            'branch' => $branch,
            'billingHealthFacility' => $billingBranch,
            'chartType' => $chartType,
            'chartStatus' => $chartStatus,
            'cpap_date_from' => $cpap_date_from,
            'cpap_date_to' => $cpap_date_to,
            'cpap_status' => $cpap_status,
            'cpap_sold_date_from' => $cpap_sold_date_from,
            'cpap_sold_date_to' => $cpap_sold_date_to,
            'cpap_sold_status' => $cpap_sold_status,
            'hsat_date_from' => $hsat_date_from,
            'hsat_date_to' => $hsat_date_to,
            'hsat_status' => $hsat_status,
            'hsat_mobile_date_from' => $hsat_mobile_date_from,
            'hsat_mobile_date_to' => $hsat_mobile_date_to,
            'hsat_mobile_status' => $hsat_mobile_status,
            'oximetry_date_from' => $oximetry_date_from,
            'oximetry_date_to' => $oximetry_date_to,
            'oximetry_status' => $oximetry_status,
            'hsat_ri_date_from' => $hsat_ri_date_from,
            'hsat_ri_date_to' => $hsat_ri_date_to,
            'hsat_ri_status' => $hsat_ri_status,
            'cpap_eval_date_from' => $cpap_eval_date_from,
            'cpap_eval_date_to' => $cpap_eval_date_to,
            'cpap_eval_status' => $cpap_eval_status,
            'chart_type_cycle' => $chart_type_cycle,
            'clinician' => $clinician,
            'booked' => $booked,
            'unbooked' => $unbooked,
        ));

        $page_title = 'Patient Progress Report';
        return $this->render('@RxConnexion/Report/PatientProgress/preview.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css?v=1.0.1'),
            'javascripts' => array('rxconnexion/admin/js/report/report_preview.js?v=1.0.1'),
            'records' => $records,
            'summary' => $summary,
            'hsatExpNoOfDays' => $hsatChartType ? $hsatChartType->getExpectedNoOfDays() : 0,
            'hsatMobileExpNoOfDays' => $hsatMobileChartType ? $hsatMobileChartType->getExpectedNoOfDays() : 0,
            'hsatResultInterpretationNoOfDays' => $hsatResultInterpretationChartType ? $hsatResultInterpretationChartType->getExpectedNoOfDays() : 0,
            'oximetryNoOfDays' => $oximetryChartType ? $oximetryChartType->getExpectedNoOfDays() : 0,
            'cpapSetupNoOfDays' => $cpapSetupChartType ? $cpapSetupChartType->getExpectedNoOfDays() : 0,
            'cpapSetupSoldNoOfDays' => $cpapSetupSoldChartType ? $cpapSetupSoldChartType->getExpectedNoOfDays() : 0,
            'cpapEvalNoOfDays' => $cpapEvalChartType ? $cpapEvalChartType->getExpectedNoOfDays() : 0,
            'cpapEndEvalNoOfDays' => $cpapEndEvalChartType ? $cpapEndEvalChartType->getExpectedNoOfDays() : 0,
            'dateFrom' => $date_from,
            'dateTo' => $date_to,
            'receiveDateFrom' => $receive_date_from,
            'receiveDateTo' => $receive_date_to,
            'booked' => $booked,
            'unbooked' => $unbooked,
            'branchDesc' => !empty($branchDesc) ? $branchDesc->getDescription() : 'null',
            'providerDesc' => !empty($providerDesc) ? $providerDesc->getFullName() : 'null',
        ));
    }

    /**
     * @Route(
     *      "/patient_progress/export_to_pdf/{date_from}/{date_to}/{receive_date_from}/{receive_date_to}/{patient}/{company}/{branch}/{billingBranch}/{chartType}/{chartStatus}/{cpap_date_from}/{cpap_date_to}/{cpap_status}/{cpap_sold_date_from}/{cpap_sold_date_to}/{cpap_sold_status}/{hsat_date_from}/{hsat_date_to}/{hsat_status}/{hsat_mobile_date_from}/{hsat_mobile_date_to}/{hsat_mobile_status}/{oximetry_date_from}/{oximetry_date_to}/{oximetry_status}/{hsat_ri_date_from}/{hsat_ri_date_to}/{hsat_ri_status}/{cpap_eval_date_from}/{cpap_eval_date_to}/{cpap_eval_status}/{chart_type_cycle}{clinician}",
     *      name = "report_patient_progress_export_to_pdf"
     * )
     */
    public function patientProgress_export_to_pdfAction($date_from, $date_to, $receive_date_from, $receive_date_to, $patient, $company, $branch, $billingBranch, $chartType, $chartStatus, $cpap_date_from, $cpap_date_to, $cpap_status, $cpap_sold_date_from, $cpap_sold_date_to, $cpap_sold_status, $hsat_date_from,$hsat_date_to,$hsat_status,$hsat_mobile_date_from,$hsat_mobile_date_to,$hsat_mobile_status,$oximetry_date_from,$oximetry_date_to,$oximetry_status,$hsat_ri_date_from,$hsat_ri_date_to,$hsat_ri_status,$cpap_eval_date_from,$cpap_eval_date_to,$cpap_eval_status,$chart_type_cycle,$clinician) {

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

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

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

        $hsatChartType = $em->getRepository('RxConnexionBundle:ChartTypeEntity')->findOneBy(array(
            'description' => 'HSAT'
        ));

        $records = $em->getRepository('RxConnexionBundle:ReferralEntity')->reportPatientProgress(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'receive_date_from' => $receive_date_from,
            'receive_date_to' => $receive_date_to,
            'patient' => $patient,
            'company' => $company,
            'branch' => $branch,
            'billingHealthFacility' => $billingBranch,
            'chartType' => $chartType,
            'chartStatus' => $chartStatus,
            'cpap_date_from' => $cpap_date_from,
            'cpap_date_to' => $cpap_date_to,
            'cpap_status' => $cpap_status,
            'cpap_sold_date_from' => $cpap_sold_date_from,
            'cpap_sold_date_to' => $cpap_sold_date_to,
            'cpap_sold_status' => $cpap_sold_status,
            'hsat_date_from' => $hsat_date_from,
            'hsat_date_to' => $hsat_date_to,
            'hsat_status' => $hsat_status,
            'oximetry_date_from' => $oximetry_date_from,
            'oximetry_date_to' => $oximetry_date_to,
            'oximetry_status' => $oximetry_status,
            'hsat_ri_date_from' => $hsat_ri_date_from,
            'hsat_ri_date_to' => $hsat_ri_date_to,
            'hsat_ri_status' => $hsat_ri_status,
            'cpap_eval_date_from' => $cpap_eval_date_from,
            'cpap_eval_date_to' => $cpap_eval_date_to,
            'cpap_eval_status' => $cpap_eval_status,
            'clinician' => $clinician
        ));

        $summary = $em->getRepository('RxConnexionBundle:ReferralEntity')->reportPatientProgressSummary(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'receive_date_from' => $receive_date_from,
            'receive_date_to' => $receive_date_to,
            'patient' => $patient,
            'company' => $company,
            'branch' => $branch,
            'billingHealthFacility' => $billingBranch,
            'chartType' => $chartType,
            'chartStatus' => $chartStatus,
            'cpap_date_from' => $cpap_date_from,
            'cpap_date_to' => $cpap_date_to,
            'cpap_status' => $cpap_status,
            'cpap_sold_date_from' => $cpap_sold_date_from,
            'cpap_sold_date_to' => $cpap_sold_date_to,
            'cpap_sold_status' => $cpap_sold_status,
            'hsat_date_from' => $hsat_date_from,
            'hsat_date_to' => $hsat_date_to,
            'hsat_status' => $hsat_status,
            'oximetry_date_from' => $oximetry_date_from,
            'oximetry_date_to' => $oximetry_date_to,
            'oximetry_status' => $oximetry_status,
            'hsat_ri_date_from' => $hsat_ri_date_from,
            'hsat_ri_date_to' => $hsat_ri_date_to,
            'hsat_ri_status' => $hsat_ri_status,
            'cpap_eval_date_from' => $cpap_eval_date_from,
            'cpap_eval_date_to' => $cpap_eval_date_to,
            'cpap_eval_status' => $cpap_eval_status,
            'chart_type_cycle' => $chart_type_cycle,
            'clinician' => $clinician
        ));

        $page_title = 'Patient Progress Report';
        $content = $this->renderView('@RxConnexion/Report/PatientProgress/preview.wkpdf.twig', array(
            'page_title' => $page_title,
            'date_from' => $date_from,
            'date_to' => $date_to,
            'records' => $records,
            'summary' => $summary,
            'hsatExpNoOfDays' => $hsatChartType->getExpectedNoOfDays(),
        ));

        $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content, array(
            'orientation'=>'Landscape',
            'dpi' => 72,
            // 'disable-smart-shrinking',
            'zoom' => 'LINUX' == strtoupper(PHP_OS) ? 0.78 : 1
        ));

        $pdfResponse = array(
            'success' => true,
            'msg' => 'PDF was successfully generated.',
            'pdfBase64' => base64_encode($xml)
        );
        if($pdfResponse['success']) {
            $pdfContent = $pdfResponse['pdfBase64'];
            return new Response(base64_decode($pdfContent), 200, array(
                'Content-Type' => 'application/pdf',
                'Content-Disposition'   => 'attachment; filename="Patient Progress Report' . date('m/d/Y') . ' Details.pdf"'
            ));
        } else {
            $this->get('session')->getFlashBag()->set('error_messages', $pdfResponse['msg']);
            return $this->redirect($this->generateUrl('report_patient_progress', 302));
        }
    }

    /**
     * @Route(
     *      "/patient_progress/export_to_excel/{date_from}/{date_to}/{receive_date_from}/{receive_date_to}/{patient}/{company}/{branch}/{billingBranch}/{chartType}/{chartStatus}/{cpap_date_from}/{cpap_date_to}/{cpap_status}/{cpap_sold_date_from}/{cpap_sold_date_to}/{cpap_sold_status}/{hsat_date_from}/{hsat_date_to}/{hsat_status}/{hsat_mobile_date_from}/{hsat_mobile_date_to}/{hsat_mobile_status}/{oximetry_date_from}/{oximetry_date_to}/{oximetry_status}/{hsat_ri_date_from}/{hsat_ri_date_to}/{hsat_ri_status}/{cpap_eval_date_from}/{cpap_eval_date_to}/{cpap_eval_status}/{chart_type_cycle}/{clinician}/{booked}/{unbooked}",
     *      name = "report_patient_progress_export_to_excel"
     * )
     */
    public function report_patient_progress_export_to_excelAction($date_from, $date_to, $receive_date_from, $receive_date_to, $patient, $company, $branch, $billingBranch, $chartType, $chartStatus, $cpap_date_from, $cpap_date_to, $cpap_status, $cpap_sold_date_from, $cpap_sold_date_to, $cpap_sold_status, $hsat_date_from,$hsat_date_to,$hsat_status,$hsat_mobile_date_from,$hsat_mobile_date_to,$hsat_mobile_status,$oximetry_date_from,$oximetry_date_to,$oximetry_status,$hsat_ri_date_from,$hsat_ri_date_to,$hsat_ri_status,$cpap_eval_date_from,$cpap_eval_date_to,$cpap_eval_status,$chart_type_cycle,$clinician,$booked,$unbooked) {

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

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

        $phpExcelObject = $this->get('phpexcel')->createPHPExcelObject();
        $activeSheet = $phpExcelObject->setActiveSheetIndex(0);
        $activeSheet->setCellValue('A1', 'Patient Progress Report');

        $activeSheet->mergeCells('A1:AB1');
        $activeSheet->getStyle('A1:AB1')->applyFromArray(array(
            'fill' => array(
                'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                'color' => array('rgb' => 'ADD8E6')
            ),
        ));
        $activeSheet->getStyle('A1')->getFont()->setBold( true );

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

        $hsatChartType = $em->getRepository('RxConnexionBundle:ChartTypeEntity')->findOneBy(array(
            'description' => 'HSAT'
        ));

        $hsatExpNoOfDays = $hsatChartType->getExpectedNoOfDays();

        $records = $em->getRepository('RxConnexionBundle:ReferralEntity')->reportPatientProgress(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'receive_date_from' => $receive_date_from,
            'receive_date_to' => $receive_date_to,
            'patient' => $patient,
            'company' => $company,
            'branch' => $branch,
            'billingHealthFacility' => $billingBranch,
            'chartType' => $chartType,
            'chartStatus' => $chartStatus,
            'cpap_date_from' => $cpap_date_from,
            'cpap_date_to' => $cpap_date_to,
            'cpap_status' => $cpap_status,
            'cpap_sold_date_from' => $cpap_sold_date_from,
            'cpap_sold_date_to' => $cpap_sold_date_to,
            'cpap_sold_status' => $cpap_sold_status,
            'hsat_date_from' => $hsat_date_from,
            'hsat_date_to' => $hsat_date_to,
            'hsat_status' => $hsat_status,
            'hsat_mobile_date_from' => $hsat_mobile_date_from,
            'hsat_mobile_date_to' => $hsat_mobile_date_to,
            'hsat_mobile_status' => $hsat_mobile_status,
            'oximetry_date_from' => $oximetry_date_from,
            'oximetry_date_to' => $oximetry_date_to,
            'oximetry_status' => $oximetry_status,
            'hsat_ri_date_from' => $hsat_ri_date_from,
            'hsat_ri_date_to' => $hsat_ri_date_to,
            'hsat_ri_status' => $hsat_ri_status,
            'cpap_eval_date_from' => $cpap_eval_date_from,
            'cpap_eval_date_to' => $cpap_eval_date_to,
            'cpap_eval_status' => $cpap_eval_status,
            'chart_type_cycle' => $chart_type_cycle,
            'clinician' => $clinician,
            'booked' => $booked,
            'unbooked' => $unbooked,
        ));

        $summary = $em->getRepository('RxConnexionBundle:ReferralEntity')->reportPatientProgressSummary(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'receive_date_from' => $receive_date_from,
            'receive_date_to' => $receive_date_to,
            'patient' => $patient,
            'company' => $company,
            'branch' => $branch,
            'billingHealthFacility' => $billingBranch,
            'chartType' => $chartType,
            'chartStatus' => $chartStatus,
            'cpap_date_from' => $cpap_date_from,
            'cpap_date_to' => $cpap_date_to,
            'cpap_status' => $cpap_status,
            'cpap_sold_date_from' => $cpap_sold_date_from,
            'cpap_sold_date_to' => $cpap_sold_date_to,
            'cpap_sold_status' => $cpap_sold_status,
            'hsat_date_from' => $hsat_date_from,
            'hsat_date_to' => $hsat_date_to,
            'hsat_status' => $hsat_status,
            'hsat_mobile_date_from' => $hsat_mobile_date_from,
            'hsat_mobile_date_to' => $hsat_mobile_date_to,
            'hsat_mobile_status' => $hsat_mobile_status,
            'oximetry_date_from' => $oximetry_date_from,
            'oximetry_date_to' => $oximetry_date_to,
            'oximetry_status' => $oximetry_status,
            'hsat_ri_date_from' => $hsat_ri_date_from,
            'hsat_ri_date_to' => $hsat_ri_date_to,
            'hsat_ri_status' => $hsat_ri_status,
            'cpap_eval_date_from' => $cpap_eval_date_from,
            'cpap_eval_date_to' => $cpap_eval_date_to,
            'cpap_eval_status' => $cpap_eval_status,
            'clinician' => $clinician,
            'booked' => $booked,
            'unbooked' => $unbooked,
        ));

        $activeSheet->setCellValue('A3', 'Patient ID');
        $activeSheet->setCellValue('B3', 'Referral Date');
        $activeSheet->setCellValue('C3', 'Received Date');
        $activeSheet->setCellValue('D3', 'Patient');
        $activeSheet->setCellValue('E3', 'Patient Services');
        $activeSheet->setCellValue('F3', 'Previous Branch');
        $activeSheet->setCellValue('G3', 'Branch');
        $activeSheet->setCellValue('H3', 'Primary Clinician');
        $activeSheet->setCellValue('I3', 'Specialist Referral');
        $activeSheet->setCellValue('J3', 'HSAT Status');
        $activeSheet->setCellValue('K3', 'HSAT Interval');
        $activeSheet->setCellValue('L3', 'HSAT Date');
        $activeSheet->setCellValue('M3', 'HSAT Results Interpretation Status');
        $activeSheet->setCellValue('N3', 'HSAT Results Interpretation Interval');
        $activeSheet->setCellValue('O3', 'HSAT Results Interpretation Date');
        $activeSheet->setCellValue('P3', 'CPAP Setup Status');
        $activeSheet->setCellValue('Q3', 'CPAP Setup Interval');
        $activeSheet->setCellValue('R3', 'CPAP Setup Date');
        $activeSheet->setCellValue('S3', 'CPAP Setup Sold Status');
        $activeSheet->setCellValue('T3', 'CPAP Setup Sold Interval');
        $activeSheet->setCellValue('U3', 'CPAP Setup Sold Date');
        $activeSheet->setCellValue('V3', 'CPAP Eval');
        $activeSheet->setCellValue('W3', 'CPAP Eval Interval');
        $activeSheet->setCellValue('X3', 'CPAP Eval Date');
        $activeSheet->setCellValue('Y3', 'CPAP End Eval');
        $activeSheet->setCellValue('Z3', 'CPAP End Eval Interval');
        $activeSheet->setCellValue('AA3', 'CPAP End Eval Date');
        $activeSheet->setCellValue('AB3', 'Invoice No');
        $activeSheet->setCellValue('AC3', 'Billing Date');
        $activeSheet->getStyle('A3:AC3')->applyFromArray(array(
            'fill' => array(
                'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                'color' => array('rgb' => 'C3CFEF')
            ),
        ));
        $activeSheet->getStyle('A3:AA3')->getFont()->setBold( true );

        $rowCtr = 4;
        $totalCount = 0;
        $threeDayCtr = 0;
        $twoDayCtr = 0;
        $oneDayCtr = 0;

        foreach($records['patientProgress'] as $record) {

            $rowCtr++;
            $totalCount++;

            $x = $hsatExpNoOfDays ? $hsatExpNoOfDays : 0;
            $refferalToHsat = date('m/d/Y', strtotime($record['referralDate'].' + '.$x.' days'));

            if ($record['hsatChartDate'] == '') {
                if(date('m/d/Y', strtotime(date("m/d/Y"). ' + 3 days')) == $refferalToHsat) {
                    $threeDayCtr = $threeDayCtr + 1;
                    $styleArray = array(
                        'font'  => array(
                            'color' => array('rgb' => 'B4C200'),
                        ));

                    $activeSheet->getStyle('D'.$rowCtr)->applyFromArray($styleArray);
                } else if(date('m/d/Y', strtotime(date("m/d/Y"). ' + 2 days')) == $refferalToHsat) {
                    $twoDayCtr = $twoDayCtr + 1;
                    $styleArray = array(
                        'font'  => array(
                            'color' => array('rgb' => 'FFA500'),
                        ));

                    $activeSheet->getStyle('D'.$rowCtr)->applyFromArray($styleArray);
                } else if(date('m/d/Y', strtotime(date("m/d/Y"). ' + 1 days')) >= $refferalToHsat) {
                    $oneDayCtr = $oneDayCtr + 1;
                    $styleArray = array(
                        'font'  => array(
                            'color' => array('rgb' => 'FF0000'),
                        ));

                    $activeSheet->getStyle('D'.$rowCtr)->applyFromArray($styleArray);
                }
            }
            $explodedPs = explode(',', $record['patientServices']);
            $activeSheet->setCellValue('A'.$rowCtr, $record['patientId']);
            $activeSheet->setCellValue('B'.$rowCtr, $record['referralDate']);
            $activeSheet->setCellValue('C'.$rowCtr, $record['receivedDate']);
            $activeSheet->setCellValue('D'.$rowCtr, $record['patientName']);
            foreach ($explodedPs as $ps) {
                $patientService = explode('|', $ps);
                $activeSheet->setCellValue('E'.$rowCtr, isset($patientService[1]) ? $patientService[1] : '');
                $rowCtr++;
            }
            $activeSheet->setCellValue('F'.$rowCtr, $record['prevBranchDesc']);
            $activeSheet->setCellValue('G'.$rowCtr, $record['branchDesc']);
            $activeSheet->setCellValue('H'.$rowCtr, $record['primaryProvider']);
            $activeSheet->setCellValue('I'.$rowCtr, $record['specialistFullName']);
            $activeSheet->setCellValue('J'.$rowCtr, $record['hsatStatusDesc']);
            $activeSheet->setCellValue('K'.$rowCtr, $record['hsatTimeDiff']);
            $activeSheet->setCellValue('L'.$rowCtr, $record['hsatChartDate']);
            $activeSheet->setCellValue('M'.$rowCtr, $record['hsatResultInterStatusDesc']);
            $activeSheet->setCellValue('N'.$rowCtr, $record['hsatInterTimeDiff']);
            $activeSheet->setCellValue('O'.$rowCtr, $record['hsatResultInterChartDate']);
            $activeSheet->setCellValue('P'.$rowCtr, $record['cpapSetupStatusDesc']);
            $activeSheet->setCellValue('Q'.$rowCtr, $record['cpapSetupTimeDiff']);
            $activeSheet->setCellValue('R'.$rowCtr, $record['cpapSetupChartDate']);
            $activeSheet->setCellValue('S'.$rowCtr, $record['cpapSetupSoldStatusDesc']);
            $activeSheet->setCellValue('T'.$rowCtr, $record['cpapSetupSoldTimeDiff']);
            $activeSheet->setCellValue('U'.$rowCtr, $record['cpapSetupSold']);
            $activeSheet->setCellValue('V'.$rowCtr, $record['cpapEvalStatusDesc']);
            $activeSheet->setCellValue('W'.$rowCtr, $record['cpapEvalTimeDiff']);
            $activeSheet->setCellValue('X'.$rowCtr, $record['cpapEvalChartDate']);
            $activeSheet->setCellValue('Y'.$rowCtr, $record['cpapEndEvalStatusDesc']);
            $activeSheet->setCellValue('Z'.$rowCtr, $record['cpapEndEvalTimeDiff']);
            $activeSheet->setCellValue('AA'.$rowCtr, $record['cpapEndEvalChartDate']);
            $activeSheet->setCellValue('AB'.$rowCtr, $record['invoice_no']);
            $activeSheet->setCellValue('AC'.$rowCtr, $record['billingDate']);

        }

        $rowCtr++;
        $activeSheet->setCellValue('A'.$rowCtr, 'Total Records: '.$totalCount);


        $rowCtr++;
        $rowCtr++;

        $activeSheet->setCellValue('A'.$rowCtr, 'Booked Summary')->getStyle( 'A'.$rowCtr )->getFont()->setBold( true );
        $activeSheet->getStyle('A'.$rowCtr)->applyFromArray(array(
            'fill' => array(
                'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                'color' => array('rgb' => 'ADD8E6')
            ),
            'borders' => array(
                'allborders' => array(
                    'style' => \PHPExcel_Style_Border::BORDER_THIN
                )
            )
        ));

        $rowCtr++;
        $activeSheet->setCellValue('A'.$rowCtr, 'Encounter Type')->getStyle( 'A'.$rowCtr )->getFont()->setBold( true );
        $activeSheet->setCellValue('B'.$rowCtr, 'Count')->getStyle( 'B'.$rowCtr )->getFont()->setBold( true );
        $activeSheet->getStyle('A'.$rowCtr.':B'.$rowCtr)->applyFromArray(array(
            'fill' => array(
                'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                'color' => array('rgb' => 'ADD8E6')
            ),
            'borders' => array(
                'allborders' => array(
                    'style' => \PHPExcel_Style_Border::BORDER_THIN
                )
            )
        ));

        $rowCtr++;
        $activeSheet->setCellValue('A'.$rowCtr, 'HSAT')->getStyle( 'A'.$rowCtr )->getFont()->setBold( true );
        $activeSheet->setCellValue('B'.$rowCtr, $summary['booked']['hsatCount']);

        $rowCtr++;
        $activeSheet->setCellValue('A'.$rowCtr, 'HSAT (Mobile)')->getStyle( 'A'.$rowCtr )->getFont()->setBold( true );
        $activeSheet->setCellValue('B'.$rowCtr, $summary['booked']['hsatMobileCount']);

        $rowCtr++;
        $activeSheet->setCellValue('A'.$rowCtr, 'HSAT Results Interpretation')->getStyle( 'A'.$rowCtr )->getFont()->setBold( true );
        $activeSheet->setCellValue('B'.$rowCtr, $summary['booked']['hsatResultInterCount']);

        $rowCtr++;
        $activeSheet->setCellValue('A'.$rowCtr, 'CPAP Setup')->getStyle( 'A'.$rowCtr )->getFont()->setBold( true );
        $activeSheet->setCellValue('B'.$rowCtr, $summary['booked']['cpapSetupCount']);

        $rowCtr++;
        $activeSheet->setCellValue('A'.$rowCtr, 'CPAP Eval')->getStyle( 'A'.$rowCtr )->getFont()->setBold( true );
        $activeSheet->setCellValue('B'.$rowCtr, $summary['booked']['cpapEvalCount']);

        $rowCtr++;
        $activeSheet->setCellValue('A'.$rowCtr, 'CPAP End Eval')->getStyle( 'A'.$rowCtr )->getFont()->setBold( true );
        $activeSheet->setCellValue('B'.$rowCtr, $summary['booked']['cpapEndEvalCount']);

        $rowCtr++;
        $activeSheet->setCellValue('A'.$rowCtr, 'CPAP Setup Sold')->getStyle( 'A'.$rowCtr )->getFont()->setBold( true );
        $activeSheet->setCellValue('B'.$rowCtr, $summary['booked']['cpapSetupSoldCount']);

        $rowCtr++;
        $activeSheet->setCellValue('A'.$rowCtr, 'Invoices')->getStyle( 'A'.$rowCtr )->getFont()->setBold( true );
        $activeSheet->setCellValue('B'.$rowCtr, $summary['booked']['invoicesCount']);


        $rowCtr = $rowCtr - 8;
        //UNBOOKED
        $activeSheet->setCellValue('D'.$rowCtr, 'Unbooked Summary')->getStyle( 'D'.$rowCtr )->getFont()->setBold( true );
        $activeSheet->getStyle('D'.$rowCtr)->applyFromArray(array(
            'fill' => array(
                'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                'color' => array('rgb' => 'ADD8E6')
            ),
            'borders' => array(
                'allborders' => array(
                    'style' => \PHPExcel_Style_Border::BORDER_THIN
                )
            )
        ));
        $rowCtr++;
        $activeSheet->setCellValue('D'.$rowCtr, 'Encounter Type')->getStyle( 'D'.$rowCtr )->getFont()->setBold( true );
        $activeSheet->setCellValue('E'.$rowCtr, 'Count')->getStyle( 'E'.$rowCtr )->getFont()->setBold( true );
        $activeSheet->getStyle('D'.$rowCtr.':E'.$rowCtr)->applyFromArray(array(
            'fill' => array(
                'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                'color' => array('rgb' => 'ADD8E6')
            ),
            'borders' => array(
                'allborders' => array(
                    'style' => \PHPExcel_Style_Border::BORDER_THIN
                )
            )
        ));

        $rowCtr++;
        $activeSheet->setCellValue('D'.$rowCtr, 'HSAT')->getStyle( 'D'.$rowCtr )->getFont()->setBold( true );
        $activeSheet->setCellValue('E'.$rowCtr, $summary['unbooked']['hsatCount']);

        $rowCtr++;
        $activeSheet->setCellValue('D'.$rowCtr, 'HSAT (Mobile)')->getStyle( 'D'.$rowCtr )->getFont()->setBold( true );
        $activeSheet->setCellValue('E'.$rowCtr, $summary['unbooked']['hsatMobileCount']);

        $rowCtr++;
        $activeSheet->setCellValue('D'.$rowCtr, 'HSAT Results Interpretation')->getStyle( 'D'.$rowCtr )->getFont()->setBold( true );
        $activeSheet->setCellValue('E'.$rowCtr, $summary['unbooked']['hsatResultInterCount']);

        $rowCtr++;
        $activeSheet->setCellValue('D'.$rowCtr, 'CPAP Setup')->getStyle( 'D'.$rowCtr )->getFont()->setBold( true );
        $activeSheet->setCellValue('E'.$rowCtr, $summary['unbooked']['cpapSetupCount']);

        $rowCtr++;
        $activeSheet->setCellValue('D'.$rowCtr, 'CPAP Eval')->getStyle( 'D'.$rowCtr )->getFont()->setBold( true );
        $activeSheet->setCellValue('E'.$rowCtr, $summary['unbooked']['cpapEvalCount']);

        $rowCtr++;
        $activeSheet->setCellValue('D'.$rowCtr, 'CPAP End Eval')->getStyle( 'D'.$rowCtr )->getFont()->setBold( true );
        $activeSheet->setCellValue('E'.$rowCtr, $summary['unbooked']['cpapEndEvalCount']);

        $rowCtr++;
        $activeSheet->setCellValue('D'.$rowCtr, 'CPAP Setup Sold')->getStyle( 'D'.$rowCtr )->getFont()->setBold( true );
        $activeSheet->setCellValue('E'.$rowCtr, $summary['unbooked']['cpapSetupSoldCount']);

        $rowCtr++;
        $activeSheet->setCellValue('D'.$rowCtr, 'Invoices')->getStyle( 'D'.$rowCtr )->getFont()->setBold( true );
        $activeSheet->setCellValue('E'.$rowCtr, $summary['unbooked']['invoicesCount']);

//        $rowCtr = $rowCtr - 8;
//        //REFERRAL BRANCH
//        $activeSheet->setCellValue('D'.$rowCtr, 'Total Number of Referrals by Branch')->getStyle( 'D'.$rowCtr )->getFont()->setBold( true );
//        $activeSheet->getStyle('D'.$rowCtr)->applyFromArray(array(
//            'fill' => array(
//                'type' => \PHPExcel_Style_Fill::FILL_SOLID,
//                'color' => array('rgb' => 'ADD8E6')
//            ),
//            'borders' => array(
//                'allborders' => array(
//                    'style' => \PHPExcel_Style_Border::BORDER_THIN
//                )
//            )
//        ));
//        $rowCtr++;
//        $activeSheet->setCellValue('D'.$rowCtr, 'Branch')->getStyle( 'D'.$rowCtr )->getFont()->setBold( true );
//        $activeSheet->setCellValue('E'.$rowCtr, 'Count')->getStyle( 'E'.$rowCtr )->getFont()->setBold( true );
//        $activeSheet->getStyle('D'.$rowCtr.':E'.$rowCtr)->applyFromArray(array(
//            'fill' => array(
//                'type' => \PHPExcel_Style_Fill::FILL_SOLID,
//                'color' => array('rgb' => 'ADD8E6')
//            ),
//            'borders' => array(
//                'allborders' => array(
//                    'style' => \PHPExcel_Style_Border::BORDER_THIN
//                )
//            )
//        ));
//
//        $rowCtr++;
//
//        foreach($summary['branch'] as $summaryBranch) {
//            $rowCtr++;
//            $activeSheet->setCellValue('D'.$rowCtr, $summaryBranch['branchDesc'])->getStyle( 'D'.$rowCtr )->getFont()->setBold( true );
//            $activeSheet->setCellValue('E'.$rowCtr, $summaryBranch['branchCount']);
//        }



        $page_title = 'Patient Progress Report';
        $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;
    }

    //Payment Report
    /**
     * @Route("/report_payment", name="report_payment")
     */
    public function paymentReportAction() {

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

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

        $em = $this->getDoctrine()->getManager();
        $company = $em->getRepository('RxConnexionBundle:CompanyEntity')->companiesForMultiple($userData);
        $financingCompany = $em->getRepository('RxConnexionBundle:FinancingCompanyEntity')->financingCompanyForMultiple();
        $branch = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->branchesForBillingMultiple($userData);

        $page_title = 'Payment Report';
        return $this->render('@RxConnexion/Report/Payment/index.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'company' => $company,
            'branch' => $branch,
            'financingCompany' => $financingCompany,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/payment/payment.js?v=1.0.2')
        ));
    }

    /**
     * @Route(
     *      "/report_payment/preview/{date_from}/{date_to}/{patient}/{company}/{branch}/{branchAddress}/{paymentType}/{paymentStatus}/{financingCompany}",
     *      name = "report_payment_preview"
     * )
     */
    public function report_payment_previewAction($date_from, $date_to, $patient, $company, $branch, $branchAddress, $paymentType, $paymentStatus, $financingCompany) {

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

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientPaymentEntity')->reportPayment(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'patient' => $patient,
            'company' => $company,
            'branch' => $branch,
            'branchAddress' => $branchAddress,
            'paymentType' => $paymentType,
            'paymentStatus' => $paymentStatus,
            'financingCompany' => $financingCompany,
            'userData' => $userData
        ));

        $page_title = 'Payment Report';
        return $this->render('@RxConnexion/Report/Payment/preview.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'javascripts' => array('rxconnexion/admin/js/report/report_preview.js'),
            'records' => $records,
        ));
    }

    /**
     * @Route(
     *      "/report_payment/export_to_pdf/{date_from}/{date_to}/{patient}/{company}/{branch}/{branchAddress}/{paymentType}/{paymentStatus}/{financingCompany}",
     *      name = "report_payment_export_to_pdf"
     * )
     */
    public function report_payment_export_to_pdfAction($date_from, $date_to, $patient, $company, $branch, $branchAddress, $paymentType, $paymentStatus, $financingCompany) {

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

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientPaymentEntity')->reportPayment(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'patient' => $patient,
            'company' => $company,
            'branch' => $branch,
            'branchAddress' => $branchAddress,
            'paymentType' => $paymentType,
            'paymentStatus' => $paymentStatus,
            'financingCompany' => $financingCompany,
            'userData' => $userData
        ));

        $page_title = 'Payment Report';
        $content = $this->renderView('@RxConnexion/Report/Payment/preview.wkpdf.twig', array(
            'page_title' => $page_title,
            'records' => $records
        ));

        $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content, array(
            'orientation'=>'Landscape',
            'dpi' => 72,
            // 'disable-smart-shrinking',
            'zoom' => 'LINUX' == strtoupper(PHP_OS) ? 0.78 : 1
        ));

        $pdfResponse = array(
            'success' => true,
            'msg' => 'PDF was successfully generated.',
            'pdfBase64' => base64_encode($xml)
        );
        if($pdfResponse['success']) {
            $pdfContent = $pdfResponse['pdfBase64'];
            return new Response(base64_decode($pdfContent), 200, array(
                'Content-Type' => 'application/pdf',
                'Content-Disposition'   => 'attachment; filename="Payment Report' . date('m/d/Y') . ' Details.pdf"'
            ));
        } else {
            $this->get('session')->getFlashBag()->set('error_messages', $pdfResponse['msg']);
            return $this->redirect($this->generateUrl('report_payment', 302));
        }
    }

    /**
     * @Route(
     *      "/report_payment/export_to_excel/{date_from}/{date_to}/{patient}/{company}/{branch}/{branchAddress}/{paymentType}/{paymentStatus}/{financingCompany}",
     *      name = "report_payment_export_to_excel"
     * )
     */
    public function report_payment_export_to_excelAction($date_from, $date_to, $patient, $company, $branch, $branchAddress, $paymentType, $paymentStatus, $financingCompany) {

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

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientPaymentEntity')->reportPayment(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'patient' => $patient,
            'company' => $company,
            'branch' => $branch,
            'branchAddress' => $branchAddress,
            'paymentType' => $paymentType,
            'paymentStatus' => $paymentStatus,
            'financingCompany' => $financingCompany,
            'userData' => $userData
        ));

        $columnRange = range('A', 'Z');
        $cellsData = array(
            array('cell' => 'A1', 'data' => 'Payment Type'),
            array('cell' => 'B1', 'data' => 'Patient'),
            array('cell' => 'C1', 'data' => 'Invoice No.'),
            array('cell' => 'D1', 'data' => 'Billing Address'),
            array('cell' => 'E1', 'data' => 'Billing Branch'),
            array('cell' => 'F1', 'data' => 'Financing Company'),
            array('cell' => 'G1', 'data' => 'Pay Date'),
            array('cell' => 'H1', 'data' => 'Amount'),
            array('cell' => 'I1', 'data' => 'Status'),
            array('cell' => 'J1', 'data' => 'Note'),
        );
        $rowCtr = 1;
        $totalCount = 0;
        $totalAmt = 0;
        foreach($records['payment'] as $record) {
            $totalAmt = $totalAmt + $record['amount'];
            $rowCtr++;
            $totalCount++;

            $cellsData[] = array('cell' => "A$rowCtr", 'data' => $record['pay_type']);
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => $record['patientName']);
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => $record['invoiceNo']);
            $cellsData[] = array('cell' => "D$rowCtr", 'data' => $record['branchAddress']);
            $cellsData[] = array('cell' => "E$rowCtr", 'data' => $record['billingBranch']);
            $cellsData[] = array('cell' => "F$rowCtr", 'data' => $record['financingCompany']);
            $cellsData[] = array('cell' => "G$rowCtr", 'data' => $record['pay_date']);
            $cellsData[] = array('cell' => "H$rowCtr", 'data' => $record['amount']);
            $cellsData[] = array('cell' => "I$rowCtr", 'data' => $record['payment_status']);
            $cellsData[] = array('cell' => "J$rowCtr", 'data' => $record['note']);
        }

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


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

        $rowCtr++;
        $rowCtr++;
        $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Billing Branch');
        $cellsData[] = array('cell' => "B$rowCtr", 'data' => 'Transaction Count');
        $cellsData[] = array('cell' => "C$rowCtr", 'data' => 'Total Amount');

        $totalTransacSummary = 0;
        $totalAmtSummary = 0;
        foreach($records['summary'] as $record) {
            $totalTransacSummary = $totalTransacSummary + $record['transactionCount'];
            $totalAmtSummary = $totalAmtSummary + $record['totalAmt'];
            $rowCtr++;
            $totalCount++;

            $cellsData[] = array('cell' => "A$rowCtr", 'data' => $record['billingBranch']);
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => $record['transactionCount']);
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => $record['totalAmt']);
        }
        $rowCtr++;
        $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Total:');
        $cellsData[] = array('cell' => "B$rowCtr", 'data' => $totalTransacSummary);
        $cellsData[] = array('cell' => "C$rowCtr", 'data' => $totalAmtSummary);

        $rowCtr++;
        $rowCtr++;
        $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Payment Type');
        $cellsData[] = array('cell' => "B$rowCtr", 'data' => 'Transaction Count');
        $cellsData[] = array('cell' => "C$rowCtr", 'data' => 'Total Amount');


        $breakdown_totalTransacSummary = 0;
        $breakdown_totalAmtSummary = 0;
        foreach($records['breakdown'] as $record) {
            $breakdown_totalTransacSummary = $breakdown_totalTransacSummary + $record['transactionCount'];
            $breakdown_totalAmtSummary = $breakdown_totalAmtSummary + $record['totalAmt'];
            $rowCtr++;
            $totalCount++;

            $cellsData[] = array('cell' => "A$rowCtr", 'data' => $record['paymentType']);
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => $record['transactionCount']);
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => $record['totalAmt']);
        }
        $rowCtr++;
        $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Total:');
        $cellsData[] = array('cell' => "B$rowCtr", 'data' => $breakdown_totalTransacSummary);
        $cellsData[] = array('cell' => "C$rowCtr", 'data' => $breakdown_totalAmtSummary);

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

    //Refund Report
    /**
     * @Route("/report_refund", name="report_refund")
     */
    public function refundReportAction() {

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

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

        $em = $this->getDoctrine()->getManager();
        $company = $em->getRepository('RxConnexionBundle:CompanyEntity')->companiesForMultiple($userData);
        $financingCompany = $em->getRepository('RxConnexionBundle:FinancingCompanyEntity')->financingCompanyForMultiple();
        $branch = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->branchesForBillingMultiple($userData);

        $page_title = 'Billing Refund Report';
        return $this->render('@RxConnexion/Report/Refund/index.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'company' => $company,
            'branch' => $branch,
            'financingCompany' => $financingCompany,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/refund/refund.js?v=1.0.2')
        ));
    }

    /**
     * @Route(
     *      "/report_refund/preview/{date_from}/{date_to}/{company}/{branch}/{patient}",
     *      name = "report_refund_preview"
     * )
     */
    public function report_refund_previewAction($date_from, $date_to, $company, $branch, $patient) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Billing Refund Preview'))) return $authService->redirectToHome();

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientBillingRefundEntity')->reportRefund(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company,
            'branch' => $branch,
            'patient' => $patient,
            'userData' => $userData
        ));

        $page_title = 'Billing Refund Report';
        return $this->render('@RxConnexion/Report/Refund/preview.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'javascripts' => array('rxconnexion/admin/js/report/report_preview.js'),
            'records' => $records,
        ));
    }

    /**
     * @Route(
     *      "/report_refund/export_to_pdf/{date_from}/{date_to}/{company}/{branch}/{patient}",
     *      name = "report_refund_export_to_pdf"
     * )
     */
    public function report_refund_export_to_pdfAction($date_from, $date_to, $company, $branch, $patient) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Billing Refund Pdf'))) return $authService->redirectToHome();

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientBillingRefundEntity')->reportRefund(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company,
            'branch' => $branch,
            'patient' => $patient,
            'userData' => $userData
        ));

        $page_title = 'Billing Refund Report';
        $content = $this->renderView('@RxConnexion/Report/Refund/preview.wkpdf.twig', array(
            'page_title' => $page_title,
            'records' => $records
        ));

        $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content, array(
            'orientation'=>'Landscape',
            'dpi' => 72,
            // 'disable-smart-shrinking',
            'zoom' => 'LINUX' == strtoupper(PHP_OS) ? 0.78 : 1
        ));

        $pdfResponse = array(
            'success' => true,
            'msg' => 'PDF was successfully generated.',
            'pdfBase64' => base64_encode($xml)
        );
        if($pdfResponse['success']) {
            $pdfContent = $pdfResponse['pdfBase64'];
            return new Response(base64_decode($pdfContent), 200, array(
                'Content-Type' => 'application/pdf',
                'Content-Disposition'   => 'attachment; filename="Billing Refund Report' . date('m/d/Y') . ' Details.pdf"'
            ));
        } else {
            $this->get('session')->getFlashBag()->set('error_messages', $pdfResponse['msg']);
            return $this->redirect($this->generateUrl('report_payment', 302));
        }
    }

    /**
     * @Route(
     *      "/report_refund/export_to_excel/{date_from}/{date_to}/{company}/{branch}/{patient}",
     *      name = "report_refund_export_to_excel"
     * )
     */
    public function report_refund_export_to_excelAction($date_from, $date_to, $company, $branch, $patient) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Billing Refund Excel'))) return $authService->redirectToHome();

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientBillingRefundEntity')->reportRefund(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company,
            'branch' => $branch,
            'patient' => $patient,
            'userData' => $userData
        ));

        $columnRange = range('A', 'Z');
        $cellsData = array(
            array('cell' => 'A1', 'data' => 'Invoice No.'),
            array('cell' => 'B1', 'data' => 'Refund Date'),
            array('cell' => 'C1', 'data' => 'Patient'),
            array('cell' => 'D1', 'data' => 'Billing Branch'),
            array('cell' => 'E1', 'data' => 'Billing Address'),
            array('cell' => 'F1', 'data' => 'Amount Due'),
            array('cell' => 'G1', 'data' => 'Amount Paid'),
            array('cell' => 'H1', 'data' => 'Amount Balance'),
            array('cell' => 'I1', 'data' => 'Amount Refunded'),
            array('cell' => 'J1', 'data' => 'Note'),
        );
        $rowCtr = 1;
        $totalCount = 0;

        foreach($records as $record) {

            $rowCtr++;
            $totalCount++;

            $cellsData[] = array('cell' => "A$rowCtr", 'data' => $record['invoiceNo']);
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => $record['refundDate']);
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => $record['patientName']);
            $cellsData[] = array('cell' => "D$rowCtr", 'data' => $record['healthFacility']);
            $cellsData[] = array('cell' => "E$rowCtr", 'data' => $record['healthFacilityAddress']);
            $cellsData[] = array('cell' => "F$rowCtr", 'data' => $record['amountDue']);
            $cellsData[] = array('cell' => "G$rowCtr", 'data' => $record['amountPaid']);
            $cellsData[] = array('cell' => "H$rowCtr", 'data' => $record['amountBalance']);
            $cellsData[] = array('cell' => "I$rowCtr", 'data' => $record['amountRefund']);
            $cellsData[] = array('cell' => "J$rowCtr", 'data' => $record['note']);
        }

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

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

    //Payment Without Invoice Report
    /**
     * @Route("/report_payment_without_invoice", name="report_payment_without_invoice")
     */
    public function payment_without_invoiceAction() {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Payment Without Invoice'))) return $authService->redirectToHome();

        $page_title = 'Payment Without Invoice Report';
        return $this->render('@RxConnexion/Report/PaymentWithoutInvoice/index.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/payment_without_invoice/payment_without_invoice.js')
        ));
    }

    /**
     * @Route(
     *      "/report_payment_without_invoice/preview/{date_from}/{date_to}/{company_id}/{branch_id}/{patient}",
     *      name = "report_payment_without_invoice_preview"
     * )
     */
    public function payment_without_invoice_previewAction($date_from, $date_to, $company_id, $branch_id, $patient) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Payment Without Invoice Preview'))) return $authService->redirectToHome();

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientPaymentEntity')->reportPaymentWithoutInvoice(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company_id,
            'branch' => $branch_id,
            'patient' => $patient,
            'userData' => $userData
        ));

        $page_title = 'Payment Without Invoice Report';
        return $this->render('@RxConnexion/Report/PaymentWithoutInvoice/preview.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'javascripts' => array('rxconnexion/admin/js/report/report_preview.js'),
            'records' => $records,
        ));
    }

    /**
     * @Route(
     *      "/report_payment_without_invoice/export_to_pdf/{date_from}/{date_to}/{company_id}/{branch_id}/{patient}",
     *      name = "report_payment_without_invoice_export_to_pdf"
     * )
     */
    public function payment_without_invoice_export_to_pdfAction($date_from, $date_to, $company_id, $branch_id, $patient) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Payment Without Invoice Pdf'))) return $authService->redirectToHome();

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientPaymentEntity')->reportPaymentWithoutInvoice(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company_id,
            'branch' => $branch_id,
            'patient' => $patient,
            'userData' => $userData
        ));

        $page_title = 'Payment Without Invoice Report';
        $content = $this->renderView('@RxConnexion/Report/PaymentWithoutInvoice/preview.wkpdf.twig', array(
            'page_title' => $page_title,
            'records' => $records
        ));

        $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content, array(
            'orientation'=>'Landscape',
            'dpi' => 72,
            // 'disable-smart-shrinking',
            'zoom' => 'LINUX' == strtoupper(PHP_OS) ? 0.78 : 1
        ));

        $pdfResponse = array(
            'success' => true,
            'msg' => 'PDF was successfully generated.',
            'pdfBase64' => base64_encode($xml)
        );
        if($pdfResponse['success']) {
            $pdfContent = $pdfResponse['pdfBase64'];
            return new Response(base64_decode($pdfContent), 200, array(
                'Content-Type' => 'application/pdf',
                //'Content-Disposition'   => 'attachment; filename="Payment Without Invoice Report' . date('m/d/Y') . ' Details.pdf"'
            ));
        } else {
            $this->get('session')->getFlashBag()->set('error_messages', $pdfResponse['msg']);
            return $this->redirect($this->generateUrl('report_payment_without_invoice', 302));
        }
    }

    /**
     * @Route(
     *      "/report_payment_without_invoice/export_to_excel/{date_from}/{date_to}/{company_id}/{branch_id}/{patient}",
     *      name = "report_payment_without_invoice_export_to_excel"
     * )
     */
    public function payment_without_invoice_export_to_excelAction($date_from, $date_to, $company_id, $branch_id, $patient) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Payment Without Invoice Excel'))) return $authService->redirectToHome();

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientPaymentEntity')->reportPaymentWithoutInvoice(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company_id,
            'branch' => $branch_id,
            'patient' => $patient,
            'userData' => $userData
        ));

        $columnRange = range('A', 'Z');
        $cellsData = array(
            array('cell' => 'A1', 'data' => 'Previous System Invoice No.'),
            array('cell' => 'B1', 'data' => 'Previous System Invoice Branch'),
            array('cell' => 'C1', 'data' => 'Payment Type'),
            array('cell' => 'D1', 'data' => 'Company'),
            array('cell' => 'E1', 'data' => 'Branch'),
            array('cell' => 'F1', 'data' => 'Patient'),
            array('cell' => 'G1', 'data' => 'Pay Date'),
            array('cell' => 'H1', 'data' => 'Amount'),
            array('cell' => 'I1', 'data' => 'Status'),
            array('cell' => 'J1', 'data' => 'Note'),
        );
        $rowCtr = 1;
        $totalCount = 0;
        $totalAmount = 0;

        foreach($records as $record) {

            $rowCtr++;
            $totalCount++;
            $totalAmount+=$record['amount'];

            $cellsData[] = array('cell' => "A$rowCtr", 'data' => $record['prev_sys_invoice_no']);
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => $record['prev_sys_invoice_branch']);
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => $record['pay_type']);
            $cellsData[] = array('cell' => "D$rowCtr", 'data' => $record['companyDesc']);
            $cellsData[] = array('cell' => "E$rowCtr", 'data' => $record['branchDesc']);
            $cellsData[] = array('cell' => "F$rowCtr", 'data' => $record['patientName']);
            $cellsData[] = array('cell' => "G$rowCtr", 'data' => $record['pay_date']);
            $cellsData[] = array('cell' => "H$rowCtr", 'data' => $record['amount']);
            $cellsData[] = array('cell' => "I$rowCtr", 'data' => $record['payment_status']);
            $cellsData[] = array('cell' => "J$rowCtr", 'data' => $record['note']);
        }

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


        $page_title = 'Payment Without Invoice Report';
        return $this->export_to_excel($columnRange, $cellsData, $page_title);
    }


    //AR Summary Report
    /**
     * @Route("/report_ar_summary", name="report_ar_summary")
     */
    public function ar_summary_ReportAction() {

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

        $session = $this->get('session');
        $userData = $session->get('userData');
        $em = $this->getDoctrine()->getManager();
        $company = $em->getRepository('RxConnexionBundle:CompanyEntity')->companiesForMultiple($userData);
        $branch = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->branchesForBillingMultiple($userData);

        $page_title = 'AR Summary Report';
        return $this->render('@RxConnexion/Report/ARSummary/index.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'company' => $company,
            'branch' => $branch,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/ar_summary/ar_summary.js?v=1.0.2')
        ));
    }

    /**
     * @Route(
     *      "/report_ar_summary/preview/{date_from}/{date_to}/{payerType}/{patient}/{branch}/{branch_address}/{company}",
     *      name = "report_ar_summary_preview"
     * )
     */
    public function report_ar_summary_previewAction($date_from, $date_to, $payerType, $patient, $branch, $branch_address, $company) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report AR Summary Preview'))) return $authService->redirectToHome();

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientBillingEntity')->reportARSummary(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'payerType' => $payerType,
            'patient' => $patient,
            'branch' => $branch,
            'branch_address' => $branch_address,
            'company' => $company,
            'userData' => $userData,
        ));

        $records2 = $em->getRepository('RxConnexionBundle:PatientBillingEntity')->reportARHealthFacilitySummary(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'payerType' => $payerType,
            'patient' => $patient,
            'branch' => $branch,
            'branch_address' => $branch_address,
            'company' => $company,
            'userData' => $userData,
        ));

        $page_title = 'AR Summary Report';
        return $this->render('@RxConnexion/Report/ARSummary/preview.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'javascripts' => array('rxconnexion/admin/js/report/report_preview.js'),
            'records' => $records,
            'records2' => $records2,
        ));
    }

    /**
     * @Route(
     *      "/report_ar_summary/export_to_pdf/{date_from}/{date_to}/{payerType}/{patient}/{branch}/{branch_address}/{company}",
     *      name = "report_ar_summary_export_to_pdf"
     * )
     */
    public function report_ar_summary_export_to_pdfAction($date_from, $date_to, $payerType, $patient, $branch, $branch_address, $company) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report AR Summary Pdf'))) return $authService->redirectToHome();

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientBillingEntity')->reportARSummary(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'payerType' => $payerType,
            'patient' => $patient,
            'branch' => $branch,
            'branch_address' => $branch_address,
            'company' => $company,
            'userData' => $userData,
        ));

        $records2 = $em->getRepository('RxConnexionBundle:PatientBillingEntity')->reportARHealthFacilitySummary(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'payerType' => $payerType,
            'patient' => $patient,
            'branch' => $branch,
            'branch_address' => $branch_address,
            'company' => $company,
            'userData' => $userData,
        ));

        $page_title = 'Payment Report';
        $content = $this->renderView('@RxConnexion/Report/ARSummary/preview.wkpdf.twig', array(
            'page_title' => $page_title,
            'records' => $records,
            'records2' => $records2
        ));

        $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content, array(
            'orientation'=>'Landscape',
            'dpi' => 72,
            // 'disable-smart-shrinking',
            'zoom' => 'LINUX' == strtoupper(PHP_OS) ? 0.78 : 1
        ));

        $pdfResponse = array(
            'success' => true,
            'msg' => 'PDF was successfully generated.',
            'pdfBase64' => base64_encode($xml)
        );
        if($pdfResponse['success']) {
            $pdfContent = $pdfResponse['pdfBase64'];
            return new Response(base64_decode($pdfContent), 200, array(
                'Content-Type' => 'application/pdf',
                'Content-Disposition'   => 'attachment; filename="AR Summary Report' . date('m/d/Y') . ' Details.pdf"'
            ));
        } else {
            $this->get('session')->getFlashBag()->set('error_messages', $pdfResponse['msg']);
            return $this->redirect($this->generateUrl('report_ar_summary', 302));
        }
    }

    /**
     * @Route(
     *      "/report_ar_summary/export_to_excel/{date_from}/{date_to}/{payerType}/{patient}/{branch}/{branch_address}/{company}",
     *      name = "report_ar_summary_export_to_excel"
     * )
     */
    public function report_ar_summary_export_to_excelAction($date_from, $date_to, $payerType, $patient, $branch, $branch_address, $company) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report AR Summary Excel'))) return $authService->redirectToHome();

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientBillingEntity')->reportARSummary(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'payerType' => $payerType,
            'patient' => $patient,
            'branch' => $branch,
            'branch_address' => $branch_address,
            'company' => $company,
            'userData' => $userData,
        ));

        $records2 = $em->getRepository('RxConnexionBundle:PatientBillingEntity')->reportARHealthFacilitySummary(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'payerType' => $payerType,
            'patient' => $patient,
            'branch' => $branch,
            'branch_address' => $branch_address,
            'company' => $company,
            'userData' => $userData,
        ));

        $columnRange = range('A', 'Z');
        $cellsData = array(
            array('cell' => 'A1', 'data' => 'Payer Type'),
            array('cell' => 'B1', 'data' => 'Patient'),
            array('cell' => 'C1', 'data' => 'Insurance'),
            array('cell' => 'D1', 'data' => 'To Bill'),
            array('cell' => 'E1', 'data' => 'Current'),
            array('cell' => 'F1', 'data' => '30 Days'),
            array('cell' => 'G1', 'data' => '60 Days'),
            array('cell' => 'H1', 'data' => '90 Days'),
            array('cell' => 'I1', 'data' => '120 Days'),
            array('cell' => 'J1', 'data' => 'Credit'),
            array('cell' => 'K1', 'data' => 'Amount'),
        );
        $rowCtr = 1;
        $totalCount = 0;
        $totalCurrentBal = 0;
        $totalThirtyDays = 0;
        $totalSixtyDays = 0;
        $totalNinetyDays = 0;
        $totalOneTwentyDays = 0;
        $totalAmountBalance = 0;

        foreach($records as $record) {

            $rowCtr++;
            $totalCount++;
            $totalCurrentBal += $record['currentBal'];
            $totalThirtyDays += $record['thirtyDays'];
            $totalSixtyDays += $record['sixtyDays'];
            $totalNinetyDays += $record['ninetyDays'];
            $totalOneTwentyDays += $record['oneTwentyDays'];
            $totalAmountBalance += $record['amountBalance'];

            $cellsData[] = array('cell' => "A$rowCtr", 'data' => $record['payerType']);
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => $record['full_name']);
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => $record['patientInsurance']);
            $cellsData[] = array('cell' => "D$rowCtr", 'data' => '--');
            $cellsData[] = array('cell' => "E$rowCtr", 'data' => $record['currentBal'] ? $record['currentBal'] : '0.00');
            $cellsData[] = array('cell' => "F$rowCtr", 'data' => $record['thirtyDays'] ? $record['thirtyDays'] : '0.00');
            $cellsData[] = array('cell' => "G$rowCtr", 'data' => $record['sixtyDays'] ? $record['sixtyDays'] : '0.00');
            $cellsData[] = array('cell' => "H$rowCtr", 'data' => $record['ninetyDays'] ? $record['ninetyDays'] : '0.00');
            $cellsData[] = array('cell' => "I$rowCtr", 'data' => $record['oneTwentyDays'] ? $record['oneTwentyDays'] : '0.00');
            $cellsData[] = array('cell' => "J$rowCtr", 'data' => '--');
            $cellsData[] = array('cell' => "K$rowCtr", 'data' => $record['amountBalance']);
        }

        $rowCtr++;
        $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Total:');
        $cellsData[] = array('cell' => "D$rowCtr", 'data' => '--');
        $cellsData[] = array('cell' => "E$rowCtr", 'data' => number_format($totalCurrentBal));
        $cellsData[] = array('cell' => "F$rowCtr", 'data' => number_format($totalThirtyDays));
        $cellsData[] = array('cell' => "G$rowCtr", 'data' => number_format($totalSixtyDays));
        $cellsData[] = array('cell' => "H$rowCtr", 'data' => number_format($totalNinetyDays));
        $cellsData[] = array('cell' => "I$rowCtr", 'data' => number_format($totalOneTwentyDays));
        $cellsData[] = array('cell' => "J$rowCtr", 'data' => '--');
        $cellsData[] = array('cell' => "K$rowCtr", 'data' => number_format($totalAmountBalance));


        $rowCtr++;
        $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Total Records: ' . $totalCount);
        $rowCtr++;
        $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'AR Summary');
        $rowCtr++;
        $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Branch');
        $cellsData[] = array('cell' => "B$rowCtr", 'data' => 'Current');
        $cellsData[] = array('cell' => "C$rowCtr", 'data' => '30 Days');
        $cellsData[] = array('cell' => "D$rowCtr", 'data' => '60 Days');
        $cellsData[] = array('cell' => "E$rowCtr", 'data' => '90 Days');
        $cellsData[] = array('cell' => "F$rowCtr", 'data' => '120 Days');
        $cellsData[] = array('cell' => "G$rowCtr", 'data' => 'Amount');
        $rowCtr++;

        $sum_totalCurrentBal = 0;
        $sum_totalThirtyDays = 0;
        $sum_totalSixtyDays = 0;
        $sum_totalNinetyDays = 0;
        $sum_totalOneTwentyDays = 0;
        $sum_totalAmountBalance = 0;
        foreach ($records2 as $record2) {
            $rowCtr++;
            $sum_totalCurrentBal += $record2['currentBal'];
            $sum_totalThirtyDays += $record2['thirtyDays'];
            $sum_totalSixtyDays += $record2['sixtyDays'];
            $sum_totalNinetyDays += $record2['ninetyDays'];
            $sum_totalOneTwentyDays += $record2['oneTwentyDays'];
            $sum_totalAmountBalance += $record2['amountBalance'];

            $cellsData[] = array('cell' => "A$rowCtr", 'data' => $record2['healthFacility']);
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => $record2['currentBal']);
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => $record2['thirtyDays']);
            $cellsData[] = array('cell' => "D$rowCtr", 'data' => $record2['sixtyDays']);
            $cellsData[] = array('cell' => "E$rowCtr", 'data' => $record2['ninetyDays']);
            $cellsData[] = array('cell' => "F$rowCtr", 'data' => $record2['oneTwentyDays']);
            $cellsData[] = array('cell' => "G$rowCtr", 'data' => $record2['amountBalance']);
        }

        $rowCtr++;
        $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Total:');
        $cellsData[] = array('cell' => "B$rowCtr", 'data' => number_format($sum_totalCurrentBal));
        $cellsData[] = array('cell' => "C$rowCtr", 'data' => number_format($sum_totalThirtyDays));
        $cellsData[] = array('cell' => "D$rowCtr", 'data' => number_format($sum_totalSixtyDays));
        $cellsData[] = array('cell' => "E$rowCtr", 'data' => number_format($sum_totalNinetyDays));
        $cellsData[] = array('cell' => "F$rowCtr", 'data' => number_format($sum_totalOneTwentyDays));
        $cellsData[] = array('cell' => "G$rowCtr", 'data' => number_format($sum_totalAmountBalance));

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

    //LETTER TRACKER REPORT
    /**
     * @Route("/report_letter_tracker", name="report_letter_tracker")
     */
    public function reportLetterTrackerAction() {

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

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

        $em = $this->getDoctrine()->getManager();
        $company = $em->getRepository('RxConnexionBundle:CompanyEntity')->companiesForMultiple($userData);
        $branch = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->branchesForMultiple($userData);
        $clinicians = $em->getRepository('RxConnexionBundle:ProviderEntity')->clinicianForMultiple();
        $letterStatus = $em->getRepository('RxConnexionBundle:PatientLetterStatusEntity')->findBy(array(
            'isDeleted' => 0
        ));

        $letterTypes = PatientLetterEntity::LETTERS;
        $letterTypeArray = array();

        foreach($letterTypes as $letterType) {
            $letterTypeArray[] = $letterType;
        }

        $page_title = 'Letter Tracker Report';
        return $this->render('@RxConnexion/Report/LetterTracker/index.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'company' => $company,
            'branch' => $branch,
            'clinician' => $clinicians,
            'letterType' => $letterTypeArray,
            'letterStatus' => $letterStatus,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/letterTracker/letterTracker.js')
        ));
    }

    /**
     * @Route(
     *      "/letter_tracker/preview/{company}/{branch}/{patient}/{clinician}/{letterTypes}/{letterStatus}",
     *      name = "report_letter_tracker_preview"
     * )
     */
    public function reportLetterTracker_previewAction($company, $branch, $patient, $clinician, $letterTypes, $letterStatus) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Letter Tracker Preview'))) return $authService->redirectToHome();

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientLetterEntity')->reportLetterTracker(array(
            'company' => $company,
            'branch' => $branch,
            'patient' => $patient,
            'clinician' => $clinician,
            'letterType' => $letterTypes,
            'letterStatus' => $letterStatus,
            'userData' => $userData
        ));

        $page_title = 'Letter Tracker Report';
        return $this->render('@RxConnexion/Report/LetterTracker/preview.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'javascripts' => array('rxconnexion/admin/js/report/report_preview.js'),
            'records' => $records
        ));
    }

    /**
     * @Route(
     *      "/letter_tracker/export_to_pdf/{company}/{branch}/{patient}/{clinician}/{letterTypes}/{letterStatus}",
     *      name = "report_letter_tracker_export_to_pdf"
     * )
     */
    public function reportLetterTracker_export_to_pdfAction($company, $branch, $patient, $clinician, $letterTypes, $letterStatus) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Letter Tracker Pdf'))) return $authService->redirectToHome();

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientLetterEntity')->reportLetterTracker(array(
            'company' => $company,
            'branch' => $branch,
            'patient' => $patient,
            'clinician' => $clinician,
            'letterType' => $letterTypes,
            'letterStatus' => $letterStatus,
            'userData' => $userData
        ));

        $page_title = 'Letter Tracker Report';
        $content = $this->renderView('@RxConnexion/Report/LetterTracker/preview.wkpdf.twig', array(
            'page_title' => $page_title,
            'records' => $records
        ));

        $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content, array(
            'orientation'=>'Landscape',
            'dpi' => 72,
            // 'disable-smart-shrinking',
            'zoom' => 'LINUX' == strtoupper(PHP_OS) ? 0.78 : 1
        ));

        $pdfResponse = array(
            'success' => true,
            'msg' => 'PDF was successfully generated.',
            'pdfBase64' => base64_encode($xml)
        );
        if($pdfResponse['success']) {
            $pdfContent = $pdfResponse['pdfBase64'];
            return new Response(base64_decode($pdfContent), 200, array(
                'Content-Type' => 'application/pdf',
                'Content-Disposition'   => 'attachment; filename="Letter Tracker Report' . date('m/d/Y') . ' Details.pdf"'
            ));
        } else {
            $this->get('session')->getFlashBag()->set('error_messages', $pdfResponse['msg']);
            return $this->redirect($this->generateUrl('report_letter_tracker', 302));
        }
    }

    /**
     * @Route(
     *      "/letter_tracker/export_to_excel/{company}/{branch}/{patient}/{clinician}/{letterTypes}/{letterStatus}",
     *      name = "report_letter_tracker_export_to_excel"
     * )
     */
    public function reportLetterTracker_export_to_excelAction($company, $branch, $patient, $clinician, $letterTypes, $letterStatus) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Letter Tracker Excel'))) return $authService->redirectToHome();

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientLetterEntity')->reportLetterTracker(array(
            'company' => $company,
            'branch' => $branch,
            'patient' => $patient,
            'clinician' => $clinician,
            'letterType' => $letterTypes,
            'letterStatus' => $letterStatus,
            'userData' => $userData
        ));

        $columnRange = range('A', 'Z');

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

        $columnRange = range('A', 'Z');
        $cellsData = array(
            array('cell' => 'A1', 'data' => 'Patient'),
            array('cell' => 'B1', 'data' => 'Referring Physician'),
            array('cell' => 'C1', 'data' => 'Interpreting Physician'),
            array('cell' => 'D1', 'data' => 'Letter Type'),
            array('cell' => 'E1', 'data' => 'Letter Status'),
            array('cell' => 'F1', 'data' => 'Letter Request Date'),
            array('cell' => 'G1', 'data' => 'Date of letter initiation'),
            array('cell' => 'H1', 'data' => 'Letter audited'),
            array('cell' => 'I1', 'data' => 'Date Sent'),
            array('cell' => 'J1', 'data' => 'Fax Confirmation'),
            array('cell' => 'K1', 'data' => 'Created By'),
            array('cell' => 'L1', 'data' => 'Assigned To'),
            array('cell' => 'M1', 'data' => 'Link to Letter'),
        );
        $rowCtr = 1;
        $totalCount = 0;

        foreach($records as $record) {

            $rowCtr++;
            $totalCount++;

            $cellsData[] = array('cell' => "A$rowCtr", 'data' => $record['patientName']);
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => $record['referringPhysician']);
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => $record['hsatInProvider']);
            $cellsData[] = array('cell' => "D$rowCtr", 'data' => $record['letterType']);
            $cellsData[] = array('cell' => "E$rowCtr", 'data' => $record['letterStatus']);
            $cellsData[] = array('cell' => "F$rowCtr", 'data' => $record['requestDate']);
            $cellsData[] = array('cell' => "G$rowCtr", 'data' => $record['startedAndCompletedDate']);
            $cellsData[] = array('cell' => "H$rowCtr", 'data' => $record['reviewBy'] ? $record['reviewBy'].' ('.$record['reviewAt'].')' : '');
            $cellsData[] = array('cell' => "I$rowCtr", 'data' => $record['sentBy'] ? $record['sentBy'].' ('.$record['sentAt'].')' : '');
            $cellsData[] = array('cell' => "J$rowCtr", 'data' => $record['faxConfirmationDesc']);
            $cellsData[] = array('cell' => "K$rowCtr", 'data' => $record['createdBy']);
            $cellsData[] = array('cell' => "L$rowCtr", 'data' => $record['assignTo']);
            $cellsData[] = array('cell' => "M$rowCtr", 'data' => $record['photoDesc']);
        }

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

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

    //Invoice Itemized Report
    /**
     * @Route("/report_invoice_itemised", name="report_invoice_itemised")
     */
    public function invoice_itemised_ReportAction() {

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

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

        $em = $this->getDoctrine()->getManager();
        $company = $em->getRepository('RxConnexionBundle:CompanyEntity')->companiesForMultiple($userData);
        $branch = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->branchesForBillingMultiple($userData);

        $page_title = 'Invoice Itemize Report';
        return $this->render('@RxConnexion/Report/InvoiceItemised/index.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'company' => $company,
            'branch' => $branch,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/invoice_itemised/invoice_itemised.js?v=1.0.2')
        ));
    }

    /**
     * @Route(
     *      "/report_invoice_itemised/preview/{date_from}/{date_to}/{patient}/{company}/{branch}/{branchAddress}/{term}/{item_type}",
     *      name = "report_invoice_itemised_preview"
     * )
     */
    public function report_invoice_itemised_previewAction($date_from, $date_to, $patient, $company, $branch, $branchAddress, $term, $item_type) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Invoice Itemised Preview'))) return $authService->redirectToHome();

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientBillingEntity')->report_itemised(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'patient' => $patient,
            'company' => $company,
            'branch' => $branch,
            'branchAddress' => $branchAddress,
            'term' => $term,
            'item_type' => $item_type,
            'userData' => $userData
        ));

        $page_title = 'Invoice Itemize Report';
        return $this->render('@RxConnexion/Report/InvoiceItemised/preview.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'javascripts' => array('rxconnexion/admin/js/report/report_preview.js'),
            'records' => $records,
        ));
    }

    /**
     * @Route(
     *      "/report_invoice_itemised/export_to_pdf/{date_from}/{date_to}/{patient}/{company}/{branch}/{branchAddress}/{term}/{item_type}",
     *      name = "report_invoice_itemised_export_to_pdf"
     * )
     */
    public function report_invoice_itemised_export_to_pdfAction($date_from, $date_to, $patient, $company, $branch, $branchAddress, $term, $item_type) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Invoice Itemised Pdf'))) return $authService->redirectToHome();

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientBillingEntity')->report_itemised(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'patient' => $patient,
            'company' => $company,
            'branch' => $branch,
            'branchAddress' => $branchAddress,
            'term' => $term,
            'item_type' => $item_type,
            'userData' => $userData
        ));

        $page_title = 'Invoice Itemize Report';
        $content = $this->renderView('@RxConnexion/Report/InvoiceItemised/preview.wkpdf.twig', array(
            'page_title' => $page_title,
            'records' => $records
        ));

        $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content, array(
            'orientation'=>'Landscape',
            'dpi' => 72,
            // 'disable-smart-shrinking',
            'zoom' => 'LINUX' == strtoupper(PHP_OS) ? 0.78 : 1
        ));

        $pdfResponse = array(
            'success' => true,
            'msg' => 'PDF was successfully generated.',
            'pdfBase64' => base64_encode($xml)
        );
        if($pdfResponse['success']) {
            $pdfContent = $pdfResponse['pdfBase64'];
            return new Response(base64_decode($pdfContent), 200, array(
                'Content-Type' => 'application/pdf',
                'Content-Disposition'   => 'attachment; filename="Invoice Itemize Report' . date('m/d/Y') . ' Details.pdf"'
            ));
        } else {
            $this->get('session')->getFlashBag()->set('error_messages', $pdfResponse['msg']);
            return $this->redirect($this->generateUrl('report_invoice_itemised', 302));
        }
    }

    /**
     * @Route(
     *      "/report_invoice_itemised/export_to_excel/{date_from}/{date_to}/{patient}/{company}/{branch}/{branchAddress}/{term}/{item_type}",
     *      name = "report_invoice_itemised_export_to_excel"
     * )
     */
    public function report_invoice_itemised_export_to_excelAction($date_from, $date_to, $patient, $company, $branch, $branchAddress, $term, $item_type) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Invoice Itemised Excel'))) return $authService->redirectToHome();

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientBillingEntity')->report_itemised(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'patient' => $patient,
            'company' => $company,
            'branch' => $branch,
            'branchAddress' => $branchAddress,
            'term' => $term,
            'item_type' => $item_type,
            'userData' => $userData
        ));

        $columnRange = range('A', 'Z');
        $cellsData = array(
            array('cell' => 'A1', 'data' => 'Patient'),
            array('cell' => 'B1', 'data' => 'Invoice No.'),
            array('cell' => 'C1', 'data' => 'Company'),
            array('cell' => 'D1', 'data' => 'Branch'),
            array('cell' => 'E1', 'data' => 'Branch Address'),
            array('cell' => 'F1', 'data' => 'Category'),
            array('cell' => 'G1', 'data' => 'Term'),
            array('cell' => 'H1', 'data' => 'Item Type'),
            array('cell' => 'I1', 'data' => 'Description'),
            array('cell' => 'J1', 'data' => 'Quality'),
            array('cell' => 'K1', 'data' => 'Price'),
        );
        $rowCtr = 1;
        $totalCount = 0;

        $totalQty = 0;
        $totalPrice = 0;
        foreach($records as $record) {
            $totalQty = $totalQty + $record['qty'];
            $totalPrice = $totalPrice + $record['price'];
            $rowCtr++;
            $totalCount++;

            $cellsData[] = array('cell' => "A$rowCtr", 'data' => $record['patientName']);
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => $record['invoiceNo']);
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => $record['companyDesc']);
            $cellsData[] = array('cell' => "D$rowCtr", 'data' => $record['branch']);
            $cellsData[] = array('cell' => "E$rowCtr", 'data' => $record['branchAddress']);
            $cellsData[] = array('cell' => "F$rowCtr", 'data' => $record['itemCategory']);
            $cellsData[] = array('cell' => "G$rowCtr", 'data' => $record['term']);
            $cellsData[] = array('cell' => "H$rowCtr", 'data' => $record['itemType']);
            $cellsData[] = array('cell' => "I$rowCtr", 'data' => $record['itemDesc']);
            $cellsData[] = array('cell' => "J$rowCtr", 'data' => $record['qty']);
            $cellsData[] = array('cell' => "K$rowCtr", 'data' => $record['price']);
        }

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


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

    //Short Term and Long Term Rental Report
    /**
     * @Route("/report_rent_to_own_long_term_rental", name="report_rent_to_own_long_term_rental")
     */
    public function report_rent_to_own_long_term_rental_ReportAction() {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Rent to Own and Long Term Rental'))) return $authService->redirectToHome();

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

        $em = $this->getDoctrine()->getManager();
        $company = $em->getRepository('RxConnexionBundle:CompanyEntity')->companiesForMultiple($userData);
        $branch = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->branchesForBillingMultiple($userData);

        $page_title = 'Rental Report';
        return $this->render('@RxConnexion/Report/LongTermRental/index.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'company' => $company,
            'branch' => $branch,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/rent_to_own_long_term_rental/rent_to_own_long_term_rental.js?v=1.0.1')
        ));
    }

    /**
     * @Route(
     *      "/report_rent_to_own_long_term_rental/preview/{company}/{branch}/{clinician}/{type}",
     *      name = "report_short_term_long_term_rental_preview"
     * )
     */
    public function report_rent_to_own_long_term_rental_previewAction($company, $branch, $clinician, $type) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Rent to Own and Long Term Rental Preview'))) return $authService->redirectToHome();

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientBillingEntity')->report_rent_to_own_long_term_rental(array(
            'branch' => $branch,
            'company' => $company,
            'clinician' => $clinician,
            'type' => $type,
        ));

        $page_title = 'Rental Report';
        return $this->render('@RxConnexion/Report/LongTermRental/preview.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'javascripts' => array('rxconnexion/admin/js/report/report_preview.js'),
            'records' => $records,
        ));
    }

    /**
     * @Route(
     *      "/report_rent_to_own_long_term_rental/export_to_pdf/{company}/{branch}/{clinician}/{type}",
     *      name = "report_rent_to_own_long_term_rental_export_to_pdf"
     * )
     */
    public function report_rent_to_own_long_term_rental_export_to_pdfAction($company, $branch, $clinician, $type) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Rent to Own and Long Term Rental Pdf'))) return $authService->redirectToHome();

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientBillingEntity')->report_rent_to_own_long_term_rental(array(
            'branch' => $branch,
            'company' => $company,
            'clinician' => $clinician,
            'type' => $type,
        ));

        $page_title = 'Rental Report';
        $content = $this->renderView('@RxConnexion/Report/LongTermRental/preview.wkpdf.twig', array(
            'page_title' => $page_title,
            'records' => $records
        ));

        $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content, array(
            'orientation'=>'Landscape',
            'dpi' => 72,
            // 'disable-smart-shrinking',
            'zoom' => 'LINUX' == strtoupper(PHP_OS) ? 0.78 : 1
        ));

        $pdfResponse = array(
            'success' => true,
            'msg' => 'PDF was successfully generated.',
            'pdfBase64' => base64_encode($xml)
        );
        if($pdfResponse['success']) {
            $pdfContent = $pdfResponse['pdfBase64'];
            return new Response(base64_decode($pdfContent), 200, array(
                'Content-Type' => 'application/pdf',
                'Content-Disposition'   => 'attachment; filename="Rent to Own and Long Term Rental Report' . date('m/d/Y') . ' Details.pdf"'
            ));
        } else {
            $this->get('session')->getFlashBag()->set('error_messages', $pdfResponse['msg']);
            return $this->redirect($this->generateUrl('report_rent_to_own_long_term_rental', 302));
        }
    }

    /**
     * @Route(
     *      "/report_rent_to_own_long_term_rental/export_to_excel/{company}/{branch}/{clinician}/{type}",
     *      name = "report_rent_to_own_long_term_rental_export_to_excel"
     * )
     */
    public function report_rent_to_own_long_term_rental_export_to_excelAction($company, $branch, $clinician, $type) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Rent to Own and Long Term Rental Excel'))) return $authService->redirectToHome();

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientBillingEntity')->report_rent_to_own_long_term_rental(array(
            'branch' => $branch,
            'company' => $company,
            'clinician' => $clinician,
            'type' => $type,
        ));

        $columnRange = range('A', 'Z');
        $cellsData = array(
            array('cell' => 'A1', 'data' => 'Patient'),
            array('cell' => 'B1', 'data' => 'Company'),
            array('cell' => 'C1', 'data' => 'Branch'),
            array('cell' => 'D1', 'data' => 'Item'),
            array('cell' => 'E1', 'data' => 'Payment Plan Type'),
            array('cell' => 'F1', 'data' => 'Quantity'),
            array('cell' => 'G1', 'data' => 'Price'),
            array('cell' => 'H1', 'data' => 'Payment Day'),
            array('cell' => 'I1', 'data' => 'Amortization Amount'),
            array('cell' => 'J1', 'data' => 'Start Date'),
            array('cell' => 'K1', 'data' => 'End Date'),
        );
        $rowCtr = 1;
        $totalCount = 0;

        foreach($records as $record) {

            $rowCtr++;
            $totalCount++;

            $cellsData[] = array('cell' => "A$rowCtr", 'data' => $record['patientName']);
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => $record['companyDesc']);
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => $record['branchDesc']);
            $cellsData[] = array('cell' => "D$rowCtr", 'data' => $record['itemDesc']);
            $cellsData[] = array('cell' => "E$rowCtr", 'data' => $record['paymentPlanType']);
            $cellsData[] = array('cell' => "F$rowCtr", 'data' => $record['qty']);
            $cellsData[] = array('cell' => "G$rowCtr", 'data' => $record['price']);
            $cellsData[] = array('cell' => "H$rowCtr", 'data' => $record['paymentDay']);
            $cellsData[] = array('cell' => "I$rowCtr", 'data' => $record['amortizationAmt']);
            $cellsData[] = array('cell' => "J$rowCtr", 'data' => $record['startDate']);
            $cellsData[] = array('cell' => "K$rowCtr", 'data' => $record['endDate']);
        }

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


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


    //My Task Report
    /**
     * @Route("/report_my_task", name="report_my_task")
     */
    public function report_my_task_ReportAction() {

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

//        $session = $this->get('session');
//        $userData = $session->get('userData');
//
//        $em = $this->getDoctrine()->getManager();
//        $company = $em->getRepository('RxConnexionBundle:CompanyEntity')->companiesForMultiple($userData);
//        $branch = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->branchesForMultiple($userData);

        $page_title = 'My Task Report';
        return $this->render('@RxConnexion/Report/MyTask/index.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/ticket/ticket.js?v=1.0.1')
        ));
    }

    /**
     * @Route(
     *      "/report_my_task/preview/{date_from}/{date_to}/{account_user}/{status}",
     *      name = "report_my_task_preview"
     * )
     */
    public function report_my_task_previewAction($date_from, $date_to, $account_user, $status) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report My Task Preview'))) return $authService->redirectToHome();

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:TicketEntity')->reportTicket(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'account_user' => $account_user,
            'status' => $status,
        ));

        $page_title = 'My Task Report';
        return $this->render('@RxConnexion/Report/MyTask/preview.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'javascripts' => array('rxconnexion/admin/js/report/report_preview.js'),
            'records' => $records,
        ));
    }

    /**
     * @Route(
     *      "/report_my_task/export_to_pdf/{date_from}/{date_to}/{account_user}/{status}",
     *      name = "report_my_task_export_to_pdf"
     * )
     */
    public function report_my_task_export_to_pdfAction($date_from, $date_to, $account_user, $status) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report My Task Pdf'))) return $authService->redirectToHome();

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:TicketEntity')->reportTicket(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'account_user' => $account_user,
            'status' => $status,
        ));

        $page_title = 'My Task Report';
        $content = $this->renderView('@RxConnexion/Report/MyTask/preview.wkpdf.twig', array(
            'page_title' => $page_title,
            'records' => $records
        ));

        $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content, array(
            'orientation'=>'Landscape',
            'dpi' => 72,
            // 'disable-smart-shrinking',
            'zoom' => 'LINUX' == strtoupper(PHP_OS) ? 0.78 : 1
        ));

        $pdfResponse = array(
            'success' => true,
            'msg' => 'PDF was successfully generated.',
            'pdfBase64' => base64_encode($xml)
        );
        if($pdfResponse['success']) {
            $pdfContent = $pdfResponse['pdfBase64'];
            return new Response(base64_decode($pdfContent), 200, array(
                'Content-Type' => 'application/pdf',
                'Content-Disposition'   => 'attachment; filename="My Task Report' . date('m/d/Y') . ' Details.pdf"'
            ));
        } else {
            $this->get('session')->getFlashBag()->set('error_messages', $pdfResponse['msg']);
            return $this->redirect($this->generateUrl('report_my_task', 302));
        }
    }

    /**
     * @Route(
     *      "/report_my_task/export_to_excel/{date_from}/{date_to}/{account_user}/{status}",
     *      name = "report_my_task_export_to_excel"
     * )
     */
    public function report_my_task_export_to_excelAction($date_from, $date_to, $account_user, $status) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report My Task Excel'))) return $authService->redirectToHome();

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:TicketEntity')->reportTicket(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'account_user' => $account_user,
            'status' => $status,
        ));

        $columnRange = range('A', 'Z');
        $cellsData = array(
            array('cell' => 'A1', 'data' => 'Patient'),
            array('cell' => 'B1', 'data' => 'Ticket ID'),
            array('cell' => 'C1', 'data' => 'Ticket Severity'),
            array('cell' => 'D1', 'data' => 'Ticket Status'),
            array('cell' => 'E1', 'data' => 'Assigned To'),
            array('cell' => 'F1', 'data' => 'Latest Note'),
        );
        $rowCtr = 1;
        $totalCount = 0;

        foreach($records as $record) {

            $rowCtr++;
            $totalCount++;

            $cellsData[] = array('cell' => "A$rowCtr", 'data' => $record['patientName']);
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => $record['ticketId']);
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => $record['ticketSeverity']);
            $cellsData[] = array('cell' => "D$rowCtr", 'data' => $record['ticketStatus']);
            $cellsData[] = array('cell' => "E$rowCtr", 'data' => $record['assignedTo']);
            $cellsData[] = array('cell' => "F$rowCtr", 'data' => $record['latestNote']);
        }

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


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

    //My Letter Report
    /**
     * @Route("/report_letter", name="report_letter")
     */
    public function report_letter_ReportAction() {

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

//        $session = $this->get('session');
//        $userData = $session->get('userData');
//
//        $em = $this->getDoctrine()->getManager();
//        $company = $em->getRepository('RxConnexionBundle:CompanyEntity')->companiesForMultiple($userData);
//        $branch = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->branchesForMultiple($userData);

        $page_title = 'Letter Report';
        return $this->render('@RxConnexion/Report/Letter/index.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/letter/letter.js?v=1.0.1')
        ));
    }

    /**
     * @Route(
     *      "/report_letter/preview/{date_from}/{date_to}/{account_user}/{status}",
     *      name = "report_letter_preview"
     * )
     */
    public function report_letter_previewAction($date_from, $date_to, $account_user, $status) {

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientLetterEntity')->reportLetter(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'account_user' => $account_user,
            'status' => $status,
        ));

        $page_title = 'Letter Report';
        return $this->render('@RxConnexion/Report/Letter/preview.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'javascripts' => array('rxconnexion/admin/js/report/report_preview.js'),
            'records' => $records,
        ));
    }

    /**
     * @Route(
     *      "/report_letter/export_to_pdf/{date_from}/{date_to}/{account_user}/{status}",
     *      name = "report_letter_export_to_pdf"
     * )
     */
    public function report_letter_export_to_pdfAction($date_from, $date_to, $account_user, $status) {

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientLetterEntity')->reportLetter(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'account_user' => $account_user,
            'status' => $status,
        ));

        $page_title = 'Letter Report';
        $content = $this->renderView('@RxConnexion/Report/Letter/preview.wkpdf.twig', array(
            'page_title' => $page_title,
            'records' => $records
        ));

        $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content, array(
            'orientation'=>'Landscape',
            'dpi' => 72,
            // 'disable-smart-shrinking',
            'zoom' => 'LINUX' == strtoupper(PHP_OS) ? 0.78 : 1
        ));

        $pdfResponse = array(
            'success' => true,
            'msg' => 'PDF was successfully generated.',
            'pdfBase64' => base64_encode($xml)
        );
        if($pdfResponse['success']) {
            $pdfContent = $pdfResponse['pdfBase64'];
            return new Response(base64_decode($pdfContent), 200, array(
                'Content-Type' => 'application/pdf',
                'Content-Disposition'   => 'attachment; filename="Letter Report' . date('m/d/Y') . ' Details.pdf"'
            ));
        } else {
            $this->get('session')->getFlashBag()->set('error_messages', $pdfResponse['msg']);
            return $this->redirect($this->generateUrl('report_letter', 302));
        }
    }

    /**
     * @Route(
     *      "/report_letter/export_to_excel/{date_from}/{date_to}/{account_user}/{status}",
     *      name = "report_letter_export_to_excel"
     * )
     */
    public function report_letter_export_to_excelAction($date_from, $date_to, $account_user, $status) {

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientLetterEntity')->reportLetter(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'account_user' => $account_user,
            'status' => $status,
        ));

        $columnRange = range('A', 'Z');
        $cellsData = array(
            array('cell' => 'A1', 'data' => 'Patient'),
            array('cell' => 'B1', 'data' => 'Letter Type'),
            array('cell' => 'C1', 'data' => 'Assigned To'),
            array('cell' => 'D1', 'data' => 'Letter Status'),
        );
        $rowCtr = 1;
        $totalCount = 0;

        foreach($records as $record) {

            $rowCtr++;
            $totalCount++;

            $cellsData[] = array('cell' => "A$rowCtr", 'data' => $record['patientName']);
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => $record['letterType']);
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => $record['assignedTo']);
            $cellsData[] = array('cell' => "D$rowCtr", 'data' => $record['Letter Status']);
        }

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


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

    //Reminder Report
    /**
     * @Route("/report_reminder", name="report_reminder")
     */
    public function reminder_ReportAction() {

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

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

        $em = $this->getDoctrine()->getManager();
        $reminderType = $em->getRepository('RxConnexionBundle:ReminderTypeEntity')->findBy(array(
            'isDeleted' => 0
        ));

        $userGroup = $em->getRepository('RxConnexionBundle:UserGroupEntity')->findBy(array(
           'isDeleted' => 0
        ));

        $page_title = 'Reminder Report';
        return $this->render('@RxConnexion/Report/Reminder/index.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'reminderType' => $reminderType,
            'userGroup' => $userGroup,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/reminder/reminder.js?v=1.0.0')
        ));
    }

    /**
     * @Route(
     *      "/report_reminder/preview/{date_from}/{date_to}/{reminderType}/{userGroup}/{status}/{account_user}",
     *      name = "report_reminder_preview"
     * )
     */
    public function report_reminder_previewAction($date_from, $date_to, $reminderType, $userGroup, $status, $account_user) {

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:AccountUserReminderEntity')->reportReminder(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'reminderType' => $reminderType,
            'userGroup' => $userGroup,
            'status' => $status,
            'account_user' => $account_user,
        ));

        $page_title = 'Reminder Report';
        return $this->render('@RxConnexion/Report/Reminder/preview.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'javascripts' => array('rxconnexion/admin/js/report/report_preview.js'),
            'records' => $records,
        ));
    }

    /**
     * @Route(
     *      "/report_reminder/export_to_pdf/{date_from}/{date_to}/{reminderType}/{userGroup}/{status}/{account_user}",
     *      name = "report_reminder_export_to_pdf"
     * )
     */
    public function report_reminder_export_to_pdfAction($date_from, $date_to, $reminderType, $userGroup, $status, $account_user) {

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:AccountUserReminderEntity')->reportLetter(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'reminderType' => $reminderType,
            'userGroup' => $userGroup,
            'status' => $status,
            'account_user' => $account_user,
        ));

        $page_title = 'Reminder Report';
        $content = $this->renderView('@RxConnexion/Report/Reminder/preview.wkpdf.twig', array(
            'page_title' => $page_title,
            'records' => $records
        ));

        $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content, array(
            'orientation'=>'Landscape',
            'dpi' => 72,
            // 'disable-smart-shrinking',
            'zoom' => 'LINUX' == strtoupper(PHP_OS) ? 0.78 : 1
        ));

        $pdfResponse = array(
            'success' => true,
            'msg' => 'PDF was successfully generated.',
            'pdfBase64' => base64_encode($xml)
        );
        if($pdfResponse['success']) {
            $pdfContent = $pdfResponse['pdfBase64'];
            return new Response(base64_decode($pdfContent), 200, array(
                'Content-Type' => 'application/pdf',
                'Content-Disposition'   => 'attachment; filename="Reminder Report' . date('m/d/Y') . ' Details.pdf"'
            ));
        } else {
            $this->get('session')->getFlashBag()->set('error_messages', $pdfResponse['msg']);
            return $this->redirect($this->generateUrl('report_reminder', 302));
        }
    }

    /**
     * @Route(
     *      "/report_reminder/export_to_excel/{date_from}/{date_to}/{reminderType}/{userGroup}/{status}/{account_user}",
     *      name = "report_letter_export_to_excel"
     * )
     */
    public function report_reminder_export_to_excelAction($date_from, $date_to, $reminderType, $userGroup, $status, $account_user) {

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:AccountUserReminderEntity')->reportLetter(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'reminderType' => $reminderType,
            'userGroup' => $userGroup,
            'status' => $status,
            'account_user' => $account_user,
        ));

        $columnRange = range('A', 'Z');
        $cellsData = array(
            array('cell' => 'A1', 'data' => 'ID'),
            array('cell' => 'B1', 'data' => 'Reminder Type'),
            array('cell' => 'C1', 'data' => 'Status'),
            array('cell' => 'D1', 'data' => 'Patient'),
            array('cell' => 'E1', 'data' => 'Assigned To'),
            array('cell' => 'F1', 'data' => 'User Group'),
            array('cell' => 'G1', 'data' => 'Start Date'),
            array('cell' => 'H1', 'data' => 'End Date'),
            array('cell' => 'I1', 'data' => 'Note'),
        );
        $rowCtr = 1;
        $totalCount = 0;

        foreach($records as $record) {

            $rowCtr++;
            $totalCount++;

            $cellsData[] = array('cell' => "A$rowCtr", 'data' => $record['id']);
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => $record['reminderType']);
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => $record['reminderStatus']);
            $cellsData[] = array('cell' => "D$rowCtr", 'data' => $record['patientName']);
            $cellsData[] = array('cell' => "E$rowCtr", 'data' => $record['accountUserName']);
            $cellsData[] = array('cell' => "F$rowCtr", 'data' => $record['userGroup']);
            $cellsData[] = array('cell' => "G$rowCtr", 'data' => $record['start_date']);
            $cellsData[] = array('cell' => "H$rowCtr", 'data' => $record['end_date']);
            $cellsData[] = array('cell' => "I$rowCtr", 'data' => strip_tags($record['note']));
        }

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


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


    //Patient Data Transfer Report
    /**
     * @Route("/report_patient_data_transfer", name="report_patient_data_transfer")
     */
    public function patient_data_transfer_ReportAction() {

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

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

        $em = $this->getDoctrine()->getManager();
        $company = $em->getRepository('RxConnexionBundle:CompanyEntity')->companiesForMultiple($userData);
        $branch = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->branchesForBillingMultiple($userData);

        $page_title = 'Patient Data Transfer Report';
        return $this->render('@RxConnexion/Report/PatientDataTransfer/index.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'company' => $company,
            'branch' => $branch,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/patientDataTransfer/patientDataTransfer.js?v=1.0.0')
        ));
    }

    /**
     * @Route(
     *      "/report_patient_data_transfer/preview/{date_from}/{date_to}/{company}/{branch}/{is_patient_data_transfer}",
     *      name = "report_patient_data_transfer_preview"
     * )
     */
    public function patient_data_transfer_previewAction($date_from, $date_to, $company, $branch, $is_patient_data_transfer) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Patient Data Transfer Preview'))) return $authService->redirectToHome();

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientChartEntity')->reportPatientDataTransfer(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company,
            'branch' => $branch,
            'is_patient_data_transfer' => $is_patient_data_transfer,
            'userData' => $userData
        ));

        $typeFilter = '';
        switch ($is_patient_data_transfer) {
            case 'All':
                $typeFilter = 'All';
                break;
            case '0':
                $typeFilter = 'Without Patient Data Transfer';
                break;
            case '1':
                $typeFilter = 'With Patient Data Transfer';
                break;
        }

        $page_title = 'Patient Data Transfer Report';
        return $this->render('@RxConnexion/Report/PatientDataTransfer/preview.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'javascripts' => array('rxconnexion/admin/js/report/report_preview.js'),
            'records' => $records,
            'type' => $typeFilter
        ));
    }

    /**
     * @Route(
     *      "/report_patient_data_transfer/export_to_pdf/{date_from}/{date_to}/{company}/{branch}/{is_patient_data_transfer}",
     *      name = "report_patient_data_transfer_export_to_pdf"
     * )
     */
    public function patient_data_transfer_export_to_pdfAction($date_from, $date_to, $company, $branch, $is_patient_data_transfer) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Patient Data Transfer Pdf'))) return $authService->redirectToHome();

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientChartEntity')->reportPatientDataTransfer(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company,
            'branch' => $branch,
            'is_patient_data_transfer' => $is_patient_data_transfer,
            'userData' => $userData
        ));

        $typeFilter = '';
        switch ($is_patient_data_transfer) {
            case 'All':
                $typeFilter = 'All';
                break;
            case '0':
                $typeFilter = 'Without Patient Data Transfer';
                break;
            case '1':
                $typeFilter = 'With Patient Data Transfer';
                break;
        }

        $page_title = 'Patient Data Transfer Report';
        $content = $this->renderView('@RxConnexion/Report/PatientDataTransfer/preview.wkpdf.twig', array(
            'page_title' => $page_title,
            'records' => $records,
            'type' => $typeFilter
        ));

        $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content, array(
            'orientation'=>'Landscape',
            'dpi' => 72,
            // 'disable-smart-shrinking',
            'zoom' => 'LINUX' == strtoupper(PHP_OS) ? 0.78 : 1
        ));

        $pdfResponse = array(
            'success' => true,
            'msg' => 'PDF was successfully generated.',
            'pdfBase64' => base64_encode($xml)
        );
        if($pdfResponse['success']) {
            $pdfContent = $pdfResponse['pdfBase64'];
            return new Response(base64_decode($pdfContent), 200, array(
                'Content-Type' => 'application/pdf',
                'Content-Disposition'   => 'attachment; filename="Patient Data Transfer Report' . date('m/d/Y') . ' Details.pdf"'
            ));
        } else {
            $this->get('session')->getFlashBag()->set('error_messages', $pdfResponse['msg']);
            return $this->redirect($this->generateUrl('report_patient_data_transfer', 302));
        }
    }

    /**
     * @Route(
     *      "/report_patient_data_transfer/export_to_excel/{date_from}/{date_to}/{company}/{branch}/{is_patient_data_transfer}",
     *      name = "report_patient_data_transfer_export_to_excel"
     * )
     */
    public function patient_data_transfer_to_excelAction($date_from, $date_to, $company, $branch, $is_patient_data_transfer) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Patient Data Transfer Excel'))) return $authService->redirectToHome();

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientChartEntity')->reportPatientDataTransfer(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company,
            'branch' => $branch,
            'is_patient_data_transfer' => $is_patient_data_transfer,
            'userData' => $userData
        ));

        $columnRange = range('A', 'Z');
        $cellsData = array(
            array('cell' => 'A1', 'data' => 'Referral Date'),
            array('cell' => 'B1', 'data' => 'Patient'),
            array('cell' => 'C1', 'data' => 'Company'),
            array('cell' => 'D1', 'data' => 'Branch'),
        );
        $rowCtr = 1;
        $totalCount = 0;

        foreach($records as $record) {

            $rowCtr++;
            $totalCount++;

            $cellsData[] = array('cell' => "A$rowCtr", 'data' => $record['referralDate']);
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => $record['patientName']);
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => $record['company']);
            $cellsData[] = array('cell' => "D$rowCtr", 'data' => $record['branch']);
        }

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


        $page_title = 'Patient Data Transfer Report';
        return $this->export_to_excel($columnRange, $cellsData, $page_title);
    }

    //Conversion Report

    /**
     * @Route("/report_conversion/redirect/{date_from}/{date_to}/{company}/{branch}/{type}",
     *      defaults = {
     *          "date_from":  "null",
     *          "date_to":  "null",
     *          "company":  "null",
     *          "branch":  "null",
     *          "type":  "null",
     *      },
     *
     *      name = "report_conversion_redirect_preview"),
     */
    public function conversionRedirectAction($date_from, $date_to, $company, $branch, $type) {

        return $this->redirect($this->generateUrl('report_conversion_preview', array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company,
            'branch' => $branch,
            'type' => $type,
        )));
    }

    /**
     * @Route("/report_conversion", name="report_conversion")
     */
    public function conversion_ReportAction() {

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

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

        $em = $this->getDoctrine()->getManager();
        $company = $em->getRepository('RxConnexionBundle:CompanyEntity')->companiesForMultiple($userData);
        $branch = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->branchesForBillingMultiple($userData);

        $page_title = 'Conversion Report';
        return $this->render('@RxConnexion/Report/Conversion/index.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'company' => $company,
            'branch' => $branch,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/conversion/conversion.js?v=1.0.2')
        ));
    }

    /**
     * @Route(
     *      "/report_conversion/preview/{date_from}/{date_to}/{company}/{branch}/{type}",
     *      name = "report_conversion_preview"
     * )
     */
    public function report_conversion_previewAction($date_from, $date_to, $company, $branch, $type) {

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

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

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


        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:ReferralEntity')->reportConversion(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company,
            'branch' => $branch,
            'type' => $type,
            'userData' => $userData
        ));

        $typeFilter = '';
        switch ($type) {
            case 'null':
                $typeFilter = 'All';
                break;
            case '0':
                $typeFilter = 'Referral without Encounter';
                break;
            case '1':
                $typeFilter = 'HSAT without HSAT Results Interpretation';
                break;
            case '2':
                $typeFilter = 'HSAT Results Interpretation without CPAP Set Up';
                break;
            case '3':
                $typeFilter = 'CPAP Set Up without Invoice';
                break;
        }

        $page_title = 'Conversion Report';
        return $this->render('@RxConnexion/Report/Conversion/preview.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'javascripts' => array('rxconnexion/admin/js/report/report_preview.js'),
            'records' => $records,
            'type' => $typeFilter
        ));
    }

    /**
     * @Route(
     *      "/report_conversion/export_to_pdf/{date_from}/{date_to}/{company}/{branch}/{type}",
     *      name = "report_conversion_export_to_pdf"
     * )
     */
    public function report_conversion_export_to_pdfAction($date_from, $date_to, $company, $branch, $type) {

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

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:ReferralEntity')->reportConversion(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company,
            'branch' => $branch,
            'type' => $type,
            'userData' => $userData
        ));

        $typeFilter = '';
        switch ($type) {
            case 'null':
                $typeFilter = 'All';
                break;
            case '0':
                $typeFilter = 'Referral without Encounter';
                break;
            case '1':
                $typeFilter = 'HSAT without HSAT Results Interpretation';
                break;
            case '2':
                $typeFilter = 'HSAT Results Interpretation without CPAP Set Up';
                break;
            case '3':
                $typeFilter = 'CPAP Set Up without Invoice';
                break;
        }

        $page_title = 'Conversion Report';
        $content = $this->renderView('@RxConnexion/Report/Conversion/preview.wkpdf.twig', array(
            'page_title' => $page_title,
            'records' => $records,
            'type' => $typeFilter
        ));

        $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content, array(
            'orientation'=>'Landscape',
            'dpi' => 72,
            // 'disable-smart-shrinking',
            'zoom' => 'LINUX' == strtoupper(PHP_OS) ? 0.78 : 1
        ));

        $pdfResponse = array(
            'success' => true,
            'msg' => 'PDF was successfully generated.',
            'pdfBase64' => base64_encode($xml)
        );
        if($pdfResponse['success']) {
            $pdfContent = $pdfResponse['pdfBase64'];
            return new Response(base64_decode($pdfContent), 200, array(
                'Content-Type' => 'application/pdf',
                'Content-Disposition'   => 'attachment; filename="Conversion Report' . date('m/d/Y') . ' Details.pdf"'
            ));
        } else {
            $this->get('session')->getFlashBag()->set('error_messages', $pdfResponse['msg']);
            return $this->redirect($this->generateUrl('report_conversion', 302));
        }
    }

    /**
     * @Route(
     *      "/report_conversion/export_to_excel/{date_from}/{date_to}/{company}/{branch}/{type}",
     *      name = "report_conversion_export_to_excel"
     * )
     */
    public function report_conversion_export_to_excelAction($date_from, $date_to, $company, $branch, $type) {

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

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:ReferralEntity')->reportConversion(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company,
            'branch' => $branch,
            'type' => $type,
            'userData' => $userData
        ));

        $typeFilter = '';
        switch ($type) {
            case 'null':
                $typeFilter = 'All';
                break;
            case '0':
                $typeFilter = 'Referral without Encounter';
                break;
            case '1':
                $typeFilter = 'HSAT without HSAT Results Interpretation';
                break;
            case '2':
                $typeFilter = 'HSAT Results Interpretation without CPAP Set Up';
                break;
            case '3':
                $typeFilter = 'CPAP Set Up without Invoice';
                break;
        }

        $columnRange = range('A', 'Z');
        $cellsData = array(
            array('cell' => 'A1', 'data' => 'Referral Date'),
            array('cell' => 'B1', 'data' => 'Received Date'),
            array('cell' => 'C1', 'data' => 'Patient'),
            array('cell' => 'D1', 'data' => 'Company'),
            array('cell' => 'E1', 'data' => 'Branch'),
        );
        $rowCtr = 1;
        $totalCount = 0;

        foreach($records as $record) {
            $rowCtr++;
            $totalCount++;

            $cellsData[] = array('cell' => "A$rowCtr", 'data' => $record['referralDate']);
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => $record['receivedDate']);
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => $record['patientName']);
            $cellsData[] = array('cell' => "D$rowCtr", 'data' => $record['companyDesc']);
            $cellsData[] = array('cell' => "E$rowCtr", 'data' => $record['branchDesc']);
        }

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


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


    //Patient Billing File Report
    /**
     * @Route("/report_patient_billing_file", name="report_patient_billing_file")
     */
    public function patient_billing_file_ReportAction() {

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

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

        $em = $this->getDoctrine()->getManager();
        $company = $em->getRepository('RxConnexionBundle:CompanyEntity')->companiesForMultiple($userData);
        $branch = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->branchesForBillingMultiple($userData);

        $page_title = 'Insurance Package Report';
        return $this->render('@RxConnexion/Report/PatientBillingFile/index.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'company' => $company,
            'branch' => $branch,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/patientBillingFile/patientBillingFile.js?v=1.0.2')
        ));
    }

    /**
     * @Route(
     *      "/report_patient_billing_file/preview/{date_from}/{date_to}/{company}/{branch}/{branchAddress}/{patient}/{status}/{type}",
     *      name = "report_patient_billing_file_preview"
     * )
     */
    public function report_patient_billing_file_previewAction($date_from, $date_to, $company, $branch, $branchAddress, $patient, $status, $type) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Patient Billing File Preview'))) return $authService->redirectToHome();

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

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


        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientBillingEntity')->reportPatientBillingFile(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company,
            'branch' => $branch,
            'branchAddress' => $branchAddress,
            'patient' => $patient,
            'status' => $status,
            'type' => $type,
            'userData' => $userData
        ));

        $typeFilter = '';
        switch ($type) {
            case 'null':
                $typeFilter = 'All';
                break;
            case '1':
                $typeFilter = 'Has Insurance Package File';
                break;
            case '0':
                $typeFilter = 'Without Insurance Package File';
                break;
        }

        $page_title = 'Insurance Package Report';
        return $this->render('@RxConnexion/Report/PatientBillingFile/preview.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'javascripts' => array('rxconnexion/admin/js/report/report_preview.js'),
            'records' => $records,
            'type' => $typeFilter,
        ));
    }

    /**
     * @Route(
     *      "/report_patient_billing_file/export_to_pdf/{date_from}/{date_to}/{company}/{branch}/{branchAddress}/{patient}/{status}/{type}",
     *      name = "report_patient_billing_file_export_to_pdf"
     * )
     */
    public function report_patient_billing_file_export_to_pdfAction($date_from, $date_to, $company, $branch, $branchAddress, $patient, $status, $type) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Patient Billing File Pdf'))) return $authService->redirectToHome();

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientBillingEntity')->reportPatientBillingFile(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company,
            'branch' => $branch,
            'branchAddress' => $branchAddress,
            'patient' => $patient,
            'status' => $status,
            'type' => $type,
            'userData' => $userData
        ));

        $typeFilter = '';
        switch ($type) {
            case 'null':
                $typeFilter = 'All';
                break;
            case '1':
                $typeFilter = 'Has Insurance Package File';
                break;
            case '0':
                $typeFilter = 'Without Insurance Package File';
                break;
        }

        $page_title = 'Insurance Package Report';
        $content = $this->renderView('@RxConnexion/Report/PatientBillingFile/preview.wkpdf.twig', array(
            'page_title' => $page_title,
            'records' => $records,
            'type' => $typeFilter
        ));

        $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content, array(
            'orientation'=>'Landscape',
            'dpi' => 72,
            // 'disable-smart-shrinking',
            'zoom' => 'LINUX' == strtoupper(PHP_OS) ? 0.78 : 1
        ));

        $pdfResponse = array(
            'success' => true,
            'msg' => 'PDF was successfully generated.',
            'pdfBase64' => base64_encode($xml)
        );
        if($pdfResponse['success']) {
            $pdfContent = $pdfResponse['pdfBase64'];
            return new Response(base64_decode($pdfContent), 200, array(
                'Content-Type' => 'application/pdf',
                'Content-Disposition'   => 'attachment; filename="Insurance Package Report' . date('m/d/Y') . ' Details.pdf"'
            ));
        } else {
            $this->get('session')->getFlashBag()->set('error_messages', $pdfResponse['msg']);
            return $this->redirect($this->generateUrl('report_patient_billing_file', 302));
        }
    }

    /**
     * @Route(
     *      "/report_patient_billing_file/export_to_excel/{date_from}/{date_to}/{company}/{branch}/{branchAddress}/{patient}/{status}/{type}",
     *      name = "report_patient_billing_file_export_to_excel"
     * )
     */
    public function report_patient_billing_file_export_to_excelAction($date_from, $date_to, $company, $branch, $branchAddress, $patient, $status, $type) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Patient Billing File Excel'))) return $authService->redirectToHome();

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientBillingEntity')->reportPatientBillingFile(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company,
            'branch' => $branch,
            'branchAddress' => $branchAddress,
            'patient' => $patient,
            'status' => $status,
            'type' => $type,
            'userData' => $userData
        ));

        $columnRange = range('A', 'Z');
        $cellsData = array(
            array('cell' => 'A1', 'data' => 'Invoice No.'),
            array('cell' => 'B1', 'data' => 'Billing Date'),
            array('cell' => 'C1', 'data' => 'Patient'),
            array('cell' => 'D1', 'data' => 'Company'),
            array('cell' => 'E1', 'data' => 'Branch'),
            array('cell' => 'F1', 'data' => 'Branch Address'),
            array('cell' => 'G1', 'data' => 'Status'),
            array('cell' => 'H1', 'data' => 'File'),
            array('cell' => 'I1', 'data' => 'Note'),
        );
        $rowCtr = 1;
        $totalCount = 0;

        foreach($records as $record) {
            $rowCtr++;
            $totalCount++;

            $cellsData[] = array('cell' => "A$rowCtr", 'data' => $record['invoiceNo']);
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => $record['billingDate']);
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => $record['patient']);
            $cellsData[] = array('cell' => "D$rowCtr", 'data' => $record['companyDesc']);
            $cellsData[] = array('cell' => "E$rowCtr", 'data' => $record['healthFacility']);
            $cellsData[] = array('cell' => "F$rowCtr", 'data' => $record['healthFacilityAddress']);
            $cellsData[] = array('cell' => "G$rowCtr", 'data' => $record['billingStatus']);
            $cellsData[] = array('cell' => "H$rowCtr", 'data' => $record['patientFileDesc']);
            $cellsData[] = array('cell' => "I$rowCtr", 'data' => strip_tags($record['note']));
        }

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


        $page_title = 'Patient Billing File Report';
        return $this->export_to_excel($columnRange, $cellsData, $page_title);
    }


    //Referral Source Report
    /**
     * @Route("/report_patient_source_referral", name="report_patient_source_referral")
     */
    public function patient_source_referral_ReportAction() {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Referred By Tracking'))) return $authService->redirectToHome();

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

        $em = $this->getDoctrine()->getManager();
        $company = $em->getRepository('RxConnexionBundle:CompanyEntity')->companiesForMultiple($userData);
        $branch = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->branchesForBillingMultiple($userData);

        $page_title = 'Referred By Tracking Report';
        return $this->render('@RxConnexion/Report/PatientReferralSource/index.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'company' => $company,
            'branch' => $branch,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/patientReferralSource/patientReferralSource.js?v=1.0.2')
        ));
    }

    /**
     * @Route(
     *      "/patient_source_referral/preview/{date_from}/{date_to}/{company}/{branch}",
     *      name = "patient_source_referral_preview"
     * )
     */
    public function report_patient_source_referral_previewAction($date_from, $date_to, $company, $branch) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Referred By Tracking Preview'))) return $authService->redirectToHome();

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientEntity')->referralBy(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company,
            'branch' => $branch,
            'userData' => $userData
        ));

        $page_title = 'Referred By Tracking Report';
        return $this->render('@RxConnexion/Report/PatientReferralSource/preview.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'javascripts' => array('rxconnexion/admin/js/report/report_preview.js'),
            'records' => $records,
        ));
    }

    /**
     * @Route(
     *      "/patient_source_referral/export_to_pdf/{date_from}/{date_to}/{company}/{branch}",
     *      name = "patient_source_referral_export_to_pdf"
     * )
     */
    public function report_patient_source_referral_export_to_pdfAction($date_from, $date_to, $company, $branch) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Referred By Tracking Pdf'))) return $authService->redirectToHome();

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientEntity')->referralBy(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company,
            'branch' => $branch,
            'userData' => $userData
        ));

        $page_title = 'Referred By Tracking Report';
        $content = $this->renderView('@RxConnexion/Report/PatientReferralSource/preview.wkpdf.twig', array(
            'page_title' => $page_title,
            'records' => $records,
        ));

        $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content, array(
            'orientation'=>'Landscape',
            'dpi' => 72,
            // 'disable-smart-shrinking',
            'zoom' => 'LINUX' == strtoupper(PHP_OS) ? 0.78 : 1
        ));

        $pdfResponse = array(
            'success' => true,
            'msg' => 'PDF was successfully generated.',
            'pdfBase64' => base64_encode($xml)
        );
        if($pdfResponse['success']) {
            $pdfContent = $pdfResponse['pdfBase64'];
            return new Response(base64_decode($pdfContent), 200, array(
                'Content-Type' => 'application/pdf',
                'Content-Disposition'   => 'attachment; filename="Referred By Tracking Report' . date('m/d/Y') . ' Details.pdf"'
            ));
        } else {
            $this->get('session')->getFlashBag()->set('error_messages', $pdfResponse['msg']);
            return $this->redirect($this->generateUrl('report_patient_source_referral', 302));
        }
    }

    /**
     * @Route(
     *      "/patient_source_referral/export_to_excel/{date_from}/{date_to}/{company}/{branch}",
     *      name = "patient_source_referral_export_to_excel"
     * )
     */
    public function report_patient_source_referral_export_to_excelAction($date_from, $date_to, $company, $branch) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Referred By Tracking Excel'))) return $authService->redirectToHome();

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientEntity')->referralBy(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company,
            'branch' => $branch,
            'userData' => $userData
        ));

        $columnRange = range('A', 'M');
        $cellsData = array(
            array('cell' => 'A1', 'data' => 'ID'),
            array('cell' => 'B1', 'data' => 'Referral Date'),
            array('cell' => 'C1', 'data' => 'Patient'),
            array('cell' => 'D1', 'data' => 'Company'),
            array('cell' => 'E1', 'data' => 'Branch'),
            array('cell' => 'F1', 'data' => 'Email'),
            array('cell' => 'G1', 'data' => 'Contact No.'),
            array('cell' => 'H1', 'data' => 'Address'),
            array('cell' => 'I1', 'data' => 'DOB'),
            array('cell' => 'J1', 'data' => 'Appointments'),
            array('cell' => 'K1', 'data' => 'Last Appt.'),
            array('cell' => 'L1', 'data' => 'Gender'),
            array('cell' => 'M1', 'data' => 'Referred By'),
        );
        $rowCtr = 1;
        $totalCount = 0;

        foreach($records as $record) {
            $rowCtr++;
            $totalCount++;

            $cellsData[] = array('cell' => "A$rowCtr", 'data' => $record['patientId']);
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => $record['referralDate']);
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => $record['patientName']);
            $cellsData[] = array('cell' => "D$rowCtr", 'data' => $record['companyDesc']);
            $cellsData[] = array('cell' => "E$rowCtr", 'data' => $record['healthFacilityDesc']);
            $cellsData[] = array('cell' => "F$rowCtr", 'data' => $record['email']);
            $cellsData[] = array('cell' => "G$rowCtr", 'data' => $record['contactNo']);
            $cellsData[] = array('cell' => "H$rowCtr", 'data' => $record['address']);
            $cellsData[] = array('cell' => "I$rowCtr", 'data' => $record['birthDate']);
            $cellsData[] = array('cell' => "J$rowCtr", 'data' => $record['appointmentCnt']);
            $cellsData[] = array('cell' => "K$rowCtr", 'data' => $record['lastAppt']);
            $cellsData[] = array('cell' => "L$rowCtr", 'data' => $record['gender']);
            $cellsData[] = array('cell' => "M$rowCtr", 'data' => $record['referredBy']);
        }

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


        $page_title = 'Referred By Tracking Report';
        return $this->export_to_excel($columnRange, $cellsData, $page_title);
    }


    //Insurance Coverage
    /**
     * @Route("/report_insurance_coverage", name="report_insurance_coverage")
     */
    public function insurance_coverage_ReportAction() {

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

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

        $em = $this->getDoctrine()->getManager();
        $company = $em->getRepository('RxConnexionBundle:CompanyEntity')->companiesForMultiple($userData);
        $branch = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->branchesForBillingMultiple($userData);

        $page_title = 'Insurance Coverage Report';
        return $this->render('@RxConnexion/Report/InsuranceCoverage/index.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'company' => $company,
            'branch' => $branch,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/insuranceCoverage/insuranceCoverage.js?v=1.0.2')
        ));
    }

    /**
     * @Route(
     *      "/insurance_coverage/preview/{date_from}/{date_to}/{company}/{branch}/{branch_address}/{insurance}",
     *      name = "insurance_coverage_preview"
     * )
     */
    public function report_insurance_coverage_previewAction($date_from, $date_to, $company, $branch, $branch_address, $insurance) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Insurance Coverage Preview'))) return $authService->redirectToHome();

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

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


        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientInsuranceEntity')->insuranceCoverage(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company,
            'branch' => $branch,
            'branchAddress' => $branch_address,
            'insurance' => $insurance,
            'userData' => $userData
        ));

        $page_title = 'Insurance Coverage Report';
        return $this->render('@RxConnexion/Report/InsuranceCoverage/preview.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'javascripts' => array('rxconnexion/admin/js/report/report_preview.js'),
            'records' => $records,
        ));
    }

    /**
     * @Route(
     *      "/insurance_coverage/export_to_pdf/{date_from}/{date_to}/{company}/{branch}/{insurance}",
     *      name = "insurance_coverage_export_to_pdf"
     * )
     */
    public function report_insurance_coverage_export_to_pdfAction($date_from, $date_to, $company, $branch, $branch_address, $insurance) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Insurance Coverage Pdf'))) return $authService->redirectToHome();

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientInsuranceEntity')->insuranceCoverage(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company,
            'branch' => $branch,
            'branchAddress' => $branch_address,
            'insurance' => $insurance,
            'userData' => $userData
        ));

        $page_title = 'Insurance Coverage Report';
        $content = $this->renderView('@RxConnexion/Report/InsuranceCoverage/preview.wkpdf.twig', array(
            'page_title' => $page_title,
            'records' => $records,
        ));

        $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content, array(
            'orientation'=>'Landscape',
            'dpi' => 72,
            // 'disable-smart-shrinking',
            'zoom' => 'LINUX' == strtoupper(PHP_OS) ? 0.78 : 1
        ));

        $pdfResponse = array(
            'success' => true,
            'msg' => 'PDF was successfully generated.',
            'pdfBase64' => base64_encode($xml)
        );
        if($pdfResponse['success']) {
            $pdfContent = $pdfResponse['pdfBase64'];
            return new Response(base64_decode($pdfContent), 200, array(
                'Content-Type' => 'application/pdf',
                'Content-Disposition'   => 'attachment; filename="Insurance Coverage Report' . date('m/d/Y') . ' Details.pdf"'
            ));
        } else {
            $this->get('session')->getFlashBag()->set('error_messages', $pdfResponse['msg']);
            return $this->redirect($this->generateUrl('report_insurance_coverage', 302));
        }
    }

    /**
     * @Route(
     *      "/insurance_coverage/export_to_excel/{date_from}/{date_to}/{company}/{branch}/{branch_address}/{insurance}",
     *      name = "insurance_coverage_export_to_excel"
     * )
     */
    public function report_insurance_coverage_export_to_excelAction($date_from, $date_to, $company, $branch, $branch_address, $insurance) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Insurance Coverage Excel'))) return $authService->redirectToHome();

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientInsuranceEntity')->insuranceCoverage(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company,
            'branch' => $branch,
            'branch_address' => $branch_address,
            'insurance' => $insurance,
            'userData' => $userData
        ));

        $columnRange = range('A', 'L');
        $cellsData = array(
            array('cell' => 'A1', 'data' => 'Patient'),
            array('cell' => 'B1', 'data' => 'Company'),
            array('cell' => 'C1', 'data' => 'Billing Branch'),
            array('cell' => 'D1', 'data' => 'Billing Address'),
            array('cell' => 'E1', 'data' => 'Insurance'),
            array('cell' => 'F1', 'data' => 'Frequency'),
            array('cell' => 'G1', 'data' => 'Benefit Period'),
            array('cell' => 'H1', 'data' => 'Product Name'),
            array('cell' => 'I1', 'data' => 'Amount'),
            array('cell' => 'J1', 'data' => 'Ceiling Amount'),
            array('cell' => 'K1', 'data' => '% of Coverage'),
            array('cell' => 'L1', 'data' => 'Net Coverage'),
        );
        $rowCtr = 1;
        $totalCount = 0;
        $percentageOfCoverage = 0;
        foreach($records as $record) {
            $rowCtr++;
            $totalCount++;
            $percentageOfCoverage = ($record['amtCovered'] / $record['amt']) * 100;
            $cellsData[] = array('cell' => "A$rowCtr", 'data' => $record['patientName']);
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => $record['companyDesc']);
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => $record['branch']);
            $cellsData[] = array('cell' => "D$rowCtr", 'data' => $record['branchAddress']);
            $cellsData[] = array('cell' => "E$rowCtr", 'data' => $record['insuranceDesc']);
            $cellsData[] = array('cell' => "F$rowCtr", 'data' => $record['frequency']);
            $cellsData[] = array('cell' => "G$rowCtr", 'data' => $record['benefitPeriod']);
            $cellsData[] = array('cell' => "H$rowCtr", 'data' => $record['itemDesc']);
            $cellsData[] = array('cell' => "I$rowCtr", 'data' => $record['amt']);
            $cellsData[] = array('cell' => "J$rowCtr", 'data' => $record['amtCovered']);
            $cellsData[] = array('cell' => "K$rowCtr", 'data' => number_format($percentageOfCoverage, 2, '.', ',').' %');
            $cellsData[] = array('cell' => "L$rowCtr", 'data' => '--');
        }

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


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

    //CBT Tracker Report
    /**
     * @Route("/report_cbt_tracker", name="report_cbt_tracker")
     */
    public function cbt_tracker_ReportAction() {

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

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

        $em = $this->getDoctrine()->getManager();
        $tableList = $em->getRepository('RxConnexionBundle:AuditTrailEntity')->module_list();

        $page_title = 'CBT Tracker Report';
        return $this->render('@RxConnexion/Report/CBTTracker/index.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'tableList' => $tableList,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/cbtTracker/cbtTracker.js?v=1.0.2')
        ));
    }

    /**
     * @Route(
     *      "/report_cbt_tracker/preview/{date_from}/{date_to}/{accountUser}/{tranTable}",
     *      name = "report_cbt_tracker_preview"
     * )
     */
    public function report_cbt_tracker_previewAction($date_from, $date_to, $accountUser, $tranTable) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report CBT Tracker Preview'))) return $authService->redirectToHome();

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:AuditTrailEntity')->report_cbtTracker(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'accountUser' => $accountUser,
            'tran_table' => $tranTable
        ));

        foreach($records as $record) {
            $history = json_decode($record['data'], true);

            $historyData = '';
            $labels = array();
            switch ($record['tableName']) {
                case 'patient_chart' :
                    $labels = array(
                        'id' => 'Encounter ID',
                        'patient' => array(
                            'Patient Name',
                            'full_name'
                        ),
                        'chart_date' => 'Encounter Date',
                        'chart_status' => array(
                            'Encounter Status',
                            'description'
                        ),
                        'chart_type' => array(
                            'Encounter Type',
                            'description'
                        ),
                        'provider' => array(
                            'Clinician ID',
                            'id'
                        ),
                        'health_facility' => array(
                            'Branch',
                            'description'
                        ),
                    );
                    break;

                case 'patient' :
                    $labels = array(
                        'id' => 'Patient ID',
                        'full_name' => 'Patient Name',
                        'gender' => 'Gender',
                        'birth_date' => 'Birth Date',
                        'personal_health_no' => 'Personal Health No.',
                        'address' => 'Address',
                        'referral_date' => 'Patient Referral Date',
                        'received_date' => 'Patient Received Date',
                        'is_active' => 'Active',
                        'is_endorsed' => 'Endorsed',
                        'is_specialist' => 'Specialist',
                        'endorsed_by' => 'Endorsed By',
                        'postal_code' => array(
                            'Postal Code',
                            'description'
                        ),
                        'health_facility' => array(
                            'Branch',
                            'description'
                        ),
                    );
                    break;

                case 'schedule' :
                    $labels = array(
                        'id' => 'Schedule ID',
                        'schedule_date' => 'Date',
                        'start_time' => 'Start Time',
                        'end_time' => 'End Time',
                        'health_facility' => array(
                            'Branch',
                            'description'
                        ),
                        'patient' => array(
                            'Patient Name',
                            'full_name'
                        ),
                        'chart_type' => array(
                            'Encounter Type',
                            'description'
                        ),
                        'schedule_status' => array(
                            'Status',
                            'description'
                        ),
                        'note' => 'Note'
                    );
                    break;

                case 'patient_insurance' :
                    $labels = array(
                        'id' => 'ID',
                        'insurance_no' => 'Insurance No',
                        'expire_date' => 'Expiry Date',
                        'start_date' => 'Start Date',
                        'end_date' => 'End Date',
                        'patient' => array(
                            'Patient Name',
                            'full_name'
                        ),
                    );
                    break;

                case 'patient_referring_health_facility' :
                    $labels = array(
                        'id' => 'ID',
                        'referring_health_facility' => array(
                            'Referring Affiliate',
                            'description'
                        ),
                        'start_date' => 'Start Date',
                        'end_date' => 'End Date',
                        'patient' => array(
                            'Patient Name',
                            'full_name'
                        )
                    );
                    break;

                case 'patient_referring_provider' :
                    $labels = array(
                        'id' => 'ID',
                        'referring_provider' => array(
                            'Referring Physician ID',
                            'id',
                        ),
                        'start_date' => 'Start Date',
                        'end_date' => 'End Date',
                        'patient' => array(
                            'Patient Name',
                            'full_name'
                        )
                    );
                    break;

                case 'patient_file' :
                    $labels = array(
                        'id' => 'ID',
                        'description' => 'Description',
                        'note' => 'Notes',
                        'file_type' => array(
                            'File Type',
                            'description',
                        ),
                        'patient' => array(
                            'Patient Name',
                            'full_name'
                        )
                    );
                    break;

                case 'patient_note' :
                    $labels = array(
                        'id' => 'ID',
                        'note' => 'Notes',
                        'patient' => array(
                            'Patient Name',
                            'full_name'
                        )
                    );
                    break;

                case 'patient_diagnosis' :
                    $labels = array(
                        'id' => 'ID',
                        'start_date' => 'Start Date',
                        'end_date' => 'End Date',
                        'note' => 'Notes',
                        'patient' => array(
                            'Patient Name',
                            'full_name'
                        )
                    );
                    break;

                case 'patient_letter' :
                    $labels = array(
                        'id' => 'ID',
                        'letter_type' => 'Letter Type',
                        'patient_letter_status' => array(
                            'Status',
                            'description'
                        ),
                        'patient_insurance' => array(
                            'Insurance ID',
                            'id'
                        ),
                        'patient' => array(
                            'Patient Name',
                            'full_name'
                        ),
                    );
                    break;

                case 'patient_billing' :
                    $labels = array(
                        'id' => 'ID',
                        'invoice_no' => 'Invoice No.',
                        'billing_date' => 'Billing Date',
                        'amount_due' => 'Amount Due',
                        'amount_paid' => 'Amount Paid',
                        'amount_balance' => 'Amount Balance',
                        'billing_status' => 'Billing Status',
                        'payer_type' => 'Payer Type',
                        'note' => 'Note',
                        'patient_insurance' => array(
                            'Insurance ID',
                            'id'
                        ),
                        'patient_billing_breakdowns' => array(
                            'Breakdowns',
                            array(
                                'type' => 'Type',
                                'description' => 'Description',
                                'quantity' => 'Quantity',
                                'price' => 'Price',
                                'amount' => 'Amount',
                            )
                        ),
                        'patient' => array(
                            'Patient Name',
                            'full_name'
                        ),
                    );
                    break;

                case 'patient_payment' :
                    $labels = array(
                        'id' => 'ID',
                        'pay_type' => 'Pay Type',
                        'pay_date' => 'Pay Date',
                        'amount' => 'Amount',
                        'bill_due_amount' => 'Bill Due Amount',
                        'bill_bal_amount' => 'Bill Bal Amount',
                        'note' => 'Note',
                        'patient_billing' => array(
                            'Invoice No.',
                            'invoice_no'
                        ),
                        'patient' => array(
                            'Patient Name',
                            'full_name'
                        ),
                    );
                    break;

                case 'patient_red_flag' :
                    $labels = array(
                        'id' => 'ID',
                        'start_date' => 'Start Date',
                        'end_date' => 'End Date',
                        'red_flag_note' => 'Red Flag Note',
                        'patient' => array(
                            'Patient Name',
                            'full_name'
                        ),
                    );
                    break;

                case 'patient_service' :
                    $labels = array(
                        'id' => 'ID',
                        'start_date' => 'Start Date',
                        'end_date' => 'End Date',
                        'patient_service_type' => 'Patient Service Type',
                        'service' => array(
                            'Description',
                            'description'
                        ),
                        'specialist' => array(
                            'Last Name',
                            'last_name',
                            'First Name',
                            'first_name'
                        ),
                        'health_facility' => array(
                            'Branch',
                            'description'
                        ),
                        'patient' => array(
                            'Patient Name',
                            'full_name'
                        ),
                    );
                    break;

                case 'ticket' :
                    $labels = array(
                        'id' => 'ID',
                        'account_user' => array(
                            'Username',
                            'username'
                        ),
                        'ticket_status' => array(
                            'Status',
                            'description',
                        ),
                        'ticket_severity' => array(
                            'Severity',
                            'description',
                        ),
                        'note' => 'Note'
                    );
                    break;
            }

            if($record['axn'] == 'New' || $record['axn'] == 'Delete') {
                foreach ($labels as $columnName => $label) {
                    $historyData .= (empty($historyData) ? '' : ' | ');

                    if(is_array($label)) {
                        $historyData .= $label[0] .':';
                        if (isset($history['Details'][$columnName])) {
                            if(is_array($label[1])) {
                                foreach ($history['Details'][$columnName] as $idx => $detailsData) {
                                    $historyData .= ' ('.($idx+1).') ';
                                    $historyData2 = '';
                                    foreach($label[1] as $columnName2 => $label2) {
                                        $historyData2 .= (empty($historyData2) ? '' : ' | ').$label2.': ';
                                        if(isset($history['Details'][$columnName][$idx][$columnName2])) {
                                            $historyData2 .= $history['Details'][$columnName][$idx][$columnName2];
                                        }
                                    }
                                    $historyData .= $historyData2;
                                }
                            } else {
                                $historyData .= $history['Details'][$columnName][$label[1]];
                            }

                        }
                    } else {
                        $historyData .= $label.': ';
                        if(isset($history['Details'][$columnName])) {
                            $historyData .= $history['Details'][$columnName];
                        }
                    }

                }
            }else{
                foreach ($labels as $columnName => $label) {
                    if(is_array($label)) {
                        if(is_array($label[1])) {
                            $origValue = '';
                            $newValue = '';
                            if(isset($history['Original Details'][$columnName])) {
                                foreach ($history['Original Details'][$columnName] as $idx => $detailsData) {
                                    $origValue .= ' ('.($idx+1).') ';
                                    $origValue2 = '';
                                    foreach($label[1] as $columnName2 => $label2) {
                                        $origValue2 .= (empty($origValue2) ? '' : ' | ').$label2.': ';
                                        if(isset($history['Original Details'][$columnName][$idx][$columnName2])) {
                                            $origValue2 .= $history['Original Details'][$columnName][$idx][$columnName2];
                                        }
                                    }
                                    $origValue .= $origValue2;
                                }
                            }

                            if(isset($history['Details'][$columnName])) {
                                foreach ($history['Details'][$columnName] as $idx => $detailsData) {
                                    $newValue .= ' ('.($idx+1).') ';
                                    $newValue2 = '';
                                    foreach($label[1] as $columnName2 => $label2) {
                                        $newValue2 .= (empty($newValue2) ? '' : ' &#8226; ').$label2.': ';
                                        if(isset($history['Details'][$columnName][$idx][$columnName2])) {
                                            $newValue2 .= $history['Details'][$columnName][$idx][$columnName2];
                                        }
                                    }
                                    $newValue .= $newValue2;
                                }
                            }

                        } else {
                            $origValue = isset($history['Original Details'][$columnName]) ? $history['Original Details'][$columnName][$label[1]] : null;
                            $newValue =  isset($history['Details'][$columnName]) ? $history['Details'][$columnName][$label[1]] : null;
                        }
                    } else {
                        $origValue = isset($history['Original Details'][$columnName]) ? $history['Original Details'][$columnName] : null;
                        $newValue =  isset($history['Details'][$columnName]) ? $history['Details'][$columnName] : null;
                    }

                    if($origValue != $newValue) {
                        $historyData .= (empty($historyData) ? '' : ' | ');
                        $historyData .= (is_array($label) ? $label[0] : $label).' : ';
                        $historyData .= $origValue;

                        $historyData .= ' -> ';
                        $historyData .= $newValue;
                    }
                }

            }

            $values = array(
                'action' => $record['axn'],
                'date_created' => $record['dateCreated'],
                'user' => $record['user'],
                'label' => $record['label'],
                'history_data' => $historyData,
            );

            $result['data'][] = $values;
        }

        $page_title = 'CBT Tracker Report';
        return $this->render('@RxConnexion/Report/CBTTracker/preview.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'javascripts' => array('rxconnexion/admin/js/report/report_preview.js'),
            'records' => $result,
        ));
    }

    /**
     * @Route(
     *      "/report_cbt_tracker/export_to_pdf/{date_from}/{date_to}",
     *      name = "report_cbt_tracker_export_to_pdf"
     * )
     */
    public function report_cbt_tracker_export_to_pdfAction($date_from, $date_to) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report CBT Tracker Pdf'))) return $authService->redirectToHome();

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientEntity')->referralBy(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
        ));

        $page_title = 'Referred By Tracking Report';
        $content = $this->renderView('@RxConnexion/Report/CBTTracker/preview.wkpdf.twig', array(
            'page_title' => $page_title,
            'records' => $records,
        ));

        $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content, array(
            'orientation'=>'Landscape',
            'dpi' => 72,
            // 'disable-smart-shrinking',
            'zoom' => 'LINUX' == strtoupper(PHP_OS) ? 0.78 : 1
        ));

        $pdfResponse = array(
            'success' => true,
            'msg' => 'PDF was successfully generated.',
            'pdfBase64' => base64_encode($xml)
        );
        if($pdfResponse['success']) {
            $pdfContent = $pdfResponse['pdfBase64'];
            return new Response(base64_decode($pdfContent), 200, array(
                'Content-Type' => 'application/pdf',
                'Content-Disposition'   => 'attachment; filename="CBT Tracker Report' . date('m/d/Y') . ' Details.pdf"'
            ));
        } else {
            $this->get('session')->getFlashBag()->set('error_messages', $pdfResponse['msg']);
            return $this->redirect($this->generateUrl('report_patient_source_referral', 302));
        }
    }

    /**
     * @Route(
     *      "/report_cbt_tracker/export_to_excel/{date_from}/{date_to}/{accountUser}/{tranTable}",
     *      name = "report_cbt_tracker_export_to_excel"
     * )
     */
    public function report_cbt_tracker_export_to_excelAction($date_from, $date_to, $accountUser, $tranTable) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report CBT Tracker Excel'))) return $authService->redirectToHome();

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

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

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

        $records = $em->getRepository('RxConnexionBundle:AuditTrailEntity')->report_cbtTracker(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'tran_table' => $tranTable,
            'accountUser' => $accountUser
        ));

        foreach($records as $record) {
            $history = json_decode($record['data'], true);

            $historyData = '';
            $labels = array();
            switch ($record['tableName']) {
                case 'patient_chart' :
                    $labels = array(
                        'id' => 'Encounter ID',
                        'patient' => array(
                            'Patient Name',
                            'full_name'
                        ),
                        'chart_date' => 'Encounter Date',
                        'chart_status' => array(
                            'Encounter Status',
                            'description'
                        ),
                        'chart_type' => array(
                            'Encounter Type',
                            'description'
                        ),
                        'provider' => array(
                            'Clinician ID',
                            'id'
                        ),
                        'health_facility' => array(
                            'Branch',
                            'description'
                        ),
                    );
                    break;

                case 'patient' :
                    $labels = array(
                        'id' => 'Patient ID',
                        'full_name' => 'Patient Name',
                        'gender' => 'Gender',
                        'birth_date' => 'Birth Date',
                        'personal_health_no' => 'Personal Health No.',
                        'address' => 'Address',
                        'referral_date' => 'Patient Referral Date',
                        'received_date' => 'Patient Received Date',
                        'is_active' => 'Active',
                        'is_endorsed' => 'Endorsed',
                        'is_specialist' => 'Specialist',
                        'endorsed_by' => 'Endorsed By',
                        'postal_code' => array(
                            'Postal Code',
                            'description'
                        ),
                        'health_facility' => array(
                            'Branch',
                            'description'
                        ),
                    );
                    break;

                case 'schedule' :
                    $labels = array(
                        'id' => 'Schedule ID',
                        'schedule_date' => 'Date',
                        'start_time' => 'Start Time',
                        'end_time' => 'End Time',
                        'health_facility' => array(
                            'Branch',
                            'description'
                        ),
                        'patient' => array(
                            'Patient Name',
                            'full_name'
                        ),
                        'chart_type' => array(
                            'Encounter Type',
                            'description'
                        ),
                        'schedule_status' => array(
                            'Status',
                            'description'
                        ),
                        'note' => 'Note'
                    );
                    break;

                case 'patient_insurance' :
                    $labels = array(
                        'id' => 'ID',
                        'insurance_no' => 'Insurance No',
                        'expire_date' => 'Expiry Date',
                        'start_date' => 'Start Date',
                        'end_date' => 'End Date',
                        'patient' => array(
                            'Patient Name',
                            'full_name'
                        ),
                    );
                    break;

                case 'patient_referring_health_facility' :
                    $labels = array(
                        'id' => 'ID',
                        'referring_health_facility' => array(
                            'Referring Affiliate',
                            'description'
                        ),
                        'start_date' => 'Start Date',
                        'end_date' => 'End Date',
                        'patient' => array(
                            'Patient Name',
                            'full_name'
                        )
                    );
                    break;

                case 'patient_referring_provider' :
                    $labels = array(
                        'id' => 'ID',
                        'referring_provider' => array(
                            'Referring Physician ID',
                            'id',
                        ),
                        'start_date' => 'Start Date',
                        'end_date' => 'End Date',
                        'patient' => array(
                            'Patient Name',
                            'full_name'
                        )
                    );
                    break;

                case 'patient_file' :
                    $labels = array(
                        'id' => 'ID',
                        'description' => 'Description',
                        'note' => 'Notes',
                        'file_type' => array(
                            'File Type',
                            'description',
                        ),
                        'patient' => array(
                            'Patient Name',
                            'full_name'
                        )
                    );
                    break;

                case 'patient_note' :
                    $labels = array(
                        'id' => 'ID',
                        'note' => 'Notes',
                        'patient' => array(
                            'Patient Name',
                            'full_name'
                        )
                    );
                    break;

                case 'patient_diagnosis' :
                    $labels = array(
                        'id' => 'ID',
                        'start_date' => 'Start Date',
                        'end_date' => 'End Date',
                        'note' => 'Notes',
                        'patient' => array(
                            'Patient Name',
                            'full_name'
                        )
                    );
                    break;

                case 'patient_letter' :
                    $labels = array(
                        'id' => 'ID',
                        'letter_type' => 'Letter Type',
                        'patient_letter_status' => array(
                            'Status',
                            'description'
                        ),
                        'patient_insurance' => array(
                            'Insurance ID',
                            'id'
                        ),
                        'patient' => array(
                            'Patient Name',
                            'full_name'
                        ),
                    );
                    break;

                case 'patient_billing' :
                    $labels = array(
                        'id' => 'ID',
                        'invoice_no' => 'Invoice No.',
                        'billing_date' => 'Billing Date',
                        'amount_due' => 'Amount Due',
                        'amount_paid' => 'Amount Paid',
                        'amount_balance' => 'Amount Balance',
                        'billing_status' => 'Billing Status',
                        'payer_type' => 'Payer Type',
                        'note' => 'Note',
                        'patient_insurance' => array(
                            'Insurance ID',
                            'id'
                        ),
                        'patient_billing_breakdowns' => array(
                            'Breakdowns',
                            array(
                                'type' => 'Type',
                                'description' => 'Description',
                                'quantity' => 'Quantity',
                                'price' => 'Price',
                                'amount' => 'Amount',
                            )
                        ),
                        'patient' => array(
                            'Patient Name',
                            'full_name'
                        ),
                    );
                    break;

                case 'patient_payment' :
                    $labels = array(
                        'id' => 'ID',
                        'pay_type' => 'Pay Type',
                        'pay_date' => 'Pay Date',
                        'amount' => 'Amount',
                        'bill_due_amount' => 'Bill Due Amount',
                        'bill_bal_amount' => 'Bill Bal Amount',
                        'note' => 'Note',
                        'patient_billing' => array(
                            'Invoice No.',
                            'invoice_no'
                        ),
                        'patient' => array(
                            'Patient Name',
                            'full_name'
                        ),
                    );
                    break;

                case 'patient_red_flag' :
                    $labels = array(
                        'id' => 'ID',
                        'start_date' => 'Start Date',
                        'end_date' => 'End Date',
                        'red_flag_note' => 'Red Flag Note',
                        'patient' => array(
                            'Patient Name',
                            'full_name'
                        ),
                    );
                    break;

                case 'patient_service' :
                    $labels = array(
                        'id' => 'ID',
                        'start_date' => 'Start Date',
                        'end_date' => 'End Date',
                        'patient_service_type' => 'Patient Service Type',
                        'service' => array(
                            'Description',
                            'description'
                        ),
                        'specialist' => array(
                            'Last Name',
                            'last_name',
                            'First Name',
                            'first_name'
                        ),
                        'health_facility' => array(
                            'Branch',
                            'description'
                        ),
                        'patient' => array(
                            'Patient Name',
                            'full_name'
                        ),
                    );
                    break;

                case 'ticket' :
                    $labels = array(
                        'id' => 'ID',
                        'account_user' => array(
                            'Username',
                            'username'
                        ),
                        'ticket_status' => array(
                            'Status',
                            'description',
                        ),
                        'ticket_severity' => array(
                            'Severity',
                            'description',
                        ),
                    );
                    break;
            }

            if($record['axn'] == 'New' || $record['axn'] == 'Delete') {
                foreach ($labels as $columnName => $label) {
                    $historyData .= (empty($historyData) ? '' : ' | ');

                    if(is_array($label)) {
                        $historyData .= $label[0] .':';
                        if (isset($history['Details'][$columnName])) {
                            if(is_array($label[1])) {
                                foreach ($history['Details'][$columnName] as $idx => $detailsData) {
                                    $historyData .= ' ('.($idx+1).') ';
                                    $historyData2 = '';
                                    foreach($label[1] as $columnName2 => $label2) {
                                        $historyData2 .= (empty($historyData2) ? '' : ' | ').$label2.': ';
                                        if(isset($history['Details'][$columnName][$idx][$columnName2])) {
                                            $historyData2 .= $history['Details'][$columnName][$idx][$columnName2];
                                        }
                                    }
                                    $historyData .= $historyData2;
                                }
                            } else {
                                $historyData .= $history['Details'][$columnName][$label[1]];
                            }

                        }
                    } else {
                        $historyData .= $label.': ';
                        if(isset($history['Details'][$columnName])) {
                            $historyData .= $history['Details'][$columnName];
                        }
                    }

                }
            }else{
                foreach ($labels as $columnName => $label) {
                    if(is_array($label)) {
                        if(is_array($label[1])) {
                            $origValue = '';
                            $newValue = '';
                            if(isset($history['Original Details'][$columnName])) {
                                foreach ($history['Original Details'][$columnName] as $idx => $detailsData) {
                                    $origValue .= ' ('.($idx+1).') ';
                                    $origValue2 = '';
                                    foreach($label[1] as $columnName2 => $label2) {
                                        $origValue2 .= (empty($origValue2) ? '' : ' | ').$label2.': ';
                                        if(isset($history['Original Details'][$columnName][$idx][$columnName2])) {
                                            $origValue2 .= $history['Original Details'][$columnName][$idx][$columnName2];
                                        }
                                    }
                                    $origValue .= $origValue2;
                                }
                            }

                            if(isset($history['Details'][$columnName])) {
                                foreach ($history['Details'][$columnName] as $idx => $detailsData) {
                                    $newValue .= ' ('.($idx+1).') ';
                                    $newValue2 = '';
                                    foreach($label[1] as $columnName2 => $label2) {
                                        $newValue2 .= (empty($newValue2) ? '' : ' &#8226; ').$label2.': ';
                                        if(isset($history['Details'][$columnName][$idx][$columnName2])) {
                                            $newValue2 .= $history['Details'][$columnName][$idx][$columnName2];
                                        }
                                    }
                                    $newValue .= $newValue2;
                                }
                            }

                        } else {
                            $origValue = isset($history['Original Details'][$columnName]) ? $history['Original Details'][$columnName][$label[1]] : null;
                            $newValue =  isset($history['Details'][$columnName]) ? $history['Details'][$columnName][$label[1]] : null;
                        }
                    } else {
                        $origValue = isset($history['Original Details'][$columnName]) ? $history['Original Details'][$columnName] : null;
                        $newValue =  isset($history['Details'][$columnName]) ? $history['Details'][$columnName] : null;
                    }

                    if($origValue != $newValue) {
                        $historyData .= (empty($historyData) ? '' : ' | ');
                        $historyData .= (is_array($label) ? $label[0] : $label).' : ';
                        $historyData .= $origValue;

                        $historyData .= ' -> ';
                        $historyData .= $newValue;
                    }
                }

            }

            $values = array(
                'action' => $record['axn'],
                'date_created' => $record['dateCreated'],
                'user' => $record['user'],
                'label' => $record['label'],
                'history_data' => $historyData,
            );

            $result['data'][] = $values;
        }

        $columnRange = range('A', 'M');
        $cellsData = array(
            array('cell' => 'A1', 'data' => 'Date'),
            array('cell' => 'B1', 'data' => 'Full Name'),
            array('cell' => 'C1', 'data' => 'Module'),
            array('cell' => 'D1', 'data' => 'Action'),
            array('cell' => 'E1', 'data' => 'Data'),
        );
        $rowCtr = 1;
        $totalCount = 0;

        foreach($result['data'] as $results) {
            $rowCtr++;
            $totalCount++;

            $cellsData[] = array('cell' => "A$rowCtr", 'data' => $results['date_created']);
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => $results['user'] ? $results['user'] : 'Super Admin');
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => $results['label']);
            $cellsData[] = array('cell' => "D$rowCtr", 'data' => $results['action']);
            $cellsData[] = array('cell' => "E$rowCtr", 'data' => $results['history_data']);
        }

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


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

    //LETTER LOGIN REPORT
    /**
     * @Route("/report_login_tracker", name="report_login_tracker")
     */
    public function reportLoginTrackerAction() {

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

        $em = $this->getDoctrine()->getManager();
        $users = $em->getRepository('RxConnexionBundle:AccountUserEntity')->findBy(array(
            'isDeleted' => false,
            'isActive' => true
        ));

        $page_title = 'Login Tracker Report';
        return $this->render('@RxConnexion/Report/LoginTracker/index.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'users' => $users,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/loginTracker/loginTracker.js')
        ));
    }

    /**
     * @Route(
     *      "/login_tracker/preview/{date_from}/{date_to}/{user}",
     *      name = "report_login_tracker_preview"
     * )
     */
    public function reportLoginTracker_previewAction($date_from, $date_to, $user) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Login Tracker Preview'))) return $authService->redirectToHome();

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:AccountUserEntity')->reportLoginTracker(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'users' => $user
        ));

        $page_title = 'Login Tracker Report';
        return $this->render('@RxConnexion/Report/LoginTracker/preview.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'javascripts' => array('rxconnexion/admin/js/report/report_preview.js'),
            'records' => $records
        ));
    }

    /**
     * @Route(
     *      "/login_tracker/export_to_pdf/{date_from}/{date_to}/{user}",
     *      name = "report_login_tracker_export_to_pdf"
     * )
     */
    public function reportLoginTracker_export_to_pdfAction($date_from, $date_to, $user) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Login Tracker Pdf'))) return $authService->redirectToHome();

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:AccountUserEntity')->reportLoginTracker(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'users' => $user
        ));


        $page_title = 'Letter Tracker Report';
        $content = $this->renderView('@RxConnexion/Report/LoginTracker/preview.wkpdf.twig', array(
            'page_title' => $page_title,
            'records' => $records
        ));

        $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content, array(
            'orientation'=>'Landscape',
            'dpi' => 72,
            // 'disable-smart-shrinking',
            'zoom' => 'LINUX' == strtoupper(PHP_OS) ? 0.78 : 1
        ));

        $pdfResponse = array(
            'success' => true,
            'msg' => 'PDF was successfully generated.',
            'pdfBase64' => base64_encode($xml)
        );
        if($pdfResponse['success']) {
            $pdfContent = $pdfResponse['pdfBase64'];
            return new Response(base64_decode($pdfContent), 200, array(
                'Content-Type' => 'application/pdf',
                'Content-Disposition'   => 'attachment; filename="Login Tracker Report' . date('m/d/Y') . ' Details.pdf"'
            ));
        } else {
            $this->get('session')->getFlashBag()->set('error_messages', $pdfResponse['msg']);
            return $this->redirect($this->generateUrl('report_letter_tracker', 302));
        }
    }

    /**
     * @Route(
     *      "/login_tracker/export_to_excel/{date_from}/{date_to}/{user}",
     *      name = "report_login_tracker_export_to_excel"
     * )
     */
    public function reportLoginTracker_export_to_excelAction($date_from, $date_to, $user) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Login Tracker Excel'))) return $authService->redirectToHome();

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:AccountUserEntity')->reportLoginTracker(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'users' => $user
        ));


        $columnRange = range('A', 'Z');

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

        $columnRange = range('A', 'Z');
        $cellsData = array(
            array('cell' => 'A1', 'data' => 'Username'),
            array('cell' => 'B1', 'data' => 'Full Name'),
            array('cell' => 'C1', 'data' => 'Date'),
            array('cell' => 'D1', 'data' => 'Status'),
        );
        $rowCtr = 1;
        $totalCount = 0;

        foreach($records as $record) {

            $rowCtr++;
            $totalCount++;

            $cellsData[] = array('cell' => "A$rowCtr", 'data' => $record['username']);
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => $record['full_name']);
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => $record['date']);
            $cellsData[] = array('cell' => "D$rowCtr", 'data' => $record['statusLog']);
        }

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

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

    /**
     * @Route("/report_fax", name="report_fax")
     */
    public function reportFaxAction() {

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

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

        $em = $this->getDoctrine()->getManager();
        $branch = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->branchesForMultiple($userData);
        $company = $em->getRepository('RxConnexionBundle:CompanyEntity')->companiesForMultiple($userData);

        $page_title = 'Fax Report';
        return $this->render('@RxConnexion/Report/Fax/index.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'company' => $company,
            'branch' => $branch,
            'status' => FaxTranEntity::STATUS,
            'category' => FaxTranEntity::CATEGORY,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/fax/fax.js')
        ));
    }

    /**
     * @Route(
     *      "/report_fax/preview/{date_from}/{date_to}/{company}/{branch}/{status}/{category}",
     *      name = "report_report_fax_preview"
     * )
     */
    public function reportFax_previewAction($date_from, $date_to, $company, $branch, $status, $category) {

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

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:FaxTranEntity')->reportFax(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company,
            'branch' => $branch,
            'status' => $status,
            'category' => $category,
            'userData' => $userData
        ));

        $page_title = 'Fax Report';
        return $this->render('@RxConnexion/Report/Fax/preview.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'javascripts' => array('rxconnexion/admin/js/report/report_preview.js'),
            'records' => $records
        ));
    }

    /**
     * @Route(
     *      "/report_fax/export_to_pdf/{date_from}/{date_to}/{company}/{branch}/{status}/{category}",
     *      name = "report_report_fax_export_to_pdf"
     * )
     */
    public function reportFax_export_to_pdfAction($date_from, $date_to, $company, $branch, $status, $category) {

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

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:FaxTranEntity')->reportFax(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company,
            'branch' => $branch,
            'status' => $status,
            'category' => $category,
            'userData' => $userData
        ));


        $page_title = 'Fax Report';
        $content = $this->renderView('@RxConnexion/Report/Fax/preview.wkpdf.twig', array(
            'page_title' => $page_title,
            'records' => $records
        ));

        $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content, array(
            'orientation'=>'Landscape',
            'dpi' => 72,
            // 'disable-smart-shrinking',
            'zoom' => 'LINUX' == strtoupper(PHP_OS) ? 0.78 : 1
        ));

        $pdfResponse = array(
            'success' => true,
            'msg' => 'PDF was successfully generated.',
            'pdfBase64' => base64_encode($xml)
        );
        if($pdfResponse['success']) {
            $pdfContent = $pdfResponse['pdfBase64'];
            return new Response(base64_decode($pdfContent), 200, array(
                'Content-Type' => 'application/pdf',
                'Content-Disposition'   => 'attachment; filename="Fax Report' . date('m/d/Y') . ' Details.pdf"'
            ));
        } else {
            $this->get('session')->getFlashBag()->set('error_messages', $pdfResponse['msg']);
            return $this->redirect($this->generateUrl('report_fax', 302));
        }
    }

    /**
     * @Route(
     *      "/report_fax/export_to_excel/{date_from}/{date_to}/{company}/{branch}/{status}/{category}",
     *      name = "report_report_fax_export_to_excel"
     * )
     */
    public function reportFax_export_to_excelAction($date_from, $date_to, $company, $branch, $status, $category) {

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

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:FaxTranEntity')->reportFax(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company,
            'branch' => $branch,
            'status' => $status,
            'category' => $category,
            'userData' => $userData
        ));

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

        $columnRange = range('A', 'K');
        $cellsData = array(
            array('cell' => 'A1', 'data' => 'Fax Date'),
            array('cell' => 'B1', 'data' => 'Fax Category'),
            array('cell' => 'C1', 'data' => 'Fax #'),
            array('cell' => 'D1', 'data' => 'Company'),
            array('cell' => 'E1', 'data' => 'Branch'),
            array('cell' => 'F1', 'data' => 'Assigned To'),
            array('cell' => 'G1', 'data' => 'File Name'),
            array('cell' => 'H1', 'data' => 'Pages'),
            array('cell' => 'I1', 'data' => 'Duplicate'),
            array('cell' => 'J1', 'data' => 'Existing'),
            array('cell' => 'K1', 'data' => 'Unable to Process'),
        );
        $rowCtr = 1;
        $totalCount = 0;

        foreach($records as $record) {

            $rowCtr++;
            $totalCount++;

            $cellsData[] = array('cell' => "A$rowCtr", 'data' => $record['faxDate']);
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => $record['fax_category']);
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => $record['faxNo'] == null ? '8332624798' : $record['faxNo']);
            $cellsData[] = array('cell' => "D$rowCtr", 'data' => $record['companyDesc']);
            $cellsData[] = array('cell' => "E$rowCtr", 'data' => $record['branchDesc']);
            $cellsData[] = array('cell' => "F$rowCtr", 'data' => $record['assignTo']);
            $cellsData[] = array('cell' => "G$rowCtr", 'data' => $record['file_name']);
            $cellsData[] = array('cell' => "H$rowCtr", 'data' => $record['pages']);
            $cellsData[] = array('cell' => "I$rowCtr", 'data' => $record['isDuplicate']);
            $cellsData[] = array('cell' => "J$rowCtr", 'data' => $record['isExisting']);
            $cellsData[] = array('cell' => "K$rowCtr", 'data' => $record['isUnableToProcess']);
        }

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

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


    /**
     * @Route("/patient_cycle", name="report_patient_cycle")
     */
    public function reportPatientCycleAction() {

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

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

        $em = $this->getDoctrine()->getManager();
        $branch = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->branchesForMultiple($userData);
        $company = $em->getRepository('RxConnexionBundle:CompanyEntity')->companiesForMultiple($userData);

        $page_title = 'Patient Cycle Report';
        return $this->render('@RxConnexion/Report/PatientCycle/index.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'company' => $company,
            'branch' => $branch,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/patientCycle/patientCycle.js')
        ));
    }

    /**
     * @Route(
     *      "/patient_cycle/preview/{date_from}/{date_to}/{receive_date_from}/{receive_date_to}/{company}/{branch}",
     *      name = "report_patient_cycle_preview"
     * )
     */
    public function reportPatientCycle_previewAction($date_from, $date_to, $receive_date_from, $receive_date_to, $company, $branch) {

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

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientEntity')->reportPatientCycle(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'receive_date_from' => $receive_date_from,
            'receive_date_to' => $receive_date_to,
            'company' => $company,
            'branch' => $branch
        ));

        $page_title = 'Patient Cycle Report';
        return $this->render('@RxConnexion/Report/PatientCycle/preview.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'javascripts' => array('rxconnexion/admin/js/report/report_preview.js'),
            'records' => $records
        ));
    }

    /**
     * @Route(
     *      "/fax/export_to_excel/{date_from}/{date_to}/{company}/{branch}/{status}/{category}",
     *      name = "report_fax_export_to_excel"
     * )
     */
    public function reportPatientCycle_export_to_excelAction($date_from, $date_to, $company, $branch, $status, $category) {

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

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:FaxTranEntity')->reportFax(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company,
            'branch' => $branch,
            'status' => $status,
            'category' => $category,
            'userData' => $userData
        ));

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

        $columnRange = range('A', 'K');
        $cellsData = array(
            array('cell' => 'A1', 'data' => 'Fax Date'),
            array('cell' => 'B1', 'data' => 'Fax Category'),
            array('cell' => 'C1', 'data' => 'Fax #'),
            array('cell' => 'D1', 'data' => 'Company'),
            array('cell' => 'E1', 'data' => 'Branch'),
            array('cell' => 'F1', 'data' => 'Assigned To'),
            array('cell' => 'G1', 'data' => 'File Name'),
            array('cell' => 'H1', 'data' => 'Pages'),
            array('cell' => 'I1', 'data' => 'Duplicate'),
            array('cell' => 'J1', 'data' => 'Existing'),
            array('cell' => 'K1', 'data' => 'Unable to Process'),
        );
        $rowCtr = 1;
        $totalCount = 0;

        foreach($records as $record) {

            $rowCtr++;
            $totalCount++;

            $cellsData[] = array('cell' => "A$rowCtr", 'data' => $record['faxDate']);
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => $record['fax_category']);
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => $record['faxNo'] == null ? '8332624798' : $record['faxNo']);
            $cellsData[] = array('cell' => "D$rowCtr", 'data' => $record['companyDesc']);
            $cellsData[] = array('cell' => "E$rowCtr", 'data' => $record['branchDesc']);
            $cellsData[] = array('cell' => "F$rowCtr", 'data' => $record['assignTo']);
            $cellsData[] = array('cell' => "G$rowCtr", 'data' => $record['file_name']);
            $cellsData[] = array('cell' => "H$rowCtr", 'data' => $record['pages']);
            $cellsData[] = array('cell' => "I$rowCtr", 'data' => $record['isDuplicate']);
            $cellsData[] = array('cell' => "J$rowCtr", 'data' => $record['isExisting']);
            $cellsData[] = array('cell' => "K$rowCtr", 'data' => $record['isUnableToProcess']);
        }

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

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

    /**
     * @Route("/patient_with_different_branches", name="report_patient_with_different_branches")
     */
    public function reportPatientWithDifferentBranchesAction() {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Patient With Different Branches'))) return $authService->redirectToHome();

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

        $em = $this->getDoctrine()->getManager();
        $branch = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->branchesForMultiple($userData);
        $company = $em->getRepository('RxConnexionBundle:CompanyEntity')->companiesForMultiple($userData);

        $page_title = 'Patient With Different Branches (Encounter) Report';
        return $this->render('@RxConnexion/Report/PatientWithDifferentBranches/index.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'company' => $company,
            'branch' => $branch,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/patientCycle/patientCycle.js')
        ));
    }

    /**
     * @Route(
     *      "/patient_with_different_branches/preview/{date_from}/{date_to}",
     *      name = "report_patient_with_different_branches_preview"
     * )
     */
    public function reportPatientWithDifferentBranches_previewAction($date_from, $date_to) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Patient With Different Branches Preview'))) return $authService->redirectToHome();

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientChartEntity')->reportPatientWithDifferentBranches(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
        ));

        $page_title = 'Patient with different branches Report';
        return $this->render('@RxConnexion/Report/PatientWithDifferentBranches/preview.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'javascripts' => array('rxconnexion/admin/js/report/report_preview.js'),
            'records' => $records
        ));
    }

    /**
     * @Route(
     *      "/patient_with_different_branches/export_to_excel/{date_from}/{date_to}",
     *      name = "report_patient_with_different_branches_export_to_excel"
     * )
     */
    public function reportPatientWithDifferentBranches_export_to_excelAction($date_from, $date_to) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Patient With Different Branches Excel'))) return $authService->redirectToHome();

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientChartEntity')->reportPatientWithDifferentBranches(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
        ));

        $cellsData[] = array('cell' => 'A1', 'data' => 'Patient with different branches Report');

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

        foreach($records as $record) {

            $rowCtr++;
            $totalCount++;

            $cellsData[] = array('cell' => "A$rowCtr", 'data' => $record['referralDate']);
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => $record['patientName']);
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => $record['prevHealthFacility']);
            $cellsData[] = array('cell' => "D$rowCtr", 'data' => $record['latestHealthFacility']);
        }

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

        $page_title = 'Patient with different branches Report';
        return $this->export_to_excel($columnRange, $cellsData, $page_title);
    }

    /**
     * @Route("/patient_with_different_branches_invoice", name="report_patient_with_different_branches_invoice")
     */
    public function reportPatientWithDifferentBranchesInvoiceAction() {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Patient With Different Branches Invoice'))) return $authService->redirectToHome();

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

        $em = $this->getDoctrine()->getManager();
        $branch = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->branchesForMultiple($userData);
        $company = $em->getRepository('RxConnexionBundle:CompanyEntity')->companiesForMultiple($userData);

        $page_title = 'Patient with Different Branches (Invoice) Report';
        return $this->render('@RxConnexion/Report/PatientWithDifferentBranchesInvoice/index.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'company' => $company,
            'branch' => $branch,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/patientCycle/patientCycle.js')
        ));
    }

    /**
     * @Route(
     *      "/patient_with_different_branches/preview/{date_from}/{date_to}/{company}/{branch}/{status}/{category}",
     *      name = "report_fax_preview"
     * )
     */
    public function reportPatientWithDifferentBranchesInvoice_previewAction($date_from, $date_to) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Patient With Different Branches Invoice Preview'))) return $authService->redirectToHome();

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientBillingEntity')->reportPatientWithDifferentBranchesInvoice(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
        ));

        $page_title = 'Patient with different branches (Invoice) Report';
        return $this->render('@RxConnexion/Report/PatientWithDifferentBranchesInvoice/preview.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'javascripts' => array('rxconnexion/admin/js/report/report_preview.js'),
            'records' => $records
        ));
    }

    /**
     * @Route(
     *      "/patient_with_different_branches/export_to_excel/{date_from}/{date_to}/{company}/{branch}/{status}/{category}",
     *      name = "report_fax_export_to_excel"
     * )
     */
    public function reportPatientWithDifferentBranchesInvoice_export_to_excelAction($date_from, $date_to) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Patient With Different Branches Invoice Excel'))) return $authService->redirectToHome();

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientBillingEntity')->reportPatientWithDifferentBranchesInvoice(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
        ));


        $cellsData[] = array('cell' => 'A1', 'data' => 'Patient with different branches (Invoice) Report');

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

        foreach($records as $record) {

            $rowCtr++;
            $totalCount++;

            $cellsData[] = array('cell' => "A$rowCtr", 'data' => $record['referralDate']);
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => $record['patientName']);
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => $record['prevHealthFacility']);
            $cellsData[] = array('cell' => "D$rowCtr", 'data' => $record['latestHealthFacility']);
        }

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

        $page_title = 'Patient with different branches Report';
        return $this->export_to_excel($columnRange, $cellsData, $page_title);
    }


    /**
     * @Route("/file_report", name="report_file")
     */
    public function reportFileAction() {

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

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

        $em = $this->getDoctrine()->getManager();
        $branch = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->branchesForMultiple($userData);
        $company = $em->getRepository('RxConnexionBundle:CompanyEntity')->companiesForMultiple($userData);
        $fileTypes = $em->getRepository('RxConnexionBundle:FileTypeEntity')->fileTypesForMultiple();

        $page_title = 'File Report';
        return $this->render('@RxConnexion/Report/File/index.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'company' => $company,
            'branch' => $branch,
            'fileType' => $fileTypes,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/file/file.js')
        ));
    }

    /**
     * @Route(
     *      "/file_report/preview/{date_from}/{date_to}/{receive_date_from}/{receive_date_to}/{upload_date_from}/{upload_date_to}/{company}/{branch}/{file_type}",
     *      name = "report_file_preview"
     * )
     */
    public function reportFile_previewAction($date_from, $date_to, $receive_date_from, $receive_date_to, $upload_date_from, $upload_date_to, $company, $branch, $file_type) {

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

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientFileEntity')->reportFile(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'receive_date_from' => $receive_date_from,
            'receive_date_to' => $receive_date_to,
            'upload_date_from' => $upload_date_from,
            'upload_date_to' => $upload_date_to,
            'file_type' => $file_type,
            'company' => $company,
            'branch' => $branch
        ));

        $page_title = 'File Report';
        return $this->render('@RxConnexion/Report/File/preview.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'javascripts' => array('rxconnexion/admin/js/report/report_preview.js'),
            'records' => $records
        ));
    }


    /**
     * @Route("/fax_outbound_report", name="fax_outbound_report")
     */
    public function reportFaxOutBoundAction() {

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

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

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

        $page_title = 'Fax Outbound Report';
        return $this->render('@RxConnexion/Report/FaxOutbound/index.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'javascripts' => array('rxconnexion/admin/js/report/report.js')
        ));
    }

    /**
     * @Route(
     *      "/fax_outbound/preview/{date_from}/{date_to}/{type}",
     *      name = "fax_outbound_report_preview"
     * )
     */
    public function reportFaxOutBound_previewAction($date_from, $date_to, $type) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Fax Outbound Preview'))) return $authService->redirectToHome();

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository(FaxTranOutboundEntity::class)->reportFaxOutBound(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'type' => $type
        ));

        $page_title = 'Fax Outbound Report';
        return $this->render('@RxConnexion/Report/FaxOutbound/preview.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'javascripts' => array('rxconnexion/admin/js/report/report_preview.js'),
            'records' => $records,
            'type' => $type
        ));
    }


    //***************************************************************************************************//

    /* ===================================================================================== */
    /* =====================P R I V A T E   F U N C T I O N S=============================== */
    /* ===================================================================================== */


    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;
    }
}