<?php

namespace RxConnexionBundle\Controller;

use RxConnexionBundle\Entity\AccountUserEntity;
use RxConnexionBundle\Entity\FaxTranEntity;
use RxConnexionBundle\Entity\FaxTranOutboundEntity;
use RxConnexionBundle\Entity\HealthFacilityEntity;
use RxConnexionBundle\Entity\InventoryEntity;
use RxConnexionBundle\Entity\ItemCategoryEntity;
use RxConnexionBundle\Entity\ItemSubCategoryEntity;
use RxConnexionBundle\Entity\PatientChartEntity;
use RxConnexionBundle\Entity\PatientLetterEntity;
use RxConnexionBundle\Entity\PatientReferringHealthFacilityEntity;
use RxConnexionBundle\Entity\PatientReferringProviderEntity;
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}/{city}",
     *      name = "report_patient_preview"
     * )
     */
    public function patient_previewAction($company_id, $branch_id, $insurance, $status, $province_id, $postal_code_id, $referring_health_facility, $referring_provider, $city) {

        $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,
            'city' => $city,
            '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?v=1.0.1'),
            'records' => $records,
            'summary' => $summary,
            'active_count' => $status_count,
            'sum_branch' => $branch_id,
            'sum_stat' => $status,
            'sum_prov' => $province_id,
            'sum_post' => $postal_code_id,
            'userData' => $userData
        ));
    }

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

        $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,
            'patientReferringAffiliate' => $referring_health_facility,
            'patientReferringProvider' => $referring_provider,
            'city' => $city,
            '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}/{referring_health_facility}/{referring_provider}/{city}",
     *      name = "report_patient_export_to_excel"
     * )
     */
    public function patient_export_to_excelAction($company_id, $branch_id, $insurance, $status, $province_id, $postal_code_id, $referring_health_facility, $referring_provider, $city) {

        $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,
            'patientReferringAffiliate' => $referring_health_facility,
            'patientReferringProvider' => $referring_provider,
            'city' => $city,
            'userData' => $userData
        ));

        $columnRange = range('A', 'M');
        $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' => 'Phone No.'),
            array('cell' => 'H1', 'data' => 'Mobile No.'),
            array('cell' => 'I1', 'data' => 'Email Address'),
            array('cell' => 'J1', 'data' => 'Referring Physician'),
            array('cell' => 'K1', 'data' => 'Referring Affiliate'),
            array('cell' => 'L1', 'data' => 'Primary Clinician'),
            array('cell' => 'M1', 'data' => 'Patient Insurance'),
            array('cell' => 'N1', '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['phoneNo']);
            $cellsData[] = array('cell' => "H$rowCtr", 'data' => $record['mobileNo']);
            $cellsData[] = array('cell' => "I$rowCtr", 'data' => $record['email']);
            $cellsData[] = array('cell' => "J$rowCtr", 'data' => $record['referringProvider']);
            $cellsData[] = array('cell' => "K$rowCtr", 'data' => $record['referringHealthFacility']);
            $cellsData[] = array('cell' => "L$rowCtr", 'data' => $record['primaryClinician']);
            $cellsData[] = array('cell' => "M$rowCtr", 'data' => $record['patientInsurance']);
            $cellsData[] = array('cell' => "N$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' => 'Mobile No'),
            array('cell' => 'G1', 'data' => 'Company'),
            array('cell' => 'H1', 'data' => 'Branch'),
            array('cell' => 'I1', 'data' => 'Clinician'),
            array('cell' => 'J1', 'data' => 'Encounter Type'),
            array('cell' => 'K1', 'data' => 'Encounter Status'),
            array('cell' => 'L1', '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['mobileNo']);
            $cellsData[] = array('cell' => "G$rowCtr", 'data' => $record['companyDesc']);
            $cellsData[] = array('cell' => "H$rowCtr", 'data' => $record['branch']);
            $cellsData[] = array('cell' => "I$rowCtr", 'data' => $record['clinician']);
            $cellsData[] = array('cell' => "J$rowCtr", 'data' => $record['chartType']);
            $cellsData[] = array('cell' => "K$rowCtr", 'data' => $record['chartStatus']);
            $cellsData[] = array('cell' => "L$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);
        $service = $em->getRepository('RxConnexionBundle:ServiceEntity')->servicesForMultiple($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,
            'service' => $service,
            '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}/{service_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, $service_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,
            'service' => $service_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}/{service_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, $service_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,
            'service' => $service_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}/{service_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, $service_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,
            'service' => $service_id,
            'userData' => $userData
        ));

        $columnRange = range('A', 'O');
        $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' => 'Patient Services'),
            array('cell' => 'H1', 'data' => 'Referring Physician'),
            array('cell' => 'I1', 'data' => 'Referring Affiliate'),
            array('cell' => 'J1', 'data' => 'Encounter Type'),
            array('cell' => 'K1', 'data' => 'Encounter Status'),
            array('cell' => 'L1', 'data' => 'Letter Type'),
            array('cell' => 'M1', 'data' => 'Letter Status'),
            array('cell' => 'N1', 'data' => 'Agent'),
            array('cell' => 'O1', 'data' => 'Notes'),

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

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

            $rowCtr++;
            $totalCount++;
            $explodedPs = explode(',', $record['patientServices']);
            $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']);
            $newRow = $rowCtr;
            foreach ($explodedPs as $ps) {
                $patientService = explode('|', $ps);
                array('cell' => "G$newRow", 'data' => isset($patientService[1]) ? $patientService[1] : '');
                $newRow++;
            }
            $cellsData[] = array('cell' => "H$rowCtr", 'data' => $record['referring_physician']);
            $cellsData[] = array('cell' => "I$rowCtr", 'data' => $record['referring_affiliate']);
            $cellsData[] = array('cell' => "J$rowCtr", 'data' => $record['chartType']);
            $cellsData[] = array('cell' => "K$rowCtr", 'data' => $record['chartStatus']);
            $cellsData[] = array('cell' => "L$rowCtr", 'data' => $record['letterType']);
            $cellsData[] = array('cell' => "M$rowCtr", 'data' => $record['letterStatus']);
            $cellsData[] = array('cell' => "N$rowCtr", 'data' => $record['sales_agent']);
            $cellsData[] = array('cell' => "O$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);
        $service = $em->getRepository('RxConnexionBundle:ServiceEntity')->servicesForMultiple($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,
            'service' => $service,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/referralMarketing/referral_marketing.js?v=1.0.3')
        ));
    }

    /**
     * @Route(
     *      "/referral_marketing/preview/{date_from}/{date_to}/{company}/{branch}/{service}/{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, $service, $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,
            'service' => $service,
            '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}/{service}/{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, $service, $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}/{service}/{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, $service, $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,
            'service' => $service,
            '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', 'Service(s)');
        $activeSheet->setCellValue('F1', 'Referral Date');
        $activeSheet->setCellValue('G1', 'Receive Date');
        $activeSheet->setCellValue('H1', 'Encounter Type');
        $activeSheet->setCellValue('I1', 'Encounter Status');
        $activeSheet->setCellValue('J1', 'Sold');
        $activeSheet->setCellValue('K1', 'Agent');
        $activeSheet->setCellValue('L1', 'Rate');
        $activeSheet->setCellValue('M1', 'Total');
        $activeSheet->getStyle('A1:M1')->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('M'.$rowCtr, $lastHealthFacility['total']);
                    $activeSheet->mergeCells('C'.$rowCtr.':L'.$rowCtr);
                    $activeSheet->getStyle('B'.$rowCtr.':M'.$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('M'.$rowCtr, $lastHealthFacility['total']);
                    $activeSheet->mergeCells('C'.$rowCtr.':L'.$rowCtr);
                    $activeSheet->getStyle('B'.$rowCtr.':M'.$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('M'.$rowCtr, $lastCompany['total']);
                    $activeSheet->mergeCells('B'.$rowCtr.':L'.$rowCtr);
                    $activeSheet->getStyle('A'.$rowCtr.':M'.$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('M'.$rowCtr, $lastProvider['total']);
                    $activeSheet->mergeCells('D'.$rowCtr.':L'.$rowCtr);
                    $activeSheet->getStyle('C'.$rowCtr.':M'.$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('M'.$rowCtr, $lastHealthFacility['total']);
                    $activeSheet->mergeCells('C'.$rowCtr.':L'.$rowCtr);
                    $activeSheet->getStyle('B'.$rowCtr.':M'.$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']++;

            $explodedPs = explode(',', $record['patientServices']);
            $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['referral_date']);
            $activeSheet->setCellValue('G'.$rowCtr, $record['receive_date']);
            $activeSheet->setCellValue('H'.$rowCtr, $record['chartType']);
            $activeSheet->setCellValue('I'.$rowCtr, $record['chartStatus']);
            $activeSheet->setCellValue('J'.$rowCtr, $record['sold']);
            $activeSheet->setCellValue('K'.$rowCtr, $record['agent']);
            $activeSheet->setCellValue('L'.$rowCtr, $record['cpapSetupSold']);
            $activeSheet->setCellValue('M'.$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();
	    $branches = $em->getRepository(AccountUserEntity::class)->productivityReport([
		    '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'),
            'branches' => $branches,
            'dateFrom' => $date_from,
            'dateTo' => $date_to,
            'branchId' => $branch_id,
            'examTypeId' => $exam_type_id
        ));
    }

    /**
     * @Route(
     *      "/productivity/preview/old/{date_from}/{date_to}/{branch_id}/{exam_type_id}/{clinician}",
     *      name = "report_productivity_preview_old"
     * )
     */
    public function productivity_preview_oldAction($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();
	    $records = $em->getRepository(PatientChartEntity::class)->productivityReport([
		    '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.old.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,
            '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/old/{date_from}/{date_to}/{branch_id}/{exam_type_id}/{clinician}",
     *      name = "report_productivity_export_to_excel"
     * )
     */
    public function productivity_export_to_excel_oldAction($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;
    }

    /**
     * @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(['Admin Report Productivity Clinical Excel'])) return $authService->redirectToHome();

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

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

	    $phpExcelObject = $this->get('phpexcel')->createPHPExcelObject();
	    $activeSheet = $phpExcelObject->setActiveSheetIndex(0);
	    $activeSheet->setCellValue('A1', 'PRODUCTIVITY REPORT');
	    $activeSheet->setCellValue('B1', str_replace('-', '/', $date_from) . ' - ' . str_replace('-', '/', $date_to));

	    $cellStyles = ['fill' => [['A1:B1', 'ADD8E6']],'borders' => [['A1:B1']]];

	    $branches = $em->getRepository(AccountUserEntity::class)->productivityReport([
		    'date_from'      => $date_from,
		    'date_to'        => $date_to,
		    'branch'         => $branch_id,
		    'encounter_type' => $exam_type_id,
		    'clinician'      => $clinician,
	    ]);


	    $rowCtr = 1;
	    foreach ($branches as $branch) {
		    $columnCtr = "A";
		    $rowCtr += 2;

		    $activeSheet->setCellValue($columnCtr . $rowCtr, strtoupper($branch['name']))->getStyle($columnCtr . $rowCtr)->getFont()->setBold(TRUE);
		    $cellStyles['fill'][] = [$columnCtr . $rowCtr . ':' . $columnCtr . 'Z' . $rowCtr, 'C3CFEF'];

		    $rowCtr++;
		    $activeSheet->setCellValue($columnCtr . $rowCtr, 'Activity / Services')->getStyle('A' . $rowCtr)->getFont()->setBold(TRUE);
		    $cellStyles['fill'][] = [$columnCtr . $rowCtr . ':' . $columnCtr . 'Z' . $rowCtr, 'ADD8E6'];
		    $cellStyles['borders'][] = [$columnCtr . $rowCtr . ':' . $columnCtr . 'Z' . $rowCtr];

		    foreach ($branch['users'] as $user) {
			    $columnCtr++;
			    $activeSheet->setCellValue($columnCtr . $rowCtr, $user['name'])->getStyle($columnCtr . $rowCtr)->getFont()->setBold(TRUE);
		    }
		    $columnCtr++;
		    $activeSheet->setCellValue($columnCtr . $rowCtr, 'Total')->getStyle($columnCtr . $rowCtr)->getFont()->setBold(TRUE);
		    $cellStyles['fill'][] = [$columnCtr . $rowCtr, 'ADD8E6'];
		    $cellStyles['borders'][] = [$columnCtr . $rowCtr];

		    foreach ($branch['actions'] as $action) {
			    $rowCtr++;
			    $columnCtr = "A";
			    $activeSheet->setCellValue($columnCtr . $rowCtr, $action['description'])->getStyle($columnCtr . $rowCtr)->getFont()->setBold(TRUE);
			    $cellStyles['fill'][] = [$columnCtr . $rowCtr, '9396B5'];
			    $cellStyles['borders'][] = [$columnCtr . $rowCtr];

			    foreach ($branch['users'] as $user) {
				    $columnCtr++;
				    $found = FALSE;
				    foreach ($branch['data'] as $data) {
					    if ($data['user_id'] == $user['id'] && $data['action'] == $action['description']) {
						    $found = TRUE;
						    $activeSheet->setCellValue($columnCtr . $rowCtr, $data['total_count'] . ' (' . (round($data['total_count'] / $action['total'] * 100, 2)) . '%)');
					    }
				    }
				    if (!$found) {
					    $activeSheet->setCellValue($columnCtr . $rowCtr, "0");
				    }
			    }
			    $columnCtr++;
			    $activeSheet->setCellValue($columnCtr . $rowCtr, $action['total']);


		    }

		    $rowCtr++;
		    $columnCtr = "A";
		    $activeSheet->setCellValue($columnCtr . $rowCtr, 'TOTAL')->getStyle($columnCtr . $rowCtr)->getFont()->setBold(TRUE);;
		    foreach ($branch['users'] as $user) {
			    $columnCtr++;
			    $userTotal = 0;
			    foreach ($branch['data'] as $data) {
				    if ($data['user_id'] == $user['id']) {
					    $userTotal += $data['total_count'];
				    }
			    }
			    $activeSheet->setCellValue($columnCtr . $rowCtr, $userTotal . ' (' . (round($userTotal / $branch['total'] * 100, 2)) . '%)')->getStyle($columnCtr . $rowCtr)->getFont()->setBold(TRUE);;
		    }
		    $columnCtr++;
		    $activeSheet->setCellValue($columnCtr . $rowCtr, $branch['total'])->getStyle($columnCtr . $rowCtr)->getFont()->setBold(TRUE);;

	    }

	    foreach ($cellStyles['fill'] as $fill) {
		    $activeSheet->getStyle($fill[0])->applyFromArray([
			    'fill'    => [
				    'type'  => \PHPExcel_Style_Fill::FILL_SOLID,
				    'color' => ['rgb' => $fill[1]]
			    ]
		    ]);
	    }
	    foreach ($cellStyles['borders'] as $borders) {
		    $activeSheet->getStyle($borders[0])->applyFromArray([
			    'borders' => [
				    'allborders' => [
					    'style' => \PHPExcel_Style_Border::BORDER_THIN
				    ]
			    ]
		    ]);
	    }

	    $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?v=1.0.1')
        ));
    }

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

        $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,
            'status' => $status,
            'city' => $city,
        ));

        $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,
            'city' => $city,
        ));
    }

    /**
     * @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?v=1.0.1', '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,
        ));*/

        $invoiceSummary = array();
        $financingSummary = array();
        foreach ($records as $record) {
            if(!in_array($record['healthFacilityAddress'], array('Finance Underwriting & Investment Capital', 'Canpay Medical Inc.'))) {
                $exist = $this->in_array_assoc($record['healthFacilityAddress_id'], 'healthFacilityAddress_id', $invoiceSummary);
                if ($exist['exist']) {
                    $invoiceSummary[$exist['key']]['totalAmtDue'] += $record['amtDue_forTotal'];
                    $invoiceSummary[$exist['key']]['totalCount'] += 1;
                } else {
                    $invoiceSummary[] = array(
                        'healthFacilityAddress_id' => $record['healthFacilityAddress_id'],
                        'healthFacility' => $record['healthFacilityAddress'],
                        'totalAmtDue' => $record['amtDue_forTotal'],
                        'totalCount' => 1,
                    );
                }
            } else {
                $exist = $this->in_array_assoc($record['healthFacilityAddress_id'], 'healthFacilityAddress_id', $financingSummary);
                if ($exist['exist']) {
                    $financingSummary[$exist['key']]['totalAmtDue'] += $record['amtDue_forTotal'];
                    $financingSummary[$exist['key']]['totalCount'] += 1;
                } else {
                    $financingSummary[] = array(
                        'healthFacilityAddress_id' => $record['healthFacilityAddress_id'],
                        'healthFacility' => $record['healthFacilityAddress'],
                        'totalAmtDue' => $record['amtDue_forTotal'],
                        'totalCount' => 1,
                    );
                }
            }
        }

        $paymentSummary = array();
        foreach ($records as $record) {
            $exist = $this->in_array_assoc($record['healthFacilityAddress_id'], 'healthFacilityAddress_id', $paymentSummary);
            if($exist['exist']){
                $paymentSummary[$exist['key']]['totalPaymentAmount'] += $record['totalPaymentAmount'];
                $paymentSummary[$exist['key']]['count'] += 1;
            } else {
                $paymentSummary[] = array(
                    'healthFacilityAddress_id' => $record['healthFacilityAddress_id'],
                    'healthFacilityAddress' => $record['healthFacilityAddress'],
                    'totalPaymentAmount' => $record['totalPaymentAmount'],
                    'count' => 1,
                );
            }
        }

        $paymentBreakdown = array();
        foreach ($records as $record) {
            if(!is_null($record['ppForBreakdown_breakdown']) && !empty($record['ppForBreakdown_breakdown'])) {
                $breakdownArray = explode(',', $record['ppForBreakdown_breakdown']);
                foreach ($breakdownArray as $key => $item) {
                    $breakdown = explode('~', $item);

                    $paymentType = $breakdown[0];
                    $transactionCount = $breakdown[1];
                    $totalAmt = $breakdown[2];

                    $exist = $this->in_array_assoc($paymentType, 'paymentType', $paymentBreakdown);
                    if ($exist['exist']) {
                        $paymentBreakdown[$exist['key']]['transactionCount'] += $transactionCount;
                        $paymentBreakdown[$exist['key']]['totalAmt'] += $totalAmt;
                        $paymentBreakdown[$exist['key']]['invoices'][] = $record['invoiceNo'];
                    } else {
                        $paymentBreakdown[] = array(
                            'paymentType' => $paymentType,
                            'transactionCount' => $transactionCount,
                            'totalAmt' => $totalAmt,
                            'invoices' => array($record['invoiceNo'])
                        );
                    }
                }
            }
        }

        $longTermSummary = array();
        $longTermSummary_void = array();
        foreach ($records as $record) {
            if(!is_null($record['longTermCount']) && !empty($record['longTermCount'])) {
                $exist = $this->in_array_assoc($record['healthFacilityAddress_id'], 'billingBranchId', $longTermSummary);
                if ($exist['exist']) {
                    $longTermSummary[$exist['key']]['price'] += $record['pbbForLongTerm_price'];
                    $longTermSummary[$exist['key']]['cost'] += $record['pbbForLongTerm_cost'];
                    $longTermSummary[$exist['key']]['longTermCount'] += $record['longTermCount'];
                } else {
                    $longTermSummary[] = array(
                        'billingBranchId' => $record['healthFacilityAddress_id'],
                        'billingBranch' => $record['healthFacilityAddress'],
                        'price' => $record['pbbForLongTerm_price'],
	                    'cost' => $record['pbbForLongTerm_cost'],
	                    'longTermCount' => $record['longTermCount'],
                    );
                }
            }
            if(!is_null($record['longTermCount_void']) && !empty($record['longTermCount_void'])) {
                $exist = $this->in_array_assoc($record['healthFacilityAddress_id'], 'billingBranchId', $longTermSummary_void);
                if ($exist['exist']) {
                    $longTermSummary_void[$exist['key']]['price'] += $record['pbbForLongTerm_price_void'];
                    $longTermSummary_void[$exist['key']]['longTermCount'] += $record['longTermCount_void'];
                } else {
                    $longTermSummary_void[] = array(
                        'billingBranchId' => $record['healthFacilityAddress_id'],
                        'billingBranch' => $record['healthFacilityAddress'],
                        'price' => $record['pbbForLongTerm_price_void'],
                        'longTermCount' => $record['longTermCount_void'],
                    );
                }
            }
        }

        $rentToOwnSummary = array();
        $rentToOwnSummary_void = array();
        foreach ($records as $record) {
            if(!is_null($record['rentToCount']) && !empty($record['rentToCount'])) {
                $exist = $this->in_array_assoc($record['healthFacilityAddress_id'], 'billingBranchId', $rentToOwnSummary);
                if ($exist['exist']) {
	                $rentToOwnSummary[$exist['key']]['price'] += $record['pbbForRentToOwn_price'];
	                $rentToOwnSummary[$exist['key']]['cost'] += $record['pbbForRentToOwn_cost'];
	                $rentToOwnSummary[$exist['key']]['rentToCount'] += $record['rentToCount'];
                } else {
                    $rentToOwnSummary[] = array(
                        'billingBranchId' => $record['healthFacilityAddress_id'],
                        'billingBranch' => $record['healthFacilityAddress'],
                        'price' => $record['pbbForRentToOwn_price'],
	                    'cost' => $record['pbbForRentToOwn_cost'],
	                    'rentToCount' => $record['rentToCount'],
                    );
                }
            }
            if(!is_null($record['rentToCount_void']) && !empty($record['rentToCount_void'])) {
                $exist = $this->in_array_assoc($record['healthFacilityAddress_id'], 'billingBranchId', $rentToOwnSummary_void);
                if ($exist['exist']) {
                    $rentToOwnSummary_void[$exist['key']]['price'] += $record['pbbForRentToOwn_price_void'];
                    $rentToOwnSummary_void[$exist['key']]['rentToCount'] += $record['rentToCount_void'];
                } else {
                    $rentToOwnSummary_void[] = array(
                        'billingBranchId' => $record['healthFacilityAddress_id'],
                        'billingBranch' => $record['healthFacilityAddress'],
                        'price' => $record['pbbForRentToOwn_price_void'],
                        'rentToCount' => $record['rentToCount_void'],
                    );
                }
            }
        }

        $accessorySummary = array();
        $accessorySummary_void = array();
        foreach ($records as $record) {
        	if(in_array($record['healthFacilityAddress'], ['Finance Underwriting & Investment Capital', 'Canpay Medical Inc.'])) continue;
            if(!is_null($record['accessoryCount']) && !empty($record['accessoryCount'])) {
                $exist = $this->in_array_assoc($record['healthFacilityAddress_id'], 'billingBranchId', $accessorySummary);
                if ($exist['exist']) {
                    $accessorySummary[$exist['key']]['price'] += $record['pbbForAccessory_price'];
                    $accessorySummary[$exist['key']]['cost'] += $record['pbbForAccessory_cost'];
                    $accessorySummary[$exist['key']]['accessoryCount'] += $record['accessoryCount'];
                } else {
                    $accessorySummary[] = array(
                        'billingBranchId' => $record['healthFacilityAddress_id'],
                        'billingBranch' => $record['healthFacilityAddress'],
                        'price' => $record['pbbForAccessory_price'],
                        'cost' => $record['pbbForAccessory_cost'],
                        'accessoryCount' => $record['accessoryCount'],
                    );
                }
            }
            if(!is_null($record['accessoryCount_void']) && !empty($record['accessoryCount_void'])) {
                $exist = $this->in_array_assoc($record['healthFacilityAddress_id'], 'billingBranchId', $accessorySummary_void);
                if ($exist['exist']) {
                    $accessorySummary_void[$exist['key']]['price'] += $record['pbbForAccessory_price_void'];
                    $accessorySummary_void[$exist['key']]['accessoryCount'] += $record['accessoryCount_void'];
                } else {
                    $accessorySummary_void[] = array(
                        'billingBranchId' => $record['healthFacilityAddress_id'],
                        'billingBranch' => $record['healthFacilityAddress'],
                        'price' => $record['pbbForAccessory_price_void'],
                        'accessoryCount' => $record['accessoryCount_void'],
                    );
                }
            }
        }

        $cpapPackageSummary = array();
        $cpapPackageSummary_void = array();
        foreach ($records as $record) {
	        if(in_array($record['healthFacilityAddress'], ['Finance Underwriting & Investment Capital', 'Canpay Medical Inc.'])) continue;
	        if(!is_null($record['cpapPackageCount']) && !empty($record['cpapPackageCount'])) {
                $exist = $this->in_array_assoc($record['healthFacilityAddress_id'], 'billingBranchId', $cpapPackageSummary);
                if ($exist['exist']) {
                    $cpapPackageSummary[$exist['key']]['price'] += $record['pbbForCpapPackage_price'];
                    $cpapPackageSummary[$exist['key']]['cost'] += $record['pbbForCpapPackage_cost'];
                    $cpapPackageSummary[$exist['key']]['cpapPackageCount'] += $record['cpapPackageCount'];
                } else {
                    $cpapPackageSummary[] = array(
                        'billingBranchId' => $record['healthFacilityAddress_id'],
                        'billingBranch' => $record['healthFacilityAddress'],
                        'price' => $record['pbbForCpapPackage_price'],
	                    'cost' => $record['pbbForCpapPackage_cost'],
	                    'cpapPackageCount' => $record['cpapPackageCount'],
                    );
                }
            }
            if(!is_null($record['cpapPackageCount_void']) && !empty($record['cpapPackageCount_void'])) {
                $exist = $this->in_array_assoc($record['healthFacilityAddress_id'], 'billingBranchId', $cpapPackageSummary_void);
                if ($exist['exist']) {
                    $cpapPackageSummary_void[$exist['key']]['price'] += $record['pbbForCpapPackage_price_void'];
                    $cpapPackageSummary_void[$exist['key']]['cpapPackageCount'] += $record['cpapPackageCount_void'];
                } else {
                    $cpapPackageSummary_void[] = array(
                        'billingBranchId' => $record['healthFacilityAddress_id'],
                        'billingBranch' => $record['healthFacilityAddress'],
                        'price' => $record['pbbForCpapPackage_price_void'],
                        'cpapPackageCount' => $record['cpapPackageCount_void'],
                    );
                }
            }
        }

        $medicalSuppliesSummary = array();
        $medicalSuppliesSummary_void = array();
        foreach ($records as $record) {
	        if(in_array($record['healthFacilityAddress'], ['Finance Underwriting & Investment Capital', 'Canpay Medical Inc.'])) continue;
	        if(!is_null($record['medicalSuppliesCount']) && !empty($record['medicalSuppliesCount'])) {
                $exist = $this->in_array_assoc($record['healthFacilityAddress_id'], 'billingBranchId', $medicalSuppliesSummary);
                if ($exist['exist']) {
                    $medicalSuppliesSummary[$exist['key']]['price'] += $record['pbbForMedicalSupplies_price'];
                    $medicalSuppliesSummary[$exist['key']]['cost'] += $record['pbbForMedicalSupplies_cost'];
                    $medicalSuppliesSummary[$exist['key']]['medicalSuppliesCount'] += $record['medicalSuppliesCount'];
                } else {
                    $medicalSuppliesSummary[] = array(
                        'billingBranchId' => $record['healthFacilityAddress_id'],
                        'billingBranch' => $record['healthFacilityAddress'],
                        'price' => $record['pbbForMedicalSupplies_price'],
	                    'cost' => $record['pbbForMedicalSupplies_cost'],
	                    'medicalSuppliesCount' => $record['medicalSuppliesCount'],
                    );
                }
            }
            if(!is_null($record['medicalSuppliesCount_void']) && !empty($record['medicalSuppliesCount_void'])) {
                $exist = $this->in_array_assoc($record['healthFacilityAddress_id'], 'billingBranchId', $medicalSuppliesSummary_void);
                if ($exist['exist']) {
                    $medicalSuppliesSummary_void[$exist['key']]['price'] += $record['pbbForMedicalSupplies_price_void'];
                    $medicalSuppliesSummary_void[$exist['key']]['medicalSuppliesCount'] += $record['medicalSuppliesCount_void'];
                } else {
                    $medicalSuppliesSummary_void[] = array(
                        'billingBranchId' => $record['healthFacilityAddress_id'],
                        'billingBranch' => $record['healthFacilityAddress'],
                        'price' => $record['pbbForMedicalSupplies_price_void'],
                        'medicalSuppliesCount' => $record['medicalSuppliesCount_void'],
                    );
                }
            }
        }

        $partOfCpapPackageSummary = array();
        $partOfCpapPackageSummary_void = array();
        foreach ($records as $record) {
	        if(in_array($record['healthFacilityAddress'], ['Finance Underwriting & Investment Capital', 'Canpay Medical Inc.'])) continue;
	        if(!is_null($record['partOfCpapPackageCount']) && !empty($record['partOfCpapPackageCount'])) {
                $exist = $this->in_array_assoc($record['healthFacilityAddress_id'], 'billingBranchId', $partOfCpapPackageSummary);
                if ($exist['exist']) {
                    $partOfCpapPackageSummary[$exist['key']]['price'] += $record['pbbForPartOfCpapPackage_price'];
                    $partOfCpapPackageSummary[$exist['key']]['cost'] += $record['pbbForPartOfCpapPackage_cost'];
                    $partOfCpapPackageSummary[$exist['key']]['partOfCpapPackageCount'] += $record['partOfCpapPackageCount'];
                } else {
                    $partOfCpapPackageSummary[] = array(
                        'billingBranchId' => $record['healthFacilityAddress_id'],
                        'billingBranch' => $record['healthFacilityAddress'],
                        'price' => $record['pbbForPartOfCpapPackage_price'],
                        'cost' => $record['pbbForPartOfCpapPackage_cost'],
                        'partOfCpapPackageCount' => $record['partOfCpapPackageCount'],
                    );
                }
            }
            if(!is_null($record['partOfCpapPackageCount_void']) && !empty($record['partOfCpapPackageCount_void'])) {
                $exist = $this->in_array_assoc($record['healthFacilityAddress_id'], 'billingBranchId', $partOfCpapPackageSummary_void);
                if ($exist['exist']) {
                    $partOfCpapPackageSummary_void[$exist['key']]['price'] += $record['pbbForPartOfCpapPackage_price_void'];
                    $partOfCpapPackageSummary_void[$exist['key']]['partOfCpapPackageCount'] += $record['partOfCpapPackageCount_void'];
                } else {
                    $partOfCpapPackageSummary_void[] = array(
                        'billingBranchId' => $record['healthFacilityAddress_id'],
                        'billingBranch' => $record['healthFacilityAddress'],
                        'price' => $record['pbbForPartOfCpapPackage_price_void'],
                        'partOfCpapPackageCount' => $record['partOfCpapPackageCount_void'],
                    );
                }
            }
        }

        $cpapTrialSummary = array();
        $cpapTrialSummary_void = array();
        foreach ($records as $record) {
	        if(in_array($record['healthFacilityAddress'], ['Finance Underwriting & Investment Capital', 'Canpay Medical Inc.'])) continue;
	        if(!is_null($record['cpapTrialCount']) && !empty($record['cpapTrialCount'])) {
                $exist = $this->in_array_assoc($record['healthFacilityAddress_id'], 'billingBranchId', $cpapTrialSummary);
                if ($exist['exist']) {
                    $cpapTrialSummary[$exist['key']]['price'] += $record['pbbForCpapTrial_price'];
                    $cpapTrialSummary[$exist['key']]['cost'] += $record['pbbForCpapTrial_cost'];
                    $cpapTrialSummary[$exist['key']]['cpapTrialCount'] += $record['cpapTrialCount'];
                } else {
                    $cpapTrialSummary[] = array(
                        'billingBranchId' => $record['healthFacilityAddress_id'],
                        'billingBranch' => $record['healthFacilityAddress'],
                        'price' => $record['pbbForCpapTrial_price'],
                        'cost' => $record['pbbForCpapTrial_cost'],
                        'cpapTrialCount' => $record['cpapTrialCount'],
                    );
                }
            }
            if(!is_null($record['cpapTrialCount_void']) && !empty($record['cpapTrialCount_void'])) {
                $exist = $this->in_array_assoc($record['healthFacilityAddress_id'], 'billingBranchId', $cpapTrialSummary_void);
                if ($exist['exist']) {
                    $cpapTrialSummary_void[$exist['key']]['price'] += $record['pbbForCpapTrial_price_void'];
                    $cpapTrialSummary_void[$exist['key']]['cpapTrialCount'] += $record['cpapTrialCount_void'];
                } else {
                    $cpapTrialSummary_void[] = array(
                        'billingBranchId' => $record['healthFacilityAddress_id'],
                        'billingBranch' => $record['healthFacilityAddress'],
                        'price' => $record['pbbForCpapTrial_price_void'],
                        'cpapTrialCount' => $record['cpapTrialCount_void'],
                    );
                }
            }
        }



        $page_title = 'Invoice Report ' . $date_from . ' to ' . $date_to;
        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' => $records2,
            'dateFrom' => $date_from,
            'dateTo' => $date_to,
            'paymentSummary' => $paymentSummary,
            'invoiceSummary' => $invoiceSummary,
            'financingSummary' => $financingSummary,

            'accessorySummary' => $accessorySummary,
            'accessorySummary_void' => $accessorySummary_void,

            'cpapPackageSummary' => $cpapPackageSummary,
            'cpapPackageSummary_void' => $cpapPackageSummary_void,

            'medicalSuppliesSummary' => $medicalSuppliesSummary,
            'medicalSuppliesSummary_void' => $medicalSuppliesSummary_void,

            'longTermSummary' => $longTermSummary,
            'longTermSummary_void' => $longTermSummary_void,

            'rentToOwnSummary' => $rentToOwnSummary,
            'rentToOwnSummary_void' => $rentToOwnSummary_void,

            'partOfCpapPackageSummary' => $partOfCpapPackageSummary,
            'partOfCpapPackageSummary_void' => $partOfCpapPackageSummary_void,

            'cpapTrialSummary' => $cpapTrialSummary,
            'cpapTrialSummary_void' => $cpapTrialSummary_void,

            'paymentBreakdown' => $paymentBreakdown,
        ));
    }

    private function in_array_assoc($val, $key, $arr) {

        $in_array = array('exist' => false, 'key' => 0);

        foreach($arr as $rowKey => $row) {
            if($row[$key]==$val) {
                $in_array['exist'] = true;
                $in_array['key'] = $rowKey;
                break;
            }
        }

        return $in_array;
    }

    private function in_array_assoc_multiple($val_keys, $arr) {

	    $in_array = array('exist' => false, 'key' => 0);

	    foreach($arr as $rowKey => $row) {
		    $exist = true;
		    foreach ($val_keys as $vk) {
			    if($row[$vk['key']] != $vk['val']) {
				    $exist = false;
				    break;
			    }
		    }
		    if($exist) {
			    $in_array['exist'] = true;
			    $in_array['key'] = $rowKey;
			    break;
		    }
	    }

	    return $in_array;
    }

    /**
     * @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,
        ));*/

        $invoiceSummary = array();
        $financingSummary = array();
        foreach ($records as $record) {
            if(!in_array($record['healthFacilityAddress'], array('Finance Underwriting & Investment Capital', 'Canpay Medical Inc.'))) {
                $exist = $this->in_array_assoc($record['healthFacilityAddress_id'], 'healthFacilityAddress_id', $invoiceSummary);
                if ($exist['exist']) {
                    $invoiceSummary[$exist['key']]['totalAmtDue'] += $record['amtDue_forTotal'];
                    $invoiceSummary[$exist['key']]['totalCount'] += 1;
                } else {
                    $invoiceSummary[] = array(
                        'healthFacilityAddress_id' => $record['healthFacilityAddress_id'],
                        'healthFacility' => $record['healthFacilityAddress'],
                        'totalAmtDue' => $record['amtDue_forTotal'],
                        'totalCount' => 1,
                    );
                }
            } else {
                $exist = $this->in_array_assoc($record['healthFacilityAddress_id'], 'healthFacilityAddress_id', $financingSummary);
                if ($exist['exist']) {
                    $financingSummary[$exist['key']]['totalAmtDue'] += $record['amtDue_forTotal'];
                    $financingSummary[$exist['key']]['totalCount'] += 1;
                } else {
                    $financingSummary[] = array(
                        'healthFacilityAddress_id' => $record['healthFacilityAddress_id'],
                        'healthFacility' => $record['healthFacilityAddress'],
                        'totalAmtDue' => $record['amtDue_forTotal'],
                        'totalCount' => 1,
                    );
                }
            }
        }

        $paymentSummary = array();
        foreach ($records as $record) {
            $exist = $this->in_array_assoc($record['healthFacilityAddress_id'], 'healthFacilityAddress_id', $paymentSummary);
            if($exist['exist']){
                $paymentSummary[$exist['key']]['totalPaymentAmount'] += $record['totalPaymentAmount'];
                $paymentSummary[$exist['key']]['count'] += 1;
            } else {
                $paymentSummary[] = array(
                    'healthFacilityAddress_id' => $record['healthFacilityAddress_id'],
                    'healthFacilityAddress' => $record['healthFacilityAddress'],
                    'totalPaymentAmount' => $record['totalPaymentAmount'],
                    'count' => 1,
                );
            }
        }

        $paymentBreakdown = array();
        foreach ($records as $record) {
            if(!is_null($record['ppForBreakdown_breakdown']) && !empty($record['ppForBreakdown_breakdown'])) {
                $breakdownArray = explode(',', $record['ppForBreakdown_breakdown']);
                foreach ($breakdownArray as $key => $item) {
                    $breakdown = explode('~', $item);

                    $paymentType = $breakdown[0];
                    $transactionCount = $breakdown[1];
                    $totalAmt = $breakdown[2];

                    $exist = $this->in_array_assoc($paymentType, 'paymentType', $paymentBreakdown);
                    if ($exist['exist']) {
                        $paymentBreakdown[$exist['key']]['transactionCount'] += $transactionCount;
                        $paymentBreakdown[$exist['key']]['totalAmt'] += $totalAmt;
                        $paymentBreakdown[$exist['key']]['invoices'][] = $record['invoiceNo'];
                    } else {
                        $paymentBreakdown[] = array(
                            'paymentType' => $paymentType,
                            'transactionCount' => $transactionCount,
                            'totalAmt' => $totalAmt,
                            'invoices' => array($record['invoiceNo'])
                        );
                    }
                }
            }
        }

        $longTermSummary = array();
        $longTermSummary_void = array();
        foreach ($records as $record) {
            if(!is_null($record['longTermCount']) && !empty($record['longTermCount'])) {
                $exist = $this->in_array_assoc($record['healthFacilityAddress_id'], 'billingBranchId', $longTermSummary);
                if ($exist['exist']) {
                    $longTermSummary[$exist['key']]['price'] += $record['pbbForLongTerm_price'];
                    $longTermSummary[$exist['key']]['longTermCount'] += $record['longTermCount'];
                } else {
                    $longTermSummary[] = array(
                        'billingBranchId' => $record['healthFacilityAddress_id'],
                        'billingBranch' => $record['healthFacilityAddress'],
                        'price' => $record['pbbForLongTerm_price'],
                        'longTermCount' => $record['longTermCount'],
                    );
                }
            }
            if(!is_null($record['longTermCount_void']) && !empty($record['longTermCount_void'])) {
                $exist = $this->in_array_assoc($record['healthFacilityAddress_id'], 'billingBranchId', $longTermSummary_void);
                if ($exist['exist']) {
                    $longTermSummary_void[$exist['key']]['price'] += $record['pbbForLongTerm_price_void'];
                    $longTermSummary_void[$exist['key']]['longTermCount'] += $record['longTermCount_void'];
                } else {
                    $longTermSummary_void[] = array(
                        'billingBranchId' => $record['healthFacilityAddress_id'],
                        'billingBranch' => $record['healthFacilityAddress'],
                        'price' => $record['pbbForLongTerm_price_void'],
                        'longTermCount' => $record['longTermCount_void'],
                    );
                }
            }
        }

        $rentToOwnSummary = array();
        $rentToOwnSummary_void = array();
        foreach ($records as $record) {
            if(!is_null($record['rentToCount']) && !empty($record['rentToCount'])) {
                $exist = $this->in_array_assoc($record['healthFacilityAddress_id'], 'billingBranchId', $rentToOwnSummary);
                if ($exist['exist']) {
                    $rentToOwnSummary[$exist['key']]['price'] += $record['pbbForRentToOwn_price'];
                    $rentToOwnSummary[$exist['key']]['rentToCount'] += $record['rentToCount'];
                } else {
                    $rentToOwnSummary[] = array(
                        'billingBranchId' => $record['healthFacilityAddress_id'],
                        'billingBranch' => $record['healthFacilityAddress'],
                        'price' => $record['pbbForRentToOwn_price'],
                        'rentToCount' => $record['rentToCount'],
                    );
                }
            }
            if(!is_null($record['rentToCount_void']) && !empty($record['rentToCount_void'])) {
                $exist = $this->in_array_assoc($record['healthFacilityAddress_id'], 'billingBranchId', $rentToOwnSummary_void);
                if ($exist['exist']) {
                    $rentToOwnSummary_void[$exist['key']]['price'] += $record['pbbForRentToOwn_price_void'];
                    $rentToOwnSummary_void[$exist['key']]['rentToCount'] += $record['rentToCount_void'];
                } else {
                    $rentToOwnSummary_void[] = array(
                        'billingBranchId' => $record['healthFacilityAddress_id'],
                        'billingBranch' => $record['healthFacilityAddress'],
                        'price' => $record['pbbForRentToOwn_price_void'],
                        'rentToCount' => $record['rentToCount_void'],
                    );
                }
            }
        }

        $accessorySummary = array();
        $accessorySummary_void = array();
        foreach ($records as $record) {
            if(!is_null($record['accessoryCount']) && !empty($record['accessoryCount'])) {
                $exist = $this->in_array_assoc($record['healthFacilityAddress_id'], 'billingBranchId', $accessorySummary);
                if ($exist['exist']) {
                    $accessorySummary[$exist['key']]['price'] += $record['pbbForAccessory_price'];
                    $accessorySummary[$exist['key']]['accessoryCount'] += $record['accessoryCount'];
                } else {
                    $accessorySummary[] = array(
                        'billingBranchId' => $record['healthFacilityAddress_id'],
                        'billingBranch' => $record['healthFacilityAddress'],
                        'price' => $record['pbbForAccessory_price'],
                        'accessoryCount' => $record['accessoryCount'],
                    );
                }
            }
            if(!is_null($record['accessoryCount_void']) && !empty($record['accessoryCount_void'])) {
                $exist = $this->in_array_assoc($record['healthFacilityAddress_id'], 'billingBranchId', $accessorySummary_void);
                if ($exist['exist']) {
                    $accessorySummary_void[$exist['key']]['price'] += $record['pbbForAccessory_price_void'];
                    $accessorySummary_void[$exist['key']]['accessoryCount'] += $record['accessoryCount_void'];
                } else {
                    $accessorySummary_void[] = array(
                        'billingBranchId' => $record['healthFacilityAddress_id'],
                        'billingBranch' => $record['healthFacilityAddress'],
                        'price' => $record['pbbForAccessory_price_void'],
                        'accessoryCount' => $record['accessoryCount_void'],
                    );
                }
            }
        }

        $cpapPackageSummary = array();
        $cpapPackageSummary_void = array();
        foreach ($records as $record) {
            if(!is_null($record['cpapPackageCount']) && !empty($record['cpapPackageCount'])) {
                $exist = $this->in_array_assoc($record['healthFacilityAddress_id'], 'billingBranchId', $cpapPackageSummary);
                if ($exist['exist']) {
                    $cpapPackageSummary[$exist['key']]['price'] += $record['pbbForCpapPackage_price'];
                    $cpapPackageSummary[$exist['key']]['cpapPackageCount'] += $record['cpapPackageCount'];
                } else {
                    $cpapPackageSummary[] = array(
                        'billingBranchId' => $record['healthFacilityAddress_id'],
                        'billingBranch' => $record['healthFacilityAddress'],
                        'price' => $record['pbbForCpapPackage_price'],
                        'cpapPackageCount' => $record['cpapPackageCount'],
                    );
                }
            }
            if(!is_null($record['cpapPackageCount_void']) && !empty($record['cpapPackageCount_void'])) {
                $exist = $this->in_array_assoc($record['healthFacilityAddress_id'], 'billingBranchId', $cpapPackageSummary_void);
                if ($exist['exist']) {
                    $cpapPackageSummary_void[$exist['key']]['price'] += $record['pbbForCpapPackage_price_void'];
                    $cpapPackageSummary_void[$exist['key']]['cpapPackageCount'] += $record['cpapPackageCount_void'];
                } else {
                    $cpapPackageSummary_void[] = array(
                        'billingBranchId' => $record['healthFacilityAddress_id'],
                        'billingBranch' => $record['healthFacilityAddress'],
                        'price' => $record['pbbForCpapPackage_price_void'],
                        'cpapPackageCount' => $record['cpapPackageCount_void'],
                    );
                }
            }
        }

        $medicalSuppliesSummary = array();
        $medicalSuppliesSummary_void = array();
        foreach ($records as $record) {
            if(!is_null($record['medicalSuppliesCount']) && !empty($record['medicalSuppliesCount'])) {
                $exist = $this->in_array_assoc($record['healthFacilityAddress_id'], 'billingBranchId', $medicalSuppliesSummary);
                if ($exist['exist']) {
                    $medicalSuppliesSummary[$exist['key']]['price'] += $record['pbbForMedicalSupplies_price'];
                    $medicalSuppliesSummary[$exist['key']]['medicalSuppliesCount'] += $record['medicalSuppliesCount'];
                } else {
                    $medicalSuppliesSummary[] = array(
                        'billingBranchId' => $record['healthFacilityAddress_id'],
                        'billingBranch' => $record['healthFacilityAddress'],
                        'price' => $record['pbbForMedicalSupplies_price'],
                        'medicalSuppliesCount' => $record['medicalSuppliesCount'],
                    );
                }
            }
            if(!is_null($record['medicalSuppliesCount_void']) && !empty($record['medicalSuppliesCount_void'])) {
                $exist = $this->in_array_assoc($record['healthFacilityAddress_id'], 'billingBranchId', $medicalSuppliesSummary_void);
                if ($exist['exist']) {
                    $medicalSuppliesSummary_void[$exist['key']]['price'] += $record['pbbForMedicalSupplies_price_void'];
                    $medicalSuppliesSummary_void[$exist['key']]['medicalSuppliesCount'] += $record['medicalSuppliesCount_void'];
                } else {
                    $medicalSuppliesSummary_void[] = array(
                        'billingBranchId' => $record['healthFacilityAddress_id'],
                        'billingBranch' => $record['healthFacilityAddress'],
                        'price' => $record['pbbForMedicalSupplies_price_void'],
                        'medicalSuppliesCount' => $record['medicalSuppliesCount_void'],
                    );
                }
            }
        }

	    $partOfCpapPackageSummary = array();
	    $partOfCpapPackageSummary_void = array();
	    foreach ($records as $record) {
		    if(!is_null($record['partOfCpapPackageCount']) && !empty($record['partOfCpapPackageCount'])) {
			    $exist = $this->in_array_assoc($record['healthFacilityAddress_id'], 'billingBranchId', $partOfCpapPackageSummary);
			    if ($exist['exist']) {
				    $partOfCpapPackageSummary[$exist['key']]['price'] += $record['pbbForMedicalSupplies_price'];
				    $partOfCpapPackageSummary[$exist['key']]['partOfCpapPackageCount'] += $record['partOfCpapPackageCount'];
			    } else {
				    $partOfCpapPackageSummary[] = array(
					    'billingBranchId' => $record['healthFacilityAddress_id'],
					    'billingBranch' => $record['healthFacilityAddress'],
					    'price' => $record['pbbForMedicalSupplies_price'],
					    'partOfCpapPackageCount' => $record['partOfCpapPackageCount'],
				    );
			    }
		    }
		    if(!is_null($record['partOfCpapPackageCount_void']) && !empty($record['partOfCpapPackageCount_void'])) {
			    $exist = $this->in_array_assoc($record['healthFacilityAddress_id'], 'billingBranchId', $partOfCpapPackageSummary_void);
			    if ($exist['exist']) {
				    $partOfCpapPackageSummary_void[$exist['key']]['price'] += $record['pbbForMedicalSupplies_price_void'];
				    $partOfCpapPackageSummary_void[$exist['key']]['partOfCpapPackageCount'] += $record['partOfCpapPackageCount_void'];
			    } else {
				    $partOfCpapPackageSummary_void[] = array(
					    'billingBranchId' => $record['healthFacilityAddress_id'],
					    'billingBranch' => $record['healthFacilityAddress'],
					    'price' => $record['pbbForMedicalSupplies_price_void'],
					    'partOfCpapPackageCount' => $record['partOfCpapPackageCount_void'],
				    );
			    }
		    }
	    }


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

            'accessorySummary' => $accessorySummary,
            'accessorySummary_void' => $accessorySummary_void,

            'cpapPackageSummary' => $cpapPackageSummary,
            'cpapPackageSummary_void' => $cpapPackageSummary_void,

            'medicalSuppliesSummary' => $medicalSuppliesSummary,
            'medicalSuppliesSummary_void' => $medicalSuppliesSummary_void,

            'longTermSummary' => $longTermSummary,
            'longTermSummary_void' => $longTermSummary_void,

            'rentToOwnSummary' => $rentToOwnSummary,
            'rentToOwnSummary_void' => $rentToOwnSummary_void,

            'partOfCpapPackageSummary' => $partOfCpapPackageSummary,
            'partOfCpapPackageSummary_void' => $partOfCpapPackageSummary_void,

            'paymentBreakdown' => $paymentBreakdown,
        ));

        $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_invoice', 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,
        ));*/

        $invoiceSummary = array();
        $financingSummary = array();
        foreach ($records as $record) {
            if(!in_array($record['healthFacilityAddress'], array('Finance Underwriting & Investment Capital', 'Canpay Medical Inc.'))) {
                $exist = $this->in_array_assoc($record['healthFacilityAddress_id'], 'healthFacilityAddress_id', $invoiceSummary);
                if ($exist['exist']) {
                    $invoiceSummary[$exist['key']]['totalAmtDue'] += $record['amtDue_forTotal'];
                    $invoiceSummary[$exist['key']]['totalCount'] += 1;
                } else {
                    $invoiceSummary[] = array(
                        'healthFacilityAddress_id' => $record['healthFacilityAddress_id'],
                        'healthFacility' => $record['healthFacilityAddress'],
                        'totalAmtDue' => $record['amtDue_forTotal'],
                        'totalCount' => 1,
                    );
                }
            } else {
                $exist = $this->in_array_assoc($record['healthFacilityAddress_id'], 'healthFacilityAddress_id', $financingSummary);
                if ($exist['exist']) {
                    $financingSummary[$exist['key']]['totalAmtDue'] += $record['amtDue_forTotal'];
                    $financingSummary[$exist['key']]['totalCount'] += 1;
                } else {
                    $financingSummary[] = array(
                        'healthFacilityAddress_id' => $record['healthFacilityAddress_id'],
                        'healthFacility' => $record['healthFacilityAddress'],
                        'totalAmtDue' => $record['amtDue_forTotal'],
                        'totalCount' => 1,
                    );
                }
            }
        }

        $paymentSummary = array();
        foreach ($records as $record) {
            $exist = $this->in_array_assoc($record['healthFacilityAddress_id'], 'healthFacilityAddress_id', $paymentSummary);
            if($exist['exist']){
                $paymentSummary[$exist['key']]['totalPaymentAmount'] += $record['totalPaymentAmount'];
                $paymentSummary[$exist['key']]['count'] += 1;
            } else {
                $paymentSummary[] = array(
                    'healthFacilityAddress_id' => $record['healthFacilityAddress_id'],
                    'healthFacilityAddress' => $record['healthFacilityAddress'],
                    'totalPaymentAmount' => $record['totalPaymentAmount'],
                    'count' => 1,
                );
            }
        }

        $paymentBreakdown = array();
        foreach ($records as $record) {
            if(!is_null($record['ppForBreakdown_breakdown']) && !empty($record['ppForBreakdown_breakdown'])) {
                $breakdownArray = explode(',', $record['ppForBreakdown_breakdown']);
                foreach ($breakdownArray as $key => $item) {
                    $breakdown = explode('~', $item);

                    $paymentType = $breakdown[0];
                    $transactionCount = $breakdown[1];
                    $totalAmt = $breakdown[2];

                    $exist = $this->in_array_assoc($paymentType, 'paymentType', $paymentBreakdown);
                    if ($exist['exist']) {
                        $paymentBreakdown[$exist['key']]['transactionCount'] += $transactionCount;
                        $paymentBreakdown[$exist['key']]['totalAmt'] += $totalAmt;
                        $paymentBreakdown[$exist['key']]['invoices'][] = $record['invoiceNo'];
                    } else {
                        $paymentBreakdown[] = array(
                            'paymentType' => $paymentType,
                            'transactionCount' => $transactionCount,
                            'totalAmt' => $totalAmt,
                            'invoices' => array($record['invoiceNo'])
                        );
                    }
                }
            }
        }

        $longTermSummary = array();
        $longTermSummary_void = array();
        foreach ($records as $record) {
            if(!is_null($record['longTermCount']) && !empty($record['longTermCount'])) {
                $exist = $this->in_array_assoc($record['healthFacilityAddress_id'], 'billingBranchId', $longTermSummary);
                if ($exist['exist']) {
                    $longTermSummary[$exist['key']]['price'] += $record['pbbForLongTerm_price'];
                    $longTermSummary[$exist['key']]['longTermCount'] += $record['longTermCount'];
                } else {
                    $longTermSummary[] = array(
                        'billingBranchId' => $record['healthFacilityAddress_id'],
                        'billingBranch' => $record['healthFacilityAddress'],
                        'price' => $record['pbbForLongTerm_price'],
                        'longTermCount' => $record['longTermCount'],
                    );
                }
            }
            if(!is_null($record['longTermCount_void']) && !empty($record['longTermCount_void'])) {
                $exist = $this->in_array_assoc($record['healthFacilityAddress_id'], 'billingBranchId', $longTermSummary_void);
                if ($exist['exist']) {
                    $longTermSummary_void[$exist['key']]['price'] += $record['pbbForLongTerm_price_void'];
                    $longTermSummary_void[$exist['key']]['longTermCount'] += $record['longTermCount_void'];
                } else {
                    $longTermSummary_void[] = array(
                        'billingBranchId' => $record['healthFacilityAddress_id'],
                        'billingBranch' => $record['healthFacilityAddress'],
                        'price' => $record['pbbForLongTerm_price_void'],
                        'longTermCount' => $record['longTermCount_void'],
                    );
                }
            }
        }

        $rentToOwnSummary = array();
        $rentToOwnSummary_void = array();
        foreach ($records as $record) {
            if(!is_null($record['rentToCount']) && !empty($record['rentToCount'])) {
                $exist = $this->in_array_assoc($record['healthFacilityAddress_id'], 'billingBranchId', $rentToOwnSummary);
                if ($exist['exist']) {
                    $rentToOwnSummary[$exist['key']]['price'] += $record['pbbForRentToOwn_price'];
                    $rentToOwnSummary[$exist['key']]['rentToCount'] += $record['rentToCount'];
                } else {
                    $rentToOwnSummary[] = array(
                        'billingBranchId' => $record['healthFacilityAddress_id'],
                        'billingBranch' => $record['healthFacilityAddress'],
                        'price' => $record['pbbForRentToOwn_price'],
                        'rentToCount' => $record['rentToCount'],
                    );
                }
            }
            if(!is_null($record['rentToCount_void']) && !empty($record['rentToCount_void'])) {
                $exist = $this->in_array_assoc($record['healthFacilityAddress_id'], 'billingBranchId', $rentToOwnSummary_void);
                if ($exist['exist']) {
                    $rentToOwnSummary_void[$exist['key']]['price'] += $record['pbbForRentToOwn_price_void'];
                    $rentToOwnSummary_void[$exist['key']]['rentToCount'] += $record['rentToCount_void'];
                } else {
                    $rentToOwnSummary_void[] = array(
                        'billingBranchId' => $record['healthFacilityAddress_id'],
                        'billingBranch' => $record['healthFacilityAddress'],
                        'price' => $record['pbbForRentToOwn_price_void'],
                        'rentToCount' => $record['rentToCount_void'],
                    );
                }
            }
        }

        $accessorySummary = array();
        $accessorySummary_void = array();
        foreach ($records as $record) {
            if(!is_null($record['accessoryCount']) && !empty($record['accessoryCount'])) {
                $exist = $this->in_array_assoc($record['healthFacilityAddress_id'], 'billingBranchId', $accessorySummary);
                if ($exist['exist']) {
                    $accessorySummary[$exist['key']]['price'] += $record['pbbForAccessory_price'];
                    $accessorySummary[$exist['key']]['accessoryCount'] += $record['accessoryCount'];
                } else {
                    $accessorySummary[] = array(
                        'billingBranchId' => $record['healthFacilityAddress_id'],
                        'billingBranch' => $record['healthFacilityAddress'],
                        'price' => $record['pbbForAccessory_price'],
                        'accessoryCount' => $record['accessoryCount'],
                    );
                }
            }
            if(!is_null($record['accessoryCount_void']) && !empty($record['accessoryCount_void'])) {
                $exist = $this->in_array_assoc($record['healthFacilityAddress_id'], 'billingBranchId', $accessorySummary_void);
                if ($exist['exist']) {
                    $accessorySummary_void[$exist['key']]['price'] += $record['pbbForAccessory_price_void'];
                    $accessorySummary_void[$exist['key']]['accessoryCount'] += $record['accessoryCount_void'];
                } else {
                    $accessorySummary_void[] = array(
                        'billingBranchId' => $record['healthFacilityAddress_id'],
                        'billingBranch' => $record['healthFacilityAddress'],
                        'price' => $record['pbbForAccessory_price_void'],
                        'accessoryCount' => $record['accessoryCount_void'],
                    );
                }
            }
        }

        $cpapPackageSummary = array();
        $cpapPackageSummary_void = array();
        foreach ($records as $record) {
            if(!is_null($record['cpapPackageCount']) && !empty($record['cpapPackageCount'])) {
                $exist = $this->in_array_assoc($record['healthFacilityAddress_id'], 'billingBranchId', $cpapPackageSummary);
                if ($exist['exist']) {
                    $cpapPackageSummary[$exist['key']]['price'] += $record['pbbForCpapPackage_price'];
                    $cpapPackageSummary[$exist['key']]['cpapPackageCount'] += $record['cpapPackageCount'];
                } else {
                    $cpapPackageSummary[] = array(
                        'billingBranchId' => $record['healthFacilityAddress_id'],
                        'billingBranch' => $record['healthFacilityAddress'],
                        'price' => $record['pbbForCpapPackage_price'],
                        'cpapPackageCount' => $record['cpapPackageCount'],
                    );
                }
            }
            if(!is_null($record['cpapPackageCount_void']) && !empty($record['cpapPackageCount_void'])) {
                $exist = $this->in_array_assoc($record['healthFacilityAddress_id'], 'billingBranchId', $cpapPackageSummary_void);
                if ($exist['exist']) {
                    $cpapPackageSummary_void[$exist['key']]['price'] += $record['pbbForCpapPackage_price_void'];
                    $cpapPackageSummary_void[$exist['key']]['cpapPackageCount'] += $record['cpapPackageCount_void'];
                } else {
                    $cpapPackageSummary_void[] = array(
                        'billingBranchId' => $record['healthFacilityAddress_id'],
                        'billingBranch' => $record['healthFacilityAddress'],
                        'price' => $record['pbbForCpapPackage_price_void'],
                        'cpapPackageCount' => $record['cpapPackageCount_void'],
                    );
                }
            }
        }

        $medicalSuppliesSummary = array();
        $medicalSuppliesSummary_void = array();
        foreach ($records as $record) {
            if(!is_null($record['medicalSuppliesCount']) && !empty($record['medicalSuppliesCount'])) {
                $exist = $this->in_array_assoc($record['healthFacilityAddress_id'], 'billingBranchId', $medicalSuppliesSummary);
                if ($exist['exist']) {
                    $medicalSuppliesSummary[$exist['key']]['price'] += $record['pbbForMedicalSupplies_price'];
                    $medicalSuppliesSummary[$exist['key']]['medicalSuppliesCount'] += $record['medicalSuppliesCount'];
                } else {
                    $medicalSuppliesSummary[] = array(
                        'billingBranchId' => $record['healthFacilityAddress_id'],
                        'billingBranch' => $record['healthFacilityAddress'],
                        'price' => $record['pbbForMedicalSupplies_price'],
                        'medicalSuppliesCount' => $record['medicalSuppliesCount'],
                    );
                }
            }
            if(!is_null($record['medicalSuppliesCount_void']) && !empty($record['medicalSuppliesCount_void'])) {
                $exist = $this->in_array_assoc($record['healthFacilityAddress_id'], 'billingBranchId', $medicalSuppliesSummary_void);
                if ($exist['exist']) {
                    $medicalSuppliesSummary_void[$exist['key']]['price'] += $record['pbbForMedicalSupplies_price_void'];
                    $medicalSuppliesSummary_void[$exist['key']]['medicalSuppliesCount'] += $record['medicalSuppliesCount_void'];
                } else {
                    $medicalSuppliesSummary_void[] = array(
                        'billingBranchId' => $record['healthFacilityAddress_id'],
                        'billingBranch' => $record['healthFacilityAddress'],
                        'price' => $record['pbbForMedicalSupplies_price_void'],
                        'medicalSuppliesCount' => $record['medicalSuppliesCount_void'],
                    );
                }
            }
        }

	    $partOfCpapPackageSummary = array();
	    $partOfCpapPackageSummary_void = array();
	    foreach ($records as $record) {
		    if(!is_null($record['partOfCpapPackageCount']) && !empty($record['partOfCpapPackageCount'])) {
			    $exist = $this->in_array_assoc($record['healthFacilityAddress_id'], 'billingBranchId', $partOfCpapPackageSummary);
			    if ($exist['exist']) {
				    $partOfCpapPackageSummary[$exist['key']]['price'] += $record['pbbForMedicalSupplies_price'];
				    $partOfCpapPackageSummary[$exist['key']]['partOfCpapPackageCount'] += $record['partOfCpapPackageCount'];
			    } else {
				    $partOfCpapPackageSummary[] = array(
					    'billingBranchId' => $record['healthFacilityAddress_id'],
					    'billingBranch' => $record['healthFacilityAddress'],
					    'price' => $record['pbbForMedicalSupplies_price'],
					    'partOfCpapPackageCount' => $record['partOfCpapPackageCount'],
				    );
			    }
		    }
		    if(!is_null($record['partOfCpapPackageCount_void']) && !empty($record['partOfCpapPackageCount_void'])) {
			    $exist = $this->in_array_assoc($record['healthFacilityAddress_id'], 'billingBranchId', $partOfCpapPackageSummary_void);
			    if ($exist['exist']) {
				    $partOfCpapPackageSummary_void[$exist['key']]['price'] += $record['pbbForMedicalSupplies_price_void'];
				    $partOfCpapPackageSummary_void[$exist['key']]['partOfCpapPackageCount'] += $record['partOfCpapPackageCount_void'];
			    } else {
				    $partOfCpapPackageSummary_void[] = array(
					    'billingBranchId' => $record['healthFacilityAddress_id'],
					    'billingBranch' => $record['healthFacilityAddress'],
					    'price' => $record['pbbForMedicalSupplies_price_void'],
					    'partOfCpapPackageCount' => $record['partOfCpapPackageCount_void'],
				    );
			    }
		    }
	    }

        $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' => 'Address'),
            array('cell' => 'E1', 'data' => 'Phone No(s)'),
            array('cell' => 'F1', 'data' => 'Email(s)'),
            array('cell' => 'G1', 'data' => 'Company'),
            array('cell' => 'H1', 'data' => 'Branch'),
            array('cell' => 'I1', 'data' => 'Branch Address'),
            array('cell' => 'J1', 'data' => 'Amount'),
            array('cell' => 'K1', 'data' => 'Amount Paid'),
            array('cell' => 'L1', 'data' => 'Amount Refunded'),
            array('cell' => 'M1', 'data' => 'Balance'),
            array('cell' => 'N1', 'data' => 'Status'),
            array('cell' => 'O1', 'data' => 'Note'),
        );
        $rowCtr = 1;
        $totalCount = 0;
        $totalAmt = 0;
        $totalPaid = 0;
        $totalRefunded = 0;
        $totalBalance = 0;

        foreach($records as $record) {

            $rowCtr++;
            $totalCount++;
            $totalAmt = $totalAmt + $record['amtDue_forTotal'];
            $totalPaid = $totalPaid + $record['amtPaid_forTotal'];
            $totalRefunded = $totalRefunded + $record['amtRefunded_forTotal'];
            $totalBalance = $totalBalance + $record['amtBalance_forTotal'];

            $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['address']);
            $cellsData[] = array('cell' => "E$rowCtr", 'data' => $record['phoneNo']);
            $cellsData[] = array('cell' => "F$rowCtr", 'data' => $record['email']);
            $cellsData[] = array('cell' => "G$rowCtr", 'data' => $record['companyDesc']);
            $cellsData[] = array('cell' => "H$rowCtr", 'data' => $record['healthFacility']);
            $cellsData[] = array('cell' => "I$rowCtr", 'data' => $record['healthFacilityAddress']);
            $cellsData[] = array('cell' => "J$rowCtr", 'data' => number_format($record['amtDue'],2,'.',','));
            $cellsData[] = array('cell' => "K$rowCtr", 'data' => number_format($record['amtPaid'],2,'.',','));
            $cellsData[] = array('cell' => "L$rowCtr", 'data' => number_format($record['amtRefunded'],2,'.',','));
            $cellsData[] = array('cell' => "M$rowCtr", 'data' => number_format($record['amtBalance'],2,'.',','));
            $cellsData[] = array('cell' => "N$rowCtr", 'data' => $record['billingStatus']);
            $cellsData[] = array('cell' => "O$rowCtr", 'data' => $record['note']);
        }
        $rowCtr++;
        $cellsData[] = array('cell' => "G$rowCtr", 'data' => number_format($totalAmt,2,'.',','));
        $cellsData[] = array('cell' => "H$rowCtr", 'data' => number_format($totalPaid,2,'.',','));
        $cellsData[] = array('cell' => "I$rowCtr", 'data' => number_format($totalRefunded,2,'.',','));
        $cellsData[] = array('cell' => "J$rowCtr", 'data' => number_format($totalBalance,2,'.',','));

        //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($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($financingSummary 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,'.',','));

        //PAYMENT SUMMARY
        $rowCtr++;
        $rowCtr++;
        $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Payment Summary: ');
        $paymentSummaryTotal = 0;
        $paymentSummaryAmtDue = 0;
        foreach($paymentSummary as $record3) {
            $paymentSummaryTotal = $paymentSummaryTotal + $record3['count'];
            $paymentSummaryAmtDue = $paymentSummaryAmtDue + $record3['totalPaymentAmount'];
            $rowCtr++;
            $cellsData[] = array('cell' => "A$rowCtr", 'data' => $record3['healthFacilityAddress']);
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => number_format($record3['count'],2,'.',','));
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => number_format($record3['totalPaymentAmount'],2,'.',','));
        }

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

        //PAYMENT BREAKDOWN
        $rowCtr++;
        $rowCtr++;
        $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Payment Type Breakdown: ');
        $paymentSummaryTotal = 0;
        $paymentSummaryAmtDue = 0;
        foreach($paymentBreakdown as $record3) {
            $paymentSummaryTotal = $paymentSummaryTotal + $record3['transactionCount'];
            $paymentSummaryAmtDue = $paymentSummaryAmtDue + $record3['totalAmt'];
            $rowCtr++;
            $cellsData[] = array('cell' => "A$rowCtr", 'data' => $record3['paymentType']);
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => number_format($record3['transactionCount'],2,'.',','));
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => number_format($record3['totalAmt'],2,'.',','));
        }

        $rowCtr++;
        $cellsData[] = array('cell' => "B$rowCtr", 'data' => 'Total: ' . $paymentSummaryTotal);
        $cellsData[] = array('cell' => "C$rowCtr", 'data' => number_format($paymentSummaryAmtDue,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($longTermSummary 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,'.',','));

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

        $rowCtr++;
        $rowCtr++;
        $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Long Term Summary (Void / Returned)');
        $rowCtr++;
        $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Branch');
        $cellsData[] = array('cell' => "B$rowCtr", 'data' => 'Count ');
        $cellsData[] = array('cell' => "C$rowCtr", 'data' => 'Total Amount');
        foreach($longTermSummary_void 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,'.',','));


        // Rent to Own
        $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($rentToOwnSummary 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,'.',','));


        // Rent to Own Void
        $rentToOwnCount = 0;
        $rentToOwnTotalPrice = 0;

        $rowCtr++;
        $rowCtr++;
        $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Rent to Own Summary (Void / Returned)');
        $rowCtr++;
        $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Branch');
        $cellsData[] = array('cell' => "B$rowCtr", 'data' => 'Count ');
        $cellsData[] = array('cell' => "C$rowCtr", 'data' => 'Total Amount');
        foreach($rentToOwnSummary_void 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,'.',','));



        // Accessory
        $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($accessorySummary 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,'.',','));



        // Accessory Void
        $accessoryCount = 0;
        $accessoryTotalPrice = 0;

        $rowCtr++;
        $rowCtr++;
        $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Accessory Summary (Void / Returned)');
        $rowCtr++;
        $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Branch');
        $cellsData[] = array('cell' => "B$rowCtr", 'data' => 'Count ');
        $cellsData[] = array('cell' => "C$rowCtr", 'data' => 'Total Amount');
        foreach($accessorySummary_void 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,'.',','));


        // CPAP Package
        $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($cpapPackageSummary 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,'.',','));


        // CPAP Package Void
        $cpapPackageCount = 0;
        $cpapPackageTotalPrice = 0;

        $rowCtr++;
        $rowCtr++;
        $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'CPAP Package Summary (Void / Returned)');
        $rowCtr++;
        $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Branch');
        $cellsData[] = array('cell' => "B$rowCtr", 'data' => 'Count ');
        $cellsData[] = array('cell' => "C$rowCtr", 'data' => 'Total Amount');
        foreach($cpapPackageSummary_void 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,'.',','));


        // Medical Supplies
        $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($medicalSuppliesSummary 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,'.',','));


        // Medical Supplies Void
        $medicalSuppliesCount = 0;
        $medicalSuppliesTotalPrice = 0;

        $rowCtr++;
        $rowCtr++;
        $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Medical Supplies Summary (Void / Returned)');
        $rowCtr++;
        $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Branch');
        $cellsData[] = array('cell' => "B$rowCtr", 'data' => 'Count ');
        $cellsData[] = array('cell' => "C$rowCtr", 'data' => 'Total Amount');
        foreach($medicalSuppliesSummary_void 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,'.',','));


	    // Part of CPAP Package
	    $partOfCpapPackageCount = 0;
	    $partOfCpapPackageTotalPrice = 0;

	    $rowCtr++;
	    $rowCtr++;
	    $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Part of 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($partOfCpapPackageSummary as $partOfCpapPackage) {

		    $partOfCpapPackageCount = $partOfCpapPackageCount + $partOfCpapPackage['partOfCpapPackageCount'];
		    $partOfCpapPackageTotalPrice = $partOfCpapPackageTotalPrice + $partOfCpapPackage['price'];

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


	    // Part of CPAP Package Void
	    $partOfCpapPackageCount = 0;
	    $partOfCpapPackageTotalPrice = 0;

	    $rowCtr++;
	    $rowCtr++;
	    $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Part of CPAP Package Summary (Void / Returned)');
	    $rowCtr++;
	    $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Branch');
	    $cellsData[] = array('cell' => "B$rowCtr", 'data' => 'Count ');
	    $cellsData[] = array('cell' => "C$rowCtr", 'data' => 'Total Amount');
	    foreach($partOfCpapPackageSummary_void as $partOfCpapPackage) {

		    $partOfCpapPackageCount = $partOfCpapPackageCount + $partOfCpapPackage['partOfCpapPackageCount'];
		    $partOfCpapPackageTotalPrice = $partOfCpapPackageTotalPrice + $partOfCpapPackage['price'];

		    $rowCtr++;
		    $cellsData[] = array('cell' => "A$rowCtr", 'data' => $partOfCpapPackage['billingBranch']);
		    $cellsData[] = array('cell' => "B$rowCtr", 'data' => number_format($partOfCpapPackage['partOfCpapPackageCount'],2,'.',','));
		    $cellsData[] = array('cell' => "C$rowCtr", 'data' => number_format($partOfCpapPackage['price'],2,'.',','));
	    }
	    $rowCtr++;
	    $cellsData[] = array('cell' => "B$rowCtr", 'data' => 'Total: ' . $partOfCpapPackageCount);
	    $cellsData[] = array('cell' => "C$rowCtr", 'data' => number_format($partOfCpapPackageTotalPrice,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);
        $services = $em->getRepository('RxConnexionBundle:ServiceEntity')->servicesForMultiple($userData);

        $page_title = 'Specialist Referral Report';
        return $this->render('@RxConnexion/Report/SpecialistReferralTracker/index.html.twig', array(
            'title' => $page_title,
            'company' => $company,
            'branch' => $branch,
            'services' => $services,
            '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/{date_from}/{date_to}/{receive_date_from}/{receive_date_to}/{company}/{branch}/{servicing_branch}/{service}/{patient}/{specialist}/{type}",
     *      name = "report_specialist_referral_tracker_preview"
     * )
     */
    public function specialistReferralTracker_previewAction($date_from, $date_to, $receive_date_from, $receive_date_to, $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(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'receive_date_from' => $receive_date_from,
            'receive_date_to' => $receive_date_to,
            '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/{date_from}/{date_to}/{receive_date_from}/{receive_date_to}/{company}/{branch}/{servicing_branch}/{service}/{patient}/{specialist}/{type}",
     *      name = "report_specialist_referral_tracker_export_to_pdf"
     * )
     */
    public function specialistReferralTracker_export_to_pdfAction($date_from, $date_to, $receive_date_from, $receive_date_to, $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(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'receive_date_from' => $receive_date_from,
            'receive_date_to' => $receive_date_to,
            '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/{date_from}/{date_to}/{receive_date_from}/{receive_date_to}/{company}/{branch}/{servicing_branch}/{service}/{patient}/{specialist}/{type}",
     *      name = "report_specialist_referral_tracker_export_to_excel"
     * )
     */
    public function specialistReferralTracker_export_to_excelAction($date_from, $date_to, $receive_date_from, $receive_date_to, $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(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'receive_date_from' => $receive_date_from,
            'receive_date_to' => $receive_date_to,
            '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' => 'Referral Date'),
            array('cell' => 'B1', 'data' => 'Receive Date'),
            array('cell' => 'C1', 'data' => 'Patient'),
            array('cell' => 'D1', 'data' => 'Patient Type'),
            array('cell' => 'E1', 'data' => 'Referring Branch'),
            array('cell' => 'F1', 'data' => 'Clinician'),
            array('cell' => 'G1', 'data' => 'Diagnosis'),
            array('cell' => 'H1', 'data' => 'Encounter Type'),
            array('cell' => 'I1', 'data' => 'Encounter Date'),
            array('cell' => 'J1', 'data' => 'Encounter Status'),
            array('cell' => 'K1', 'data' => 'BMI'),
            array('cell' => 'L1', 'data' => 'O2 Saturation'),
            array('cell' => 'M1', 'data' => 'Initial AHI'),
            array('cell' => 'N1', 'data' => 'Current AHI'),
            array('cell' => 'O1', 'data' => 'Servicing Branch'),
            array('cell' => 'P1', 'data' => 'Service'),
            array('cell' => 'Q1', 'data' => 'Specialist'),
            array('cell' => 'R1', 'data' => 'Encounter Type'),
            array('cell' => 'S1', 'data' => 'Encounter Date'),
            array('cell' => 'T1', 'data' => 'Encounter Status'),
            array('cell' => 'U1', 'data' => 'Note'),
        );
        $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['receiveDate']);
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => $record['patientName']);
            $cellsData[] = array('cell' => "D$rowCtr", 'data' => $record['patientType']);
            $cellsData[] = array('cell' => "E$rowCtr", 'data' => $record['healthFacility']);
            $cellsData[] = array('cell' => "F$rowCtr", 'data' => $record['providerFullName']);
            $cellsData[] = array('cell' => "G$rowCtr", 'data' => $record['diagnosisDesc']);
            $cellsData[] = array('cell' => "H$rowCtr", 'data' => $record['chartType']);
            $cellsData[] = array('cell' => "I$rowCtr", 'data' => $record['chartDate']);
            $cellsData[] = array('cell' => "J$rowCtr", 'data' => $record['chartStatus']);
            $cellsData[] = array('cell' => "K$rowCtr", 'data' => $record['bmi']);
            $cellsData[] = array('cell' => "L$rowCtr", 'data' => $record['otwo_saturation']);
            $cellsData[] = array('cell' => "M$rowCtr", 'data' => $record['init_ahi']);
            $cellsData[] = array('cell' => "N$rowCtr", 'data' => $record['ahi']);
            $cellsData[] = array('cell' => "O$rowCtr", 'data' => $record['servicingHealthFacility']);
            $cellsData[] = array('cell' => "P$rowCtr", 'data' => $record['serviceDesc']);
            $cellsData[] = array('cell' => "Q$rowCtr", 'data' => $record['specialistFullName']);
            $cellsData[] = array('cell' => "R$rowCtr", 'data' => $record['sp_chartType']);
            $cellsData[] = array('cell' => "S$rowCtr", 'data' => $record['sp_chartDate']);
            $cellsData[] = array('cell' => "T$rowCtr", 'data' => $record['sp_chartStatus']);
            $cellsData[] = array('cell' => "U$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)'
        ));

        $hsatMobileRepeatChartType = $em->getRepository('RxConnexionBundle:ChartTypeEntity')->findOneBy(array(
            'description' => 'HSAT Mobile (Repeat)'
        ));

        $hsatCurbsideChartType = $em->getRepository('RxConnexionBundle:ChartTypeEntity')->findOneBy(array(
            'description' => 'HSAT Curbside'
        ));

        $hsatCurbsideRepeatChartType = $em->getRepository('RxConnexionBundle:ChartTypeEntity')->findOneBy(array(
            'description' => 'HSAT Curbside (Repeat)'
        ));

        $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,
            'hsatMobileRepeatExpNoOfDays' => $hsatMobileRepeatChartType ? $hsatMobileRepeatChartType->getExpectedNoOfDays() : 0,
            'hsatCurbsideExpNoOfDays' => $hsatCurbsideChartType ? $hsatCurbsideChartType->getExpectedNoOfDays() : 0,
            'hsatCurbsideRepeatExpNoOfDays' => $hsatCurbsideRepeatChartType ? $hsatCurbsideRepeatChartType->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' => 'Address'),
            array('cell' => 'C1', 'data' => 'Phone No.'),
            array('cell' => 'D1', 'data' => 'Email'),
            array('cell' => 'E1', 'data' => 'Invoice No.'),
            array('cell' => 'F1', 'data' => 'Company'),
            array('cell' => 'G1', 'data' => 'Branch'),
            array('cell' => 'H1', 'data' => 'Branch Address'),
            array('cell' => 'I1', 'data' => 'Category'),
            array('cell' => 'J1', 'data' => 'Term'),
            array('cell' => 'K1', 'data' => 'Item Type'),
            array('cell' => 'L1', 'data' => 'Description'),
            array('cell' => 'M1', 'data' => 'Quality'),
            array('cell' => 'N1', '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['address']);
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => $record['phoneNo']);
            $cellsData[] = array('cell' => "D$rowCtr", 'data' => $record['email']);
            $cellsData[] = array('cell' => "E$rowCtr", 'data' => $record['invoiceNo']);
            $cellsData[] = array('cell' => "F$rowCtr", 'data' => $record['companyDesc']);
            $cellsData[] = array('cell' => "G$rowCtr", 'data' => $record['branch']);
            $cellsData[] = array('cell' => "H$rowCtr", 'data' => $record['branchAddress']);
            $cellsData[] = array('cell' => "I$rowCtr", 'data' => $record['itemCategory']);
            $cellsData[] = array('cell' => "J$rowCtr", 'data' => $record['term']);
            $cellsData[] = array('cell' => "K$rowCtr", 'data' => $record['itemType']);
            $cellsData[] = array('cell' => "L$rowCtr", 'data' => $record['itemDesc']);
            $cellsData[] = array('cell' => "M$rowCtr", 'data' => $record['qty']);
            $cellsData[] = array('cell' => "N$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'),
            array('cell' => 'E1', 'data' => 'Created By'),
            array('cell' => 'F1', 'data' => 'Created At'),
        );
        $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['letterStatus'] != '' && $record['letterStatus'] != 'null' ? '('.$record['letterStatus'].')' : '');
            $cellsData[] = array('cell' => "E$rowCtr", 'data' => $record['createdBy']);
            $cellsData[] = array('cell' => "F$rowCtr", 'data' => $record['createdAt']);
        }

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

    //Inventory Report
    /**
     * @Route("/report_inventory", name="report_inventory")
     */
    public function inventory_reportAction() {

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

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

        $page_title = 'Inventory Report';
        return $this->render('@RxConnexion/Report/Inventory/index.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/inventory/inventory.js?v=1.0.0'),
	        'branches' => $userData['type'] == 'Super Admin'
		        ? $em->getRepository(HealthFacilityEntity::class)->findAllNotDeleted()
		        : $em->getRepository(HealthFacilityEntity::class)->findAllByIds($userData['branches'], true),
	        'categories' => $em->getRepository(ItemSubCategoryEntity::class)->findBy(['isDeleted' => false], ['description' => 'ASC']),
        ));
    }

    /**
     * @Route(
     *      "/report_inventory/export",
     *      name = "report_inventory_export"
     * )
     */
    public function report_inventory_exportAction(Request $request) {

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

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

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

        $categories = $request->get('categories');
        $item = $request->get('item');
        $branches = $request->get('branches');
        $statuses = $request->get('statuses');
	    $type = $request->get('type');

	    $em = $this->getDoctrine()->getManager();
	    $records = $em->getRepository('RxConnexionBundle:InventoryEntity')->reportInventory_2($userData, [
	    	'categories' => $categories,
	    	'item' => $item,
	    	'branches' => $branches,
	    	'statuses' => $statuses,
	    ]);
	    /*echo '<pre>';
	    print_r($records);
	    die();*/
	    $inventories = [];
	    $branches = [];

	    foreach ($records as $record) {

		    // branch
		    $b = $this->in_array_assoc($record['branch_id'], 'id', $branches);
		    if(!$b['exist']){
			    $branches[] = [
				    'id'            => $record['branch_id'],
				    'description'   => $record['branch'],
				    'total_qty'     => 0,
				    'total_cost'    => 0,
				    'total_value'   => 0,
			    ];
		    }

		    // item
		    $c = $this->in_array_assoc_multiple([
			    ['val' => $record['item_id'], 'key' => 'item_id'],
			    ['val' => $record['status'], 'key' => 'status'],
		    ], $inventories);
		    if($c['exist']) {
			    $inventories[$c['key']]['branches'][] = [
				    'id'            => $record['branch_id'],
				    'description'   => $record['branch'],
				    'quantity'      => $record['quantity'],
				    'ave_cost'      => $record['ave_cost'],
				    'total_cost'    => $record['quantity'] * $record['ave_cost'],
			    ];
		    } else {
			    $inventories[] = [
				    'item_id'   => $record['item_id'],
				    'item'      => $record['item'],
				    'codes'     => $record['codes'],
				    'status'    => $record['status'],
				    'branches'  => [
					    [
						    'id'           => $record['branch_id'],
						    'description'  => $record['branch'],
						    'quantity'     => $record['quantity'],
						    'ave_cost'     => $record['ave_cost'],
						    'total_cost'   => $record['quantity'] * $record['ave_cost'],
					    ]
				    ]
			    ];
		    }
	    }

	    switch($type) {
	    	//<editor-fold desc="PREVIEW">
		    case 'preview':
			    if(!$authService->isUserHasAccesses(array('Admin Report Inventory Item List Preview'))) return $authService->redirectToHome();

			    $page_title = 'Inventory Report';
			    return $this->render('@RxConnexion/Report/Inventory/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,
				    'inventories' => $inventories,
				    'branches'    => $branches,
			    ));
		    	break;
	        //</editor-fold>
		    //<editor-fold desc="PDF">
		    case 'pdf':
			    $page_title = 'Inventory Report';
			    $content = $this->renderView('@RxConnexion/Report/Inventory/preview.wkpdf.twig', array(
				    'page_title' => $page_title,
				    'records' => $records,
				    'hasCost' => $hasCost,
			    ));

			    $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="Inventory Report' . date('m/d/Y') . ' Details.pdf"'
				    ));
			    } else {
				    $this->get('session')->getFlashBag()->set('error_messages', $pdfResponse['msg']);
				    return $this->redirect($this->generateUrl('report_inventory', 302));
			    }
		    	break;
		    //</editor-fold>
		    //<editor-fold desc="EXCEL">
		    case 'excel' :
			    if(!$authService->isUserHasAccesses(array('Admin Report Inventory Item List Excel'))) return $authService->redirectToHome();

			    $columnRange = range('A', 'C');
			    $cellsData = [];
			    $fillCells = [];
			    $mergeCells = [];

			    $rowCtr = 1;

			    $cellsData[] = array('cell' => "A".($rowCtr+1), 'data' => 'Code');
			    $cellsData[] = array('cell' => "B".($rowCtr+1), 'data' => 'Item');
			    $fillCells[] = "A".($rowCtr+1);
			    $fillCells[] = "B".($rowCtr+1);

			    $column = "B";
			    foreach ($branches as $branch) {
				    $column++;
				    $fillCells[] = $column.$rowCtr;
				    $mergeCell = [$column.$rowCtr];
				    $cellsData[] = array('cell' => "{$column}$rowCtr", 'data' => $branch['description']);
				    $cellsData[] = array('cell' => $column.($rowCtr+1), 'data' => 'Qty');
				    $fillCells[] = $column.($rowCtr+1);

				    $column++;
				    $cellsData[] = array('cell' => $column.($rowCtr+1), 'data' => 'Cost');
				    $fillCells[] = $column.($rowCtr+1);

				    $column++;
				    $cellsData[] = array('cell' => $column.($rowCtr+1), 'data' => 'Value');
				    $fillCells[] = $column.($rowCtr+1);
				    $mergeCell[] = $column.$rowCtr;

				    $columnRange[] = $column;
				    $mergeCells[] = implode(':', $mergeCell);
			    }

			    $rowCtr++;
			    foreach ($inventories as $inventory) {
				    $rowCtr++;
				    $cellsData[] = array('cell' => "A$rowCtr", 'data' => $inventory['codes']);
				    $cellsData[] = array('cell' => "B$rowCtr", 'data' => $inventory['item']);

				    $column = "B";
				    foreach ($branches as &$branch) {
					    $qty = '';
					    $ave_cost = '';
					    $total_cost = '';
					    foreach ($inventory['branches'] as $inv_branch) {
						    if($inv_branch['id'] == $branch['id']) {
							    $qty = $inv_branch['quantity'];
							    $ave_cost = $inv_branch['ave_cost'];
							    $total_cost = $inv_branch['total_cost'];
							    $branch['total_qty'] += $qty;
							    $branch['total_cost'] += $ave_cost;
							    $branch['total_value'] += $total_cost;
							    break;
						    }
					    }
					    $column++;
					    $cellsData[] = array('cell' => $column.$rowCtr, 'data' => $qty);
					    $column++;
					    $cellsData[] = array('cell' => $column.$rowCtr, 'data' => $ave_cost);
					    $column++;
					    $cellsData[] = array('cell' => $column.$rowCtr, 'data' => $total_cost);
				    }
			    }
			    $rowCtr++;
			    $cellsData[] = array('cell' => "B$rowCtr", 'data' => 'TOTAL');
			    $fillCells[] = "A$rowCtr:B$rowCtr";

			    $column = "B";
			    foreach ($branches as $branch) {
				    $column++;
				    $fillCell = [$column.$rowCtr];
				    $cellsData[] = array('cell' => $column.$rowCtr, 'data' => $branch['total_qty']);
				    $column++;
				    $cellsData[] = array('cell' => $column.$rowCtr, 'data' => $branch['total_cost']);
				    $column++;
				    $cellsData[] = array('cell' => $column.$rowCtr, 'data' => $branch['total_value']);
				    $fillCell[] = $column.$rowCtr;

				    $fillCells[] = implode(':', $fillCell);
			    }

			    $page_title = 'Inventory Report';
			    return $this->export_to_excel($columnRange, $cellsData, $page_title, [], $fillCells, $mergeCells);
		    	break;
		    //</editor-fold>
	    }
    }

    //Inventory Serial Code Report
    /**
     * @Route("/inventory/serial-code", name="report_inventory_serial_code")
     */
    public function report_inventory_serial_codeAction() {

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

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

        $page_title = 'Inventory Serial Code Report';
        return $this->render('@RxConnexion/Report/InventorySerialCode/index.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/inventory/inventory.js?v=1.0.0'),
	        'branches' => $userData['type'] == 'Super Admin'
		        ? $em->getRepository(HealthFacilityEntity::class)->findAllNotDeleted()
		        : $em->getRepository(HealthFacilityEntity::class)->findAllByIds($userData['branches'], true),
	        'categories' => $em->getRepository(ItemSubCategoryEntity::class)->findBy(['isDeleted' => false], ['description' => 'ASC']),
        ));
    }

    /**
     * @Route(
     *      "/inventory/serial-code/export",
     *      name = "report_inventory_serial_code_export"
     * )
     */
    public function report_inventory_serial_code_exportAction(Request $request) {

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

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

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

        $categories = $request->get('categories');
        $item = $request->get('item');
        $branches = $request->get('branches');
        $status = $request->get('status');
	    $type = $request->get('type');

	    $em = $this->getDoctrine()->getManager();
	    $records = $em->getRepository(InventoryEntity::class)->reportInventorySerialCode($userData, array(
		    'branches' => $branches,
		    'categories' => $categories,
		    'item' => $item,
		    'status' => $status,
	    ));

	    $branches = [];
	    $items = [];
	    foreach ($records as $key => $record) {
		    $records[$key]['serialNos'] = explode(',', $record['serialNos']);
		    $colspan = count($records[$key]['serialNos']);

	    	$e = $this->in_array_assoc($record['branch_id'], 'id', $branches);
	    	if(!$e['exist']) {
	    		$branches[] = ['id' => $record['branch_id'], 'description' => $record['branch'], 'colspan' => $colspan];
		    } else {
	    		if($branches[$e['key']]['colspan'] < $colspan) {
				    $branches[$e['key']]['colspan'] = $colspan;
			    }
		    }

	    	$i = $this->in_array_assoc($record['item_id'], 'id', $items);
	    	if(!$i['exist']) {
	    		$items[] = ['id' => $record['item_id'], 'description' => $record['item'], 'codes' => $record['item_codes']];
		    }
	    }

	    $page_title = "Serial Code Report ($status)" ;
	    switch($type) {
	    	//<editor-fold desc="PREVIEW">
		    case 'preview':
			    if(!$authService->isUserHasAccesses(array('Admin Report Inventory Serial Code Preview'))) return $authService->redirectToHome();

			    return $this->render('@RxConnexion/Report/InventorySerialCode/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,
				    'branches' => $branches,
				    'items' => $items,
			    ));
		    	break;
	        //</editor-fold>
		    //<editor-fold desc="PDF">
		    case 'pdf':
			    $page_title = 'Inventory Report';
			    $content = $this->renderView('@RxConnexion/Report/Inventory/preview.wkpdf.twig', array(
				    'page_title' => $page_title,
				    'records' => $records,
				    'hasCost' => $hasCost,
			    ));

			    $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="Inventory Report' . date('m/d/Y') . ' Details.pdf"'
				    ));
			    } else {
				    $this->get('session')->getFlashBag()->set('error_messages', $pdfResponse['msg']);
				    return $this->redirect($this->generateUrl('report_inventory', 302));
			    }
		    	break;
		    //</editor-fold>
		    //<editor-fold desc="EXCEL">
		    case 'excel' :
			    if(!$authService->isUserHasAccesses(array('Admin Report Inventory Serial Code Excel'))) return $authService->redirectToHome();

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

			    $customStyles = [];
			    $fillCells = [];
			    $mergeCells = [];

			    $rowCtr = 1;
			    $totalCount = 0;

			    $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Code');
			    $cellsData[] = array('cell' => "B$rowCtr", 'data' => 'Item');
			    $column = "B";
			    foreach ($branches as $branch) {
				    $column++;
				    $cellsData[] = array('cell' => "{$column}$rowCtr", 'data' => $branch['description']);

				    $mergeCell_tmp = "{$column}$rowCtr:";
				    for ($cs = 1 ; $cs < $branch['colspan']; $cs++) {
					    $column++;
				    }
				    $mergeCell_tmp .= "{$column}$rowCtr";

				    $mergeCells[] = $mergeCell_tmp;
				    $fillCells[] = $mergeCell_tmp;
			    }

			    foreach ($items as $ik => $item) {
				    $rowCtr ++;

				    $cellsData[] = array('cell' => "A$rowCtr", 'data' => $item['codes']);
				    $cellsData[] = array('cell' => "B$rowCtr", 'data' => $item['description']);

				    $column = "B";
				    foreach ($branches as $bk => $branch) {
					    $remainingColspan = $branch['colspan'];
					    $snCtr = 0;
					    foreach ($records as $rk => $record) {
						    if ($record['item_id'] == $item['id'] && $record['branch_id'] == $branch['id']) {
							    $snCtr ++;
							    foreach ($record['serialNos'] as $serialNo) {
								    $remainingColspan -= 1;
								    $column++;
								    $cellsData[] = array('cell' => "{$column}$rowCtr", 'data' => $serialNo);
							    }
							    if($remainingColspan > 0) {
								    $column++;
								    $mergeCell_tmp = "{$column}$rowCtr:";
								    for ($cs = 1 ; $cs < $remainingColspan; $cs++) {
									    $column++;
								    }
								    $mergeCell_tmp .= "{$column}$rowCtr";
								    $mergeCells[] = $mergeCell_tmp;
							    }
						    }
					    }
					    if($snCtr == 0 && $remainingColspan == $branch['colspan']) {
						    $column++;
						    $mergeCell_tmp = "{$column}$rowCtr:";
						    for ($cs = 1 ; $cs < $branch['colspan']; $cs++) {
							    $column++;
						    }
						    $mergeCell_tmp .= "{$column}$rowCtr";
						    $mergeCells[] = $mergeCell_tmp;
					    }
				    }
			    }

			    return $this->export_to_excel($columnRange, $cellsData, $page_title, $customStyles, $fillCells, $mergeCells);
		    	break;
		    //</editor-fold>
	    }
    }

    //Inventory Transfer Report
    /**
     * @Route("/inventory/transfer", name="report_inventory_transfer")
     */
    public function report_inventory_transferAction() {

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

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

        $page_title = 'Inventory Transfer Report';
        return $this->render('@RxConnexion/Report/InventoryTransfer/index.html.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'javascripts' => array('rxconnexion/admin/js/report/report.js', 'rxconnexion/admin/js/report/inventory/inventory.js?v=1.0.0'),
	        'branches' => $userData['type'] == 'Super Admin'
		        ? $em->getRepository(HealthFacilityEntity::class)->findAllNotDeleted()
		        : $em->getRepository(HealthFacilityEntity::class)->findAllByIds($userData['branches'], true),
	        'categories' => $em->getRepository(ItemSubCategoryEntity::class)->findBy(['isDeleted' => false], ['description' => 'ASC']),
        ));
    }

    /**
     * @Route(
     *      "/inventory/transfer/export",
     *      name = "report_inventory_transfer_export"
     * )
     */
    public function report_inventory_transfer_exportAction(Request $request) {

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

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

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

	    $categories = $request->get('categories');
	    $item = $request->get('item');
	    $date_from = $request->get('date_from');
	    $date_to = $request->get('date_to');
	    $branch_from = $request->get('branch_from');
	    $branch_to = $request->get('branch_to');
	    $type = $request->get('type');

	    $em = $this->getDoctrine()->getManager();
	    $records = $em->getRepository(InventoryEntity::class)->reportInventoryTransfer($userData, array(
		    'date_from' => $date_from,
		    'date_to' => $date_to,
		    'branch_from' => $branch_from,
		    'branch_to' => $branch_to,
		    'categories' => $categories,
		    'item' => $item,
	    ));
	    /*echo '<pre>';
	    print_r($records);
	    die();*/

	    $transfers = [];
	    foreach ($records as $k => $record) {

		    $items = [];
		    foreach (explode('@@', $record['items']) as $item) {
			    $item = explode('~~', $item);
			    $items[] = [
				    'id' => $item[0],
				    'description' => $item[1],
				    'quantity' => $item[2],
				    'ave_cost' => $item[3],
				    'codes' => $item[4],
			    ];
		    }
		    $records[$k]['items'] = $items;

		    $e = $this->in_array_assoc($record['from_to'], 'from_to', $transfers);
		    if(!$e['exist']) {
		    	$items_tmp = [];
			    foreach ($items as $item) {
				    $i = $this->in_array_assoc($item['id'], 'id', $items_tmp);
				    if($i['exist']) {
					    $items_tmp[$i['key']]['quantity'] += $item['quantity'];
					    $items_tmp[$i['key']]['ave_cost'] += $item['ave_cost'];
				    } else {
					    $items_tmp[] = $item;
				    }
			    }

		    	$transfers[] = [
				    'from_to' => $record['from_to'],
				    'transfer_inventories' => [['id' => $record['id'], 'transfer_no' => $record['transfer_no']]],
				    'branch_from_id' => $record['branch_from_id'],
				    'branch_from' => $record['branch_from'],
				    'branch_to_id' => $record['branch_to_id'],
				    'branch_to' => $record['branch_to'],
				    'items' => $items_tmp
			    ];
		    } else {
			    $transfers[$e['key']]['transfer_inventories'][] = ['id' => $record['id'], 'transfer_no' => $record['transfer_no']];
			    foreach ($records[$k]['items'] as $item) {
				    $i = $this->in_array_assoc($item['id'], 'id', $transfers[$e['key']]['items']);
				    if($i['exist']) {
					    $transfers[$e['key']]['items'][$i['key']]['quantity'] += $item['quantity'];
					    $transfers[$e['key']]['items'][$i['key']]['ave_cost'] += $item['ave_cost'];
				    } else {
					    $transfers[$e['key']]['items'][] = $item;
				    }
		    	}
		    }
	    }


	    switch($type) {
	    	//<editor-fold desc="PREVIEW">
		    case 'preview':
			    if(!$authService->isUserHasAccesses(array('Admin Report Inventory Transfer Preview'))) return $authService->redirectToHome();
			   
			    $page_title = 'Inventory Transfer Report';
			    return $this->render('@RxConnexion/Report/InventoryTransfer/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'),
				    'transfers' => $transfers,
			    ));
		    	break;
	        //</editor-fold>
		    //<editor-fold desc="PDF">
		    case 'pdf':
			    $page_title = 'Inventory Report';
			    $content = $this->renderView('@RxConnexion/Report/Inventory/preview.wkpdf.twig', array(
				    'page_title' => $page_title,
				    'records' => $records,
				    'hasCost' => $hasCost,
			    ));

			    $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="Inventory Report' . date('m/d/Y') . ' Details.pdf"'
				    ));
			    } else {
				    $this->get('session')->getFlashBag()->set('error_messages', $pdfResponse['msg']);
				    return $this->redirect($this->generateUrl('report_inventory', 302));
			    }
		    	break;
		    //</editor-fold>
		    //<editor-fold desc="EXCEL">
		    case 'excel' :
			    if(!$authService->isUserHasAccesses(array('Admin Report Inventory Transfer Excel'))) return $authService->redirectToHome();

			    $columnRange = ['A', 'E'];
			    $cellsData = array();

			    $rowCtr = 0;
			    $totalCount = 0;

			    $customStyles = [];
			    $fillCells = [];
			    $mergeCells = [];

			    foreach ($transfers as $transfer) {
				    $rowCtr++;
				    $cellsData[] = array('cell' => "A$rowCtr", 'data' => "From " . $transfer['branch_from'] . ' To ' . $transfer['branch_to']);
				    $mergeCells[] = "A$rowCtr:E$rowCtr";
				    $fillCells[] = "A$rowCtr:E$rowCtr";


				    $rowCtr++;
				    $cellsData[] = array('cell' => "A$rowCtr", 'data' => "Code");
				    $cellsData[] = array('cell' => "B$rowCtr", 'data' => "Item");
				    $cellsData[] = array('cell' => "C$rowCtr", 'data' => "Quantity");
				    $cellsData[] = array('cell' => "D$rowCtr", 'data' => "Cost");
				    $cellsData[] = array('cell' => "E$rowCtr", 'data' => "Transfer Value");
				    $fillCells[] = "A$rowCtr:E$rowCtr";


				    $totalQty = 0;
				    $totalAveCost = 0;
				    $totalValue = 0;
				    foreach ($transfer['items'] as $item) {
					    $rowCtr++;

					    $totalQty += $item['quantity'];
					    $totalAveCost += $item['ave_cost'];
					    $totalValue += ($item['quantity'] * $item['ave_cost']);

					    $cellsData[] = array('cell' => "A$rowCtr", 'data' => $item['codes']);
					    $cellsData[] = array('cell' => "B$rowCtr", 'data' => $item['description']);
					    $cellsData[] = array('cell' => "C$rowCtr", 'data' => number_format($item['quantity'], 0));
					    $cellsData[] = array('cell' => "D$rowCtr", 'data' => number_format($item['ave_cost'], 2));
					    $cellsData[] = array('cell' => "E$rowCtr", 'data' => number_format(($item['quantity'] * $item['ave_cost']), 2));

				    }

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

				    $cellsData[] = array('cell' => "C$rowCtr", 'data' => number_format($totalQty, 2));
				    $cellsData[] = array('cell' => "D$rowCtr", 'data' => number_format($totalAveCost, 2));
				    $cellsData[] = array('cell' => "E$rowCtr", 'data' => number_format($totalValue, 2));


				    $rowCtr++;
				    $rowCtr++;
			    }
			    

			    $page_title = 'Inventory Transfer Report';
			    return $this->export_to_excel($columnRange, $cellsData, $page_title, $customStyles, $fillCells, $mergeCells);
		    	break;
		    //</editor-fold>
	    }
    }

    //Inventory Items Sold
    /**
     * @Route("/inventory/items_sold", name="report_inventory_items_sold")
     */
    public function report_inventory_items_soldAction() {

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

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

        $page_title = 'Inventory Item Sold Report';
        return $this->render('@RxConnexion/Report/InventoryItemSold/index.html.twig', array(
            'title'       => $page_title,
            'page_title'  => $page_title,
            'javascripts' => array(
	            'rxconnexion/admin/js/report/report.js',
	            'rxconnexion/admin/js/report/inventory/inventory.js?v=1.0.0',
            ),
            'branches'    => $userData['type'] == 'Super Admin' ? $em->getRepository(HealthFacilityEntity::class)->findAllNotDeleted() : $em->getRepository(HealthFacilityEntity::class)->findAllByIds($userData['branches'], TRUE),
            'categories'  => $em->getRepository(ItemSubCategoryEntity::class)->findBy(['isDeleted' => false], ['description' => 'ASC']),
        ));
    }

    /**
     * @Route(
     *      "/inventory/items_sold/export",
     *      name = "report_inventory_items_sold_export"
     * )
     */
    public function report_inventory_items_sold_exportAction(Request $request) {

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

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

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

        $categories = $request->get('categories');
        $item = $request->get('item');
        $branches = $request->get('branches');
        $date_from = $request->get('date_from');
        $date_to = $request->get('date_to');
        $include_0_item_cost = $request->get('include_0_item_cost');
	    $type = $request->get('type');

	    $em = $this->getDoctrine()->getManager();
	    $records = $em->getRepository(InventoryEntity::class)->reportInventorySold($userData, array(
		    'branches'            => $branches,
		    'categories'          => $categories,
		    'item'                => $item,
		    'date_from'           => $date_from,
		    'date_to'             => $date_to,
		    'include_0_item_cost' => $include_0_item_cost,
	    ));


	    $branches = [];
	    $items = [];
	    foreach ($records as $key => $record) {
		    $e = $this->in_array_assoc($record['branch_id'], 'id', $branches);
		    if(!$e['exist']) {
			    $branches[] = [
				    'id'             => $record['branch_id'],
				    'description'    => $record['branch'],
				    'totalQty'       => $record['totalQty'],
				    'totalSoldValue' => $record['totalSoldValue'],
			    ];
		    } else {
			    $branches[$e['key']]['totalQty'] += $record['totalQty'];
			    $branches[$e['key']]['totalSoldValue'] += $record['totalSoldValue'];
		    }

		    $i = $this->in_array_assoc($record['item_id'], 'id', $items);
		    if(!$i['exist']) {
			    $items[] = [
				    'id'          => $record['item_id'],
				    'description' => $record['item'],
				    'codes'       => $record['item_codes'],
			    ];
		    }
	    }

	    switch($type) {
	    	//<editor-fold desc="PREVIEW">
		    case 'preview':
			    if(!$authService->isUserHasAccesses(array('Admin Report Inventory Items Sold Preview'))) return $authService->redirectToHome();

			    $page_title = 'Inventory Item Sold Report';
			    return $this->render('@RxConnexion/Report/InventoryItemSold/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,
				    'branches'    => $branches,
				    'items'       => $items,
			    ));
		    	break;
	        //</editor-fold>
		    //<editor-fold desc="PDF">
		    case 'pdf':
			    $page_title = 'Inventory Report';
			    $content = $this->renderView('@RxConnexion/Report/Inventory/preview.wkpdf.twig', array(
				    'page_title' => $page_title,
				    'records'    => $records,
				    'hasCost'    => $hasCost,
			    ));

			    $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="Inventory Report' . date('m/d/Y') . ' Details.pdf"'
				    ));
			    } else {
				    $this->get('session')->getFlashBag()->set('error_messages', $pdfResponse['msg']);
				    return $this->redirect($this->generateUrl('report_inventory', 302));
			    }
		    	break;
		    //</editor-fold>
		    //<editor-fold desc="EXCEL">
		    case 'excel' :
			    if(!$authService->isUserHasAccesses(array('Admin Report Inventory Items Sold Excel'))) return $authService->redirectToHome();

			    $columnRange = range('A', 'B');
			    $cellsData = array();

			    $customStyles = [];
			    $fillCells = [];
			    $mergeCells = [];

			    $rowCtr = 2;
			    $totalCount = 0;

			    $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Code');
			    $cellsData[] = array('cell' => "B$rowCtr", 'data' => 'Item');
			    $fillCells[] = "A$rowCtr:B$rowCtr";
			    $column = "B";
			    foreach ($branches as $branch) {
				    $column++;
				    $cellsData[] = array('cell' => "{$column}".($rowCtr-1), 'data' => $branch['description']);
				    $cellsData[] = array('cell' => "{$column}$rowCtr", 'data' => 'Qty');
				    $mergeCell_tmp = $column.($rowCtr-1).":";
				    $mergeCell_tmp2 = $column.$rowCtr.":";

				    $column++;
				    $cellsData[] = array('cell' => "{$column}$rowCtr", 'data' => 'Sold Value');
				    $mergeCell_tmp .= $column.($rowCtr-1);
				    $mergeCell_tmp2 .= $column.$rowCtr;


				    $mergeCells[] = $mergeCell_tmp;
				    $fillCells[] = $mergeCell_tmp;
				    $fillCells[] = $mergeCell_tmp2;

			    }

			    foreach ($items as $ik => $item) {
				    $rowCtr ++;

				    $cellsData[] = array('cell' => "A$rowCtr", 'data' => $item['codes']);
				    $cellsData[] = array('cell' => "B$rowCtr", 'data' => $item['description']);

				    $column = "B";
				    foreach ($branches as $bk => $branch) {

					    foreach ($records as $rk => $record) {
						    if ($record['item_id'] == $item['id'] && $record['branch_id'] == $branch['id']) {
							    $column++;
							    $cellsData[] = array('cell' => "{$column}$rowCtr", 'data' => $record['totalQty']);
							    $column++;
							    $cellsData[] = array('cell' => "{$column}$rowCtr", 'data' => $record['totalSoldValue']);
							    break;
						    }
					    }
				    }
			    }


			    $rowCtr ++;
			    $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'Total');
			    $column = "B";
			    foreach ($branches as $bk => $branch) {
				    $column++;
				    $cellsData[] = array('cell' => "{$column}$rowCtr", 'data' => $branch['totalQty']);
				    $column++;
				    $cellsData[] = array('cell' => "{$column}$rowCtr", 'data' => $branch['totalSoldValue']);
			    }

			    $page_title = 'Inventory Item Sold';
			    return $this->export_to_excel($columnRange, $cellsData, $page_title, $customStyles, $fillCells, $mergeCells);
		    	break;
		    //</editor-fold>
	    }
    }


    //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', 'L');
        $cellsData = array(
            array('cell' => 'A1', 'data' => 'Fax Date'),
            array('cell' => 'B1', 'data' => 'Patient Name'),
            array('cell' => 'C1', 'data' => 'Fax Category'),
            array('cell' => 'D1', 'data' => 'Fax #'),
            array('cell' => 'E1', 'data' => 'Company'),
            array('cell' => 'F1', 'data' => 'Branch'),
            array('cell' => 'G1', 'data' => 'Assigned To'),
            array('cell' => 'H1', 'data' => 'File Name'),
            array('cell' => 'I1', 'data' => 'Pages'),
            array('cell' => 'J1', 'data' => 'Duplicate'),
            array('cell' => 'K1', 'data' => 'Existing'),
            array('cell' => 'L1', '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['patientName']);
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => $record['fax_category']);
            $cellsData[] = array('cell' => "D$rowCtr", 'data' => $record['faxNo'] == null ? '8332624798' : $record['faxNo']);
            $cellsData[] = array('cell' => "E$rowCtr", 'data' => $record['companyDesc']);
            $cellsData[] = array('cell' => "F$rowCtr", 'data' => $record['branchDesc']);
            $cellsData[] = array('cell' => "G$rowCtr", 'data' => $record['assignTo']);
            $cellsData[] = array('cell' => "H$rowCtr", 'data' => $record['file_name']);
            $cellsData[] = array('cell' => "I$rowCtr", 'data' => $record['pages']);
            $cellsData[] = array('cell' => "J$rowCtr", 'data' => $record['isDuplicate']);
            $cellsData[] = array('cell' => "K$rowCtr", 'data' => $record['isExisting']);
            $cellsData[] = array('cell' => "L$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);
        $referringHealthFacilities = $em->getRepository('RxConnexionBundle:ReferringHealthFacilityEntity')->referringHealthFacilityForMultiple();
        $referringProviders = $em->getRepository('RxConnexionBundle:ReferringProviderEntity')->referringProviderForMultiple();
        $services = $em->getRepository('RxConnexionBundle:ServiceEntity')->servicesForMultiple();
        $providers = $em->getRepository('RxConnexionBundle:ProviderEntity')->clinicianForMultiple();
        $fileTypes = $em->getRepository('RxConnexionBundle:FileTypeEntity')->fileTypesForMultiple();

        $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,
            'referringHealthFacility' => $referringHealthFacilities,
            'referringProvider' => $referringProviders,
            'services' => $services,
            'providers' => $providers,
            'fileTypes' => $fileTypes,
            '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}/{referring_health_facility}/{referring_provider}/{chartType}/{chartStatus}/{service}/{primary_provider}/{fileType}/{is_due}",
     *      name = "report_patient_cycle_preview"
     * )
     */
    public function reportPatientCycle_previewAction($date_from, $date_to, $receive_date_from, $receive_date_to, $company, $branch, $referring_health_facility, $referring_provider, $chartType, $chartStatus, $service, $primary_provider, $fileType, $is_due, Request $request) {

        $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();

        $chartTypeGroups = $em->getRepository('RxConnexionBundle:ChartTypeGroupEntity')->findBy(array(
            'isDeleted' => false
        ));

        $expectedNoOfDays = array();
        foreach ($chartTypeGroups as $chartTypeGroup) {
            if($chartTypeGroup->getDescription() == 'Pre-HSAT') {
                $expectedNoOfDays['ipc'] = $chartTypeGroup->getExpectedNoOfDays();
            }
            if($chartTypeGroup->getDescription() == 'HSAT') {
                $expectedNoOfDays['hsat'] = $chartTypeGroup->getExpectedNoOfDays();
            }
            if($chartTypeGroup->getDescription() == 'HSAT Repeat') {
                $expectedNoOfDays['hsat_repeat'] = $chartTypeGroup->getExpectedNoOfDays();
            }
            if($chartTypeGroup->getDescription() == 'HSAT Results Interpretation') {
                $expectedNoOfDays['hri'] = $chartTypeGroup->getExpectedNoOfDays();
            }
            if($chartTypeGroup->getDescription() == 'PFT') {
                $expectedNoOfDays['pft'] = $chartTypeGroup->getExpectedNoOfDays();
            }
            if($chartTypeGroup->getDescription() == 'Prescription') {
                $expectedNoOfDays['prescription'] = $chartTypeGroup->getExpectedNoOfDays();
            }
            if($chartTypeGroup->getDescription() == 'CPAP Setup') {
                $expectedNoOfDays['cpap_setup'] = $chartTypeGroup->getExpectedNoOfDays();
            }
            if($chartTypeGroup->getDescription() == '6 Month Follow Up') {
                $expectedNoOfDays['six_mo_ff'] = $chartTypeGroup->getExpectedNoOfDays();
            }
        }

        $invoiceDue = $em->getRepository('RxConnexionBundle:SystemParameterEntity')->findOneBy(array(
            'description' => 'Invoice Expected Days',
            'isDeleted' => false
        ));
        $expectedNoOfDays['invoice'] = $invoiceDue ? $invoiceDue->getValue() : null;

        $records = $em->getRepository('RxConnexionBundle:PatientEntity')->reportPatientCycle2(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,
            'chartType' => $chartType,
            'chartStatus' => $chartStatus,
            'referringHealthFacility' => $referring_health_facility,
            'referringProvider' => $referring_provider,
            'service' => $service,
            'primary_provider' => $primary_provider,
            'fileType' => $fileType,
            'is_due' => $is_due,
            'userData' => $userData,
            // 'unbooked_only' => $request->get('unbooked_only'),
        ));

        $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?v=1.0.2'),
            'records' => $records,
            'date_from' => $date_from,
            'date_to' => $date_to,
            'receive_date_from' => $receive_date_from,
            'receive_date_to' => $receive_date_to,
            'company' => $company,
            'branch' => $branch,
            'chart_type' => $chartType,
            'chart_status' => $chartStatus,
            'referringHealthFacility' => $referring_health_facility,
            'referringProvider' => $referring_provider,
            'service' => $service,
            'fileType' => $fileType,
            'is_due' => $is_due,
            'expectedNoOfDays' => $expectedNoOfDays,
            // 'unbooked_only' => $request->get('unbooked_only'),
        ));
    }

    /**
     * @Route(
     *      "/patient_cycle/redirect/link/preview/{date_from}/{date_to}/{receive_date_from}/{receive_date_to}/{company}/{branch}/{referring_health_facility}/{referring_provider}/{chartType}/{chartStatus}/{service}/{primary_provider}/{fileType}/{is_due}",
     *      defaults = {
     *          "date_from" = null,
     *          "date_to" = null,
     *          "receive_date_from" = null,
     *          "receive_date_to" = null,
     *          "company" = null,
     *          "branch" = null,
     *          "referring_health_facility" = null,
     *          "referring_provider" = null,
     *          "chartType" = null,
     *          "chartStatus" = null,
     *          "service" = null,
     *          "primary_provider" = null,
     *          "fileType" = null,
     *          "is_due" = null,
     *      },
     *
     *      name = "report_link_patient_cycle_report_redirect_preview",
     *
     * )
     */
    public function patientCycle_redirect_previewAction($date_from, $date_to, $receive_date_from, $receive_date_to, $company, $branch, $referring_health_facility, $referring_provider, $chartType, $chartStatus, $service, $primary_provider, $fileType, $is_due) {

        return $this->redirect($this->generateUrl('report_patient_cycle_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',
            'company' => $company != 'null' ? $company : 'null',
            'branch' => $branch != 'null' ? $branch : 'null',
            'referring_health_facility' => $referring_health_facility != 'null' ? $referring_health_facility : 'null',
            'referring_provider' => $referring_provider != 'null' ? $referring_provider : 'null',
            'chartType' => $chartType != 'null' ? $chartType : 'null',
            'chartStatus' => $chartStatus != 'null' ? $chartStatus : 'null',
            'service' => $service != 'null' ? $service : 'null',
            'primary_provider' => $primary_provider != 'null' ? $primary_provider : 'null',
            'fileType' => $fileType != 'null' ? $fileType : 'null',
            'is_due' => $is_due != 'null' ? $is_due : 'null',
        )), 302);
    }

    /**
     * @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
        ));
    }

    /**
     * @Route("/marketing_encounter", name="report_marketing_encounter")
     */
    public function marketing_encounterAction() {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Marketing 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 = 'Marketing Encounter Report';
        return $this->render('@RxConnexion/Report/MarketingEncounter/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/marketingEncounter/marketingEncounter.js?v=1.0.2')
        ));
    }

    /**
     * @Route(
     *      "/encounter/preview/{date_from}/{date_to}/{company_id}/{branch_id}/{marketing_staff_id}/{encountertype_id}/{encounter_status}/{user_id}/{status}/{type}",
     *      name = "report_marketing_encounter_preview"
     * )
     */
    public function marketing_encounter_previewAction($date_from, $date_to, $company_id, $branch_id, $marketing_staff_id, $encountertype_id, $encounter_status, $user_id, $status, $type) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Marketing 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:PatientEntity')->reportMarketingEncounter(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company_id,
            'branch' => $branch_id,
            'marketing_staff' => $marketing_staff_id,
            'encounter_type' => $encountertype_id,
            'encounter_status' => $encounter_status,
            'user_id' => $user_id,
            'patient_status' => $status,
            'type' => $type,
            '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 = 'Marketing Encounter Report';
        return $this->render('@RxConnexion/Report/MarketingEncounter/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,
            'type' => $type,
        ));
    }

    /**
     * @Route(
     *      "/encounter/export_to_pdf/{date_from}/{date_to}/{company_id}/{branch_id}/{marketing_staff_id}/{encountertype_id}/{encounter_status}/{user_id}/{status}/{type}",
     *      name = "report_marketing_encounter_export_to_pdf"
     * )
     */
    public function marketing_encounter_export_to_pdfAction($date_from, $date_to, $company_id, $branch_id, $marketing_staff_id, $encountertype_id, $encounter_status, $user_id, $status, $type) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Marketing 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:PatientEntity')->reportMarketingEncounter(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company_id,
            'branch' => $branch_id,
            'marketing_staff' => $marketing_staff_id,
            'encounter_type' => $encountertype_id,
            'encounter_status' => $encounter_status,
            'user_id' => $user_id,
            'patient_status' => $status,
            'type' => $type,
            '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 = 'Marketing Encounter Report';
        $content = $this->renderView('@RxConnexion/Report/MarketingEncounter/preview.wkpdf.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'date_from' => $date_from,
            'date_to' => $date_to,
            'records' => $records,
            'type' => $type,
            '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="Marketing 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}/{marketing_staff_id}/{encountertype_id}/{encounter_status}/{user_id}/{status}/{type}",
     *      name = "report_marketing_encounter_export_to_excel"
     * )
     */
    public function marketing_encounter_export_to_excelAction($date_from, $date_to, $company_id, $branch_id, $marketing_staff_id, $encountertype_id, $encounter_status, $user_id, $status, $type) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Marketing 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:PatientEntity')->reportMarketingEncounter(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'company' => $company_id,
            'branch' => $branch_id,
            'marketing_staff' => $marketing_staff_id,
            'encounter_type' => $encountertype_id,
            'encounter_status' => $encounter_status,
            'user_id' => $user_id,
            'patient_status' => $status,
            'type' => $type,
            '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');

        if($type == 'rhf') {


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

                $explodedPs = explode(',', $record['notes']);

                $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['referringHealthFacilityDesc']);
                $cellsData[] = array('cell' => "E$rowCtr", 'data' => $record['branch']);
                $cellsData[] = array('cell' => "F$rowCtr", 'data' => $record['marketingStaffName']);
                $cellsData[] = array('cell' => "G$rowCtr", 'data' => $record['encounterType']);
                $cellsData[] = array('cell' => "H$rowCtr", 'data' => $record['encounterStatus']);
                foreach ($explodedPs as $ps) {
                    $notes = explode('|', $ps);
                    $cellsData[] = array('cell' => "I$rowCtr", 'data' => isset($notes[1]) ? $notes[1] : '');
                    if(count($notes) > 1) {
                        $rowCtr++;
                    }
                }
            }
        }

        if($type == 'rp') {


            $cellsData = array(
                array('cell' => 'A1', 'data' => 'Encounter ID'),
                array('cell' => 'B1', 'data' => 'Staff'),
                array('cell' => 'C1', 'data' => 'Encounter Date'),
                array('cell' => 'D1', 'data' => 'Referring Physician'),
                array('cell' => 'E1', 'data' => 'Branch'),
                array('cell' => 'F1', 'data' => 'Marketing Staff'),
                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++;
                $explodedPs = explode(',', $record['notes']);

                $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['referringProviderDesc']);
                $cellsData[] = array('cell' => "E$rowCtr", 'data' => $record['branch']);
                $cellsData[] = array('cell' => "F$rowCtr", 'data' => $record['marketingStaffName']);
                $cellsData[] = array('cell' => "G$rowCtr", 'data' => $record['encounterType']);
                $cellsData[] = array('cell' => "H$rowCtr", 'data' => $record['encounterStatus']);
                foreach ($explodedPs as $ps) {
                    $notes = explode('|', $ps);
                    $cellsData[] = array('cell' => "I$rowCtr", 'data' => isset($notes[1]) ? $notes[1] : '');
                    if(count($notes) > 1) {
                        $rowCtr++;
                    }
                }
            }
        }


        $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 = 'Marketing Encounter Report';
        return $this->export_to_excel($columnRange, $cellsData, $page_title);
    }

    /**
     * @Route("/daily_encounter_target", name="report_daily_encounter_target")
     */
    public function reportDailyEncounterTargetAction() {

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

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

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

    /**
     * @Route(
     *      "/daily_encounter_target/preview/{date_from}/{date_to}",
     *      name = "report_daily_encounter_target_preview"
     * )
     */
    public function reportDailyEncounterTarget_previewAction($date_from, $date_to) {

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

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

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

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

    /**
     * @Route("/marketing_cycle", name="report_marketing_cycle")
     */
    public function marketing_cycleAction() {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Marketing 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);
        $encounterType = $em->getRepository('RxConnexionBundle:ChartTypeEntity')->chartTypeForMultiple();
        $referringAffiliates = $em->getRepository('RxConnexionBundle:ReferringHealthFacilityEntity')->referringHealthFacilityForMultiple();
        $referringPhysicians = $em->getRepository('RxConnexionBundle:ReferringProviderEntity')->referringProviderForMultiple();
        $encounterStatus = $em->getRepository('RxConnexionBundle:PatientChartEntity')->findEncounterTypeStatus();

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

    /**
     * @Route(
     *      "/marketing_cycle/preview/{date_from}/{date_to}/{branch_id}/{encountertype_id}/{encounter_status}/{referring_health_facility}/{referring_physician}",
     *      name = "report_marketing_cycle_preview"
     * )
     */
    public function marketing_cycle_previewAction($date_from, $date_to, $branch_id, $encountertype_id, $encounter_status, $referring_health_facility, $referring_physician) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Marketing 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')->reportMarketingEncounter(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'branch' => $branch_id,
            'encounter_type' => $encountertype_id,
            'encounter_status' => $encounter_status,
            'referring_health_facility' => $referring_health_facility,
            'referring_provider' => $referring_provider,
            'userData' => $userData
        ));

        $page_title = 'Marketing Cycle Report';
        return $this->render('@RxConnexion/Report/MarketingCycle/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,
            'type' => $type,
        ));
    }

    /**
     * @Route(
     *      "/marketing_cycle/export_to_pdf/{date_from}/{date_to}/{branch_id}/{encountertype_id}/{encounter_status}/{referring_health_facility}/{referring_physician}",
     *      name = "report_marketing_cycle_export_to_pdf"
     * )
     */
    public function marketing_cycle_export_to_pdfAction($date_from, $date_to, $branch_id, $encountertype_id, $encounter_status, $referring_health_facility, $referring_physician) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Marketing 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:PatientEntity')->reportMarketingEncounter(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'branch' => $branch_id,
            'encounter_type' => $encountertype_id,
            'encounter_status' => $encounter_status,
            'referring_health_facility' => $referring_health_facility,
            'referring_provider' => $referring_provider,
            'userData' => $userData
        ));

        $page_title = 'Marketing Cycle Report';
        $content = $this->renderView('@RxConnexion/Report/MarketingCycle/preview.wkpdf.twig', array(
            'title' => $page_title,
            'page_title' => $page_title,
            'date_from' => $date_from,
            'date_to' => $date_to,
            'records' => $records,
            'type' => $type,
            '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="Marketing 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(
     *      "/marketing_cycle/export_to_excel/{date_from}/{date_to}/{branch_id}/{encountertype_id}/{encounter_status}/{referring_health_facility}/{referring_physician}",
     *      name = "report_marketing_cycle_export_to_excel"
     * )
     */
    public function marketing_cycle_export_to_excelAction($date_from, $date_to, $branch_id, $encountertype_id, $encounter_status, $referring_health_facility, $referring_physician) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Marketing 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:PatientEntity')->reportMarketingEncounter(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'branch' => $branch_id,
            'encounter_type' => $encountertype_id,
            'encounter_status' => $encounter_status,
            'referring_health_facility' => $referring_health_facility,
            'referring_physician' => $referring_physician,
            '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');

        if($type == 'rhf') {


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

                $explodedPs = explode(',', $record['notes']);

                $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['referringHealthFacilityDesc']);
                $cellsData[] = array('cell' => "E$rowCtr", 'data' => $record['branch']);
                $cellsData[] = array('cell' => "F$rowCtr", 'data' => $record['marketingStaffName']);
                $cellsData[] = array('cell' => "G$rowCtr", 'data' => $record['encounterType']);
                $cellsData[] = array('cell' => "H$rowCtr", 'data' => $record['encounterStatus']);
                foreach ($explodedPs as $ps) {
                    $notes = explode('|', $ps);
                    $cellsData[] = array('cell' => "I$rowCtr", 'data' => isset($notes[1]) ? $notes[1] : '');
                    if(count($notes) > 1) {
                        $rowCtr++;
                    }
                }
            }
        }

        if($type == 'rp') {


            $cellsData = array(
                array('cell' => 'A1', 'data' => 'Encounter ID'),
                array('cell' => 'B1', 'data' => 'Staff'),
                array('cell' => 'C1', 'data' => 'Encounter Date'),
                array('cell' => 'D1', 'data' => 'Referring Physician'),
                array('cell' => 'E1', 'data' => 'Branch'),
                array('cell' => 'F1', 'data' => 'Marketing Staff'),
                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++;
                $explodedPs = explode(',', $record['notes']);

                $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['referringProviderDesc']);
                $cellsData[] = array('cell' => "E$rowCtr", 'data' => $record['branch']);
                $cellsData[] = array('cell' => "F$rowCtr", 'data' => $record['marketingStaffName']);
                $cellsData[] = array('cell' => "G$rowCtr", 'data' => $record['encounterType']);
                $cellsData[] = array('cell' => "H$rowCtr", 'data' => $record['encounterStatus']);
                foreach ($explodedPs as $ps) {
                    $notes = explode('|', $ps);
                    $cellsData[] = array('cell' => "I$rowCtr", 'data' => isset($notes[1]) ? $notes[1] : '');
                    if(count($notes) > 1) {
                        $rowCtr++;
                    }
                }
            }
        }


        $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 = 'Marketing Encounter Report';
        return $this->export_to_excel($columnRange, $cellsData, $page_title);
    }

    /**
     * @Route(
     *      "/inventory/export_to_excel/{branch}/{location}/{status}/{item}",
     *      defaults = {
     *          "branch": "null",
     *          "location": "null",
     *          "status": "null",
     *          "item":null
     *      },
     *      name = "report_inventory_export_to_excel"
     * )
     */
    public function inventory_export_to_excelAction($branch, $location,$status,$item) {

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

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

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:InventoryEntity')->reportInventory($this->get('session')->get('userData'), $branch, $location,InventoryEntity::STATUS_STOCK_ON_HAND, $item);
	    //print_r($records);die();
        $inventories = [];
        $branches = [];

	    foreach ($records as $record) {

	    	// branch
	    	$b = $this->in_array_assoc($record['branch_id'], 'id', $branches);
	    	if(!$b['exist']){
			    $branches[] = [
				    'id'            => $record['branch_id'],
				    'description'   => $record['branch'],
				    'total_qty'     => 0,
				    'total_cost'    => 0,
				    'total_value'   => 0,
			    ];
		    }

	    	// item
		    $c = $this->in_array_assoc_multiple([
		    	['val' => $record['item_id'], 'key' => 'item_id'],
		    	['val' => $record['status'], 'key' => 'status'],
		    ], $inventories);
		    if($c['exist']) {
			    $inventories[$c['key']]['branches'][] = [
				    'id'            => $record['branch_id'],
				    'description'   => $record['branch'],
				    'quantity'      => $record['quantity'],
				    'ave_cost'      => $record['ave_cost'],
				    'total_cost'    => $record['quantity'] * $record['ave_cost'],
			    ];
		    } else {
		    	$inventories[] = [
		    		'item_id'   => $record['item_id'],
		    		'item'      => $record['item'],
				    'codes'     => $record['codes'],
				    'status'    => $record['status'],
				    'branches'  => [
				    	[
						    'id'           => $record['branch_id'],
						    'description'  => $record['branch'],
						    'quantity'     => $record['quantity'],
						    'ave_cost'     => $record['ave_cost'],
						    'total_cost'   => $record['quantity'] * $record['ave_cost'],
					    ]
				    ]
			    ];
		    }
        }

        $columnRange = range('A', 'C');
        $cellsData = [];
	    $fillCells = [];
	    $mergeCells = [];

        $rowCtr = 1;

	    $cellsData[] = array('cell' => "A".($rowCtr+1), 'data' => 'Code');
	    $cellsData[] = array('cell' => "B".($rowCtr+1), 'data' => 'Item');
	    $fillCells[] = "A".($rowCtr+1);
	    $fillCells[] = "B".($rowCtr+1);

	    $column = "B";
	    foreach ($branches as $branch) {
		    $column++;
		    $fillCells[] = $column.$rowCtr;
		    $mergeCell = [$column.$rowCtr];
		    $cellsData[] = array('cell' => "{$column}$rowCtr", 'data' => $branch['description']);
		    $cellsData[] = array('cell' => $column.($rowCtr+1), 'data' => 'Qty');
		    $fillCells[] = $column.($rowCtr+1);

		    $column++;
		    $cellsData[] = array('cell' => $column.($rowCtr+1), 'data' => 'Cost');
		    $fillCells[] = $column.($rowCtr+1);

		    $column++;
		    $cellsData[] = array('cell' => $column.($rowCtr+1), 'data' => 'Value');
		    $fillCells[] = $column.($rowCtr+1);
		    $mergeCell[] = $column.$rowCtr;

		    $columnRange[] = $column;
		    $mergeCells[] = implode(':', $mergeCell);
	    }

	    $rowCtr++;
	    foreach ($inventories as $inventory) {
		    $rowCtr++;
		    $cellsData[] = array('cell' => "A$rowCtr", 'data' => $inventory['codes']);
		    $cellsData[] = array('cell' => "B$rowCtr", 'data' => $inventory['item']);

		    $column = "B";
		    foreach ($branches as &$branch) {
			    $qty = '';
			    $ave_cost = '';
			    $total_cost = '';
			    foreach ($inventory['branches'] as $inv_branch) {
				    if($inv_branch['id'] == $branch['id']) {
					    $qty = $inv_branch['quantity'];
					    $ave_cost = $inv_branch['ave_cost'];
					    $total_cost = $inv_branch['total_cost'];
					    $branch['total_qty'] += $qty;
					    $branch['total_cost'] += $ave_cost;
					    $branch['total_value'] += $total_cost;
					    break;
				    }
			    }
			    $column++;
			    $cellsData[] = array('cell' => $column.$rowCtr, 'data' => $qty);
			    $column++;
			    $cellsData[] = array('cell' => $column.$rowCtr, 'data' => $ave_cost);
			    $column++;
			    $cellsData[] = array('cell' => $column.$rowCtr, 'data' => $total_cost);
		    }
	    }
	    $rowCtr++;
	    $cellsData[] = array('cell' => "B$rowCtr", 'data' => 'TOTAL');
	    $fillCells[] = "A$rowCtr:B$rowCtr";

	    $column = "B";
	    foreach ($branches as $branch) {
		    $column++;
		    $fillCell = [$column.$rowCtr];
		    $cellsData[] = array('cell' => $column.$rowCtr, 'data' => $branch['total_qty']);
		    $column++;
		    $cellsData[] = array('cell' => $column.$rowCtr, 'data' => $branch['total_cost']);
		    $column++;
		    $cellsData[] = array('cell' => $column.$rowCtr, 'data' => $branch['total_value']);
		    $fillCell[] = $column.$rowCtr;

		    $fillCells[] = implode(':', $fillCell);
	    }

	    /*$rowCtr+=3;
	    $cellsData[] = array('cell' => "A$rowCtr", 'data' => 'SUMMARY');
	    $mergeCells[] = "A$rowCtr:D$rowCtr";
	    foreach ($branches as $branch) {
	    	$totalBranchCost = 0;
		    $rowCtr++;
		    $branchRow = $rowCtr;
		    $cellsData[] = array('cell' => "A$branchRow", 'data' => $branch['description']);
		    $mergeCells[] = "A$rowCtr:C$rowCtr";
		    $fillCell[] = "A$rowCtr:D$rowCtr";
		    $rowCtr++;
		    $cellsData[] = array('cell' => "B$rowCtr", 'data' => 'Item');
		    $cellsData[] = array('cell' => "C$rowCtr", 'data' => 'Cost');
		    $cellsData[] = array('cell' => "D$rowCtr", 'data' => 'Total');
		    foreach ($inventories as $inventory) {
			    $rowCtr++;
			    $cellsData[] = array('cell' => "B$rowCtr", 'data' => $inventory['item']);
			    foreach ($inventory['branches'] as $inv_branch) {
				    if($inv_branch['id'] == $branch['id']) {
					    $totalBranchCost+= $inv_branch['total_cost'];
					    $cellsData[] = array('cell' => "C$rowCtr", 'data' => $inv_branch['ave_cost'] ? $inv_branch['ave_cost'] : '');
					    $cellsData[] = array('cell' => "D$rowCtr", 'data' => $inv_branch['total_cost'] > 0 ? $inv_branch['total_cost'] : '');
					    break;
				    }
			    }
		    }
		    $cellsData[] = array('cell' => "D$branchRow", 'data' => $totalBranchCost);

	    }*/


	    $page_title = 'Report : Inventory';
        return $this->export_to_excel($columnRange, $cellsData, $page_title, [], $fillCells, $mergeCells);
    }

    /**
     * @Route(
     *      "/test/export_to_pdf",
     *      name = "test_export_to_excel"
     * )
     */
    public function test_export_to_excelAction(Request $request) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Patient Letter Pdf'))) return $authService->redirectToHome();
        ini_set('memory_limit', '2048M');
        set_time_limit(0);

        $em = $this->getDoctrine()->getManager();
        $records = $em->getRepository('RxConnexionBundle:PatientNoteEntity')->test();

        $columnRange = range('A', 'G');
        $cellsData = array(
            array('cell' => 'A1', 'data' => 'Created At'),
            array('cell' => 'B1', 'data' => 'Created By'),
            array('cell' => 'C1', 'data' => 'Updated By'),
            array('cell' => 'D1', 'data' => 'Updated At'),
            array('cell' => 'E1', 'data' => 'Patient'),
            array('cell' => 'F1', 'data' => 'Type'),
            array('cell' => 'G1', 'data' => 'Note'),
        );
        $rowCtr = 1;
        $totalCount = 0;

        foreach($records as $record) {

            $rowCtr++;
            $totalCount++;

            $cellsData[] = array('cell' => "A$rowCtr", 'data' => $record['created_at']);
            $cellsData[] = array('cell' => "B$rowCtr", 'data' => $record['created_by']);
            $cellsData[] = array('cell' => "C$rowCtr", 'data' => $record['updated_by']);
            $cellsData[] = array('cell' => "D$rowCtr", 'data' => $record['updated_at']);
            $cellsData[] = array('cell' => "E$rowCtr", 'data' => $record['fullName']);
            $cellsData[] = array('cell' => "F$rowCtr", 'data' => $record['type']);
            $cellsData[] = array('cell' => "G$rowCtr", 'data' => $record['note']);
        }

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


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


    }
    //***************************************************************************************************//

    /* ======================================================================================= */
    /* =====================T R A N S F E R   F U N C T I O N S=============================== */
    /* ======================================================================================= */

    /**
     * @Route(
     *      "/transfer",
     *      name = "report_transfer"
     * )
     */
    public function transferAction() {
        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Report Transfer'))) return $authService->redirectToHome();

        $title = 'Transfer';

        $result['html'] =  $this->renderView('@RxConnexion/Report/Patient/transfer_form.html.twig', array(
            'title' => $title,
            'page_title' => $title,
        ));
        $result['success'] = true;
        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/transfer_save_action",
     *      name = "report_transfer_save"
     * )
     */
    public function transfer_saveAction(Request $request) {

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

        $referringProvider_id =  $request->get('referring_provider');
        $params =  $request->get('ids');

        if(!empty($params) || $params != null) {

            $referringProvider = $em->getRepository('RxConnexionBundle:ReferringProviderEntity')->find($referringProvider_id);

            if($referringProvider) {
                foreach ($params as $param) {
                    $patient = $em->getRepository('RxConnexionBundle:PatientEntity')->find($param);

                    //Set End Date Active Referring Provider
                    $oldPatientReferringProvider = $em->getRepository('RxConnexionBundle:PatientReferringProviderEntity')->findOneBy(array(
                        'patient' => $patient,
                        'endDate' => null,
                        'isDeleted' => false,
                    ));
                    $oldPatientReferringProvider->setEndDate(date('Y/m/d'));

                    $oldPatientReferringHealthFacility = $em->getRepository('RxConnexionBundle:PatientReferringHealthFacilityEntity')->findOneBy(array(
                        'patient' => $patient,
                        'endDate' => null,
                        'isDeleted' => false,
                    ));

                    $oldPatientReferringHealthFacility->setEndDate(date('Y/m/d'));

                    $newPatientReferringProvider = new PatientReferringProviderEntity();
                    $newPatientReferringProvider->setPatient($em->getReference('RxConnexionBundle:PatientEntity', $param));
                    $newPatientReferringProvider->setReferringProvider($referringProvider);
                    $newPatientReferringProvider->setStartDate(date('Y/m/d'));
                    $newPatientReferringProvider->setEndDate(null);
                    $em->persist($newPatientReferringProvider);

                    if($referringProvider->getActiveReferringHealthFacilityProvider() != null) {
                        $newPatientReferringHealthFacility = new PatientReferringHealthFacilityEntity();
                        $newPatientReferringHealthFacility->setPatient($em->getReference('RxConnexionBundle:PatientEntity', $param));
                        $newPatientReferringHealthFacility->setReferringHealthFacility($referringProvider->getActiveReferringHealthFacilityProvider()->getReferringHealthFacility());
                        $newPatientReferringHealthFacility->setStartDate(date('Y/m/d'));
                        $newPatientReferringHealthFacility->setEndDate(null);
                        $em->persist($newPatientReferringHealthFacility);
                    }

                    $em->flush();


                }


            }

            $result['success'] = true;
            $result['successMessages'][] = 'Record Successfully Transferred.';

        } else {
            $result['errorMessages'][] = 'Something went wrong. Please try again.';
        }

        return new JsonResponse($result);
    }


    /* ======================================================================================= */
    /* =====================V I E W N O T E   F U N C T I O N S=============================== */
    /* ======================================================================================= */

    /**
     * @Route(
     *      "/view_note",
     *      name = "report_view_note"
     * )
     */
    public function viewNoteAction(Request $request) {

        $em = $this->getDoctrine()->getManager();
        $ticketNote = $em->getRepository('RxConnexionBundle:PatientTicketEntity')->patientTicketNote(base64_decode($request->get('patient_id')));
        $patient = $em->getRepository('RxConnexionBundle:PatientEntity')->find(base64_decode($request->get('patient_id')));

        $title = 'Notes';

        $result['html'] =  $this->renderView('@RxConnexion/Report/PatientCycle/view_note.html.twig', array(
            'patient' => $patient,
            'title' => $title,
            'page_title' => $title,
            'ticketNote' => $ticketNote,
        ));
        $result['success'] = true;
        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/view_patient_note",
     *      name = "report_view_patient_note"
     * )
     */
    public function viewPatientNoteAction(Request $request) {

        $em = $this->getDoctrine()->getManager();
        $patientNote = $em->getRepository('RxConnexionBundle:PatientNoteEntity')->patientNoteForReport(base64_decode($request->get('patient_id')));
        $patient = $em->getRepository('RxConnexionBundle:PatientEntity')->find(base64_decode($request->get('patient_id')));

        $title = 'Notes';

        $result['html'] =  $this->renderView('@RxConnexion/Report/PatientCycle/view_patient_note.html.twig', array(
            'patient' => $patient,
            'title' => $title,
            'page_title' => $title,
            'patientNote' => $patientNote,
        ));
        $result['success'] = true;
        return new JsonResponse($result);
    }

    /* ===================================================================================== */
    /* =====================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(), $fillCells=array(), $mergeCells=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 ($fillCells as $fc) {
			$activeSheet->getStyle($fc)->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']);
        }

		foreach($mergeCells as $mc) {
			$activeSheet->mergeCells($mc);
		}

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