<?php

namespace RxConnexionBundle\Controller;

use RxConnexionBundle\Entity\CompanyEntity;
use RxConnexionBundle\Entity\FaxingOptionConfirmationEntity;
use RxConnexionBundle\Entity\FaxingOptionEntity;
use RxConnexionBundle\Entity\FaxingOptionFileEntity;
use RxConnexionBundle\Entity\FaxingOptionOutboundEntity;
use RxConnexionBundle\Entity\FileTypeEntity;
use RxConnexionBundle\Entity\PatientFileEntity;
use RxConnexionBundle\Form\FaxingOptionForm;
use RxConnexionBundle\Service\SRFaxService;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;


/**
 * @Route("/main/faxing_option")
 */
class FaxingOptionController extends Controller
{

    /**
     * @Route("", name="faxing_option")
     */
    public function indexAction(Request $request) {
        $authService = $this->get('rx_connexion.authService');

        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Faxing Option'))) return $authService->redirectToHome();
        $userData = $this->get('session')->get('userData');

        return $this->render('@RxConnexion/FaxingOption/index.html.twig', array(
            'title' => 'Faxing Option',
            'page_title' => 'Faxing Option',
            'javascripts' => array('rxconnexion/admin/js/faxingOption/faxingOption.js?v=1.0.7'),
        ));
    }

    /**
     * @Route("/ajax_list", name="faxing_option_ajax_list")
     */
    public function ajax_list(Request $request) {

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

        $result = array(
            "draw" => intval($get['draw']),
            "recordsTotal" => 0,
            "recordsFiltered" => 0,
            "data" => array()
        );

        $authService = $this->get('rx_connexion.authService');
        if($authService->isLoggedIn()) {

            $userData = $this->get('session')->get('userData');
            $data = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:FaxingOptionEntity')->ajax_list($get, $userData);
            $action = '';
            foreach($data['results'] as $row) {


                $attachmentWithLink = '';
                $faxingOptionLink = '';
                if(isset($row['attachmentFile'])){
                    $attachmentWithLinks = array();
                    $attachmentDetails = explode(',' , $row['attachmentFile']);
                    foreach ($attachmentDetails as $attachmentDetail){
                        $attachmentDetailForIds = explode('~', $attachmentDetail);
                        $attachmentLink = !empty($attachmentDetailForIds[0]) ? $this->generateUrl('faxing_option_file_download', array(
                            'id' => base64_encode($attachmentDetailForIds[0])
                        )) : 'javascript:void(0)';
                        $attachmentWithLinks[] = isset($attachmentDetailForIds[1]) ? "<a href='$attachmentLink' target='_blank'> $attachmentDetailForIds[1]</a>" : '';
                    }
                    $attachmentWithLink = implode('<br />' ,$attachmentWithLinks);
                }
                $encryptId = base64_encode($row['id']);
                $recipient = $row['faxNo'];
                $action = "<a data-action='u' data-id='$encryptId' class='action-button-style href-faxingOption-form' href='javascript:void(0)'>Update</a>";

                $previewUrl = $this->generateUrl('faxing_option_preview', array(
                    'faxingOption_id' => $encryptId,
                ));

                $faxUrl = $this->generateUrl('faxing_option_send', array(
                    'faxingOption_id' => $encryptId,
                ));

                $action .= "<a class='action-button-style' target='_blank' href='$previewUrl'>Preview</a>";
                $action .= "<a class='action-button-style ask-continue' data-message='Are you sure you want to fax to $recipient?' href='$faxUrl'>Fax ({$row['faxCtr']})</a>";

                if ($row['faxConfirmation'] != null || $row['faxConfirmation'] != '') {
                    $faxingOptionDownloadLink = $this->generateUrl('faxing_option_confirmation_download', array(
                        'id' => base64_encode($row['faxConfirmationId']),
                    ));

                    $faxingOptionLink = "<a href='$faxingOptionDownloadLink'>".$row['faxConfirmation'].' ('.date_format(date_create($row['faxConfirmationSent']),"Y/m/d h:i A").')'."</a>";
                }


                $values = array(
                    $row['createdAt'],
                    $row['faxNo'],
                    $row['faxTo'],
                    $row['patientName'],
                    $attachmentWithLink,
                    $row['status'],
                    $faxingOptionLink,
                    $action
                );

                $result['data'][] = $values;
            }

            $result['recordsTotal'] = $data['total'];
            $result['recordsFiltered'] = $data['total'];
        }

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/form/{action}/{id}",
     *      defaults = {
     *          "action":  "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "faxing_option_form"
     * )
     */
    public function faxingOption_formAction($action, $id) {

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

        $em = $this->getDoctrine()->getManager();
        $faxingOption = $em->getRepository('RxConnexionBundle:FaxingOptionEntity')->find(base64_decode($id));
        if(!$faxingOption) {
            $faxingOption = new FaxingOptionEntity();
        }

        $formOptions = array(
            'action' => $action,
        );
        $form = $this->createForm(FaxingOptionForm::class, $faxingOption, $formOptions);

        $companies = $em->getRepository(CompanyEntity::class)->companiesForFaxingOption($this->get('session')->get('userData'));

        $title = $action === 'n' ? 'New Fax' : 'Update Fax';

        $result['html'] =  $this->renderView('@RxConnexion/FaxingOption/faxing_option_form.html.twig', array(
            'title' => $title,
            'page_title' => $title,
            'form' => $form->createView(),
            'action' => $action,
            'faxingOption' => $faxingOption,
            'companies' => $companies,
            'javascripts' => array('rxconnexion/admin/js/faxingOption/faxOption_form.js?v=1.0.10'),
        ));
        $result['success'] = true;
        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/form/save_action",
     *      name = "faxing_option_form_save"
     * )
     */
    public function faxingOption_formSaveAction(Request $request) {
        $result['success'] = false;
        $result['successMessages'] = array();
        $result['errorMessages'] = array();

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

        $faxingOption_form = $request->get('faxingOptions');
        $em = $this->getDoctrine()->getManager();
        $faxingOption = $em->getRepository('RxConnexionBundle:FaxingOptionEntity')->find($faxingOption_form['id']);
        if(!$faxingOption) {
            $faxingOption = new FaxingOptionEntity();
        }
        $formOptions = array(
            'action' => $faxingOption_form['action'],
        );
        $form = $this->createForm(FaxingOptionForm::class, $faxingOption, $formOptions);
        $errors = $em->getRepository('RxConnexionBundle:FaxingOptionEntity')->validate($faxingOption_form);


        if(!count($errors)) {

            switch($faxingOption_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if($form->isValid()) {

                        $session = $this->get('session')->get('userData');
                        $faxingOption->setName($session['fullName']);
                        $faxingOptionForm = $request->get('faxingOptionForm');

                        $company = $em->getRepository(CompanyEntity::class)->find(base64_decode($faxingOptionForm['template']));

                        if(isset($_FILES['files']['tmp_name'])) {
                            foreach($_FILES['files']['tmp_name'] as $key => $tmpName) {
                                if(!empty($tmpName)) {
                                    $faxingOptionFile = new FaxingOptionFileEntity();
                                    $faxingOptionFile->setFaxingOption($faxingOption);

                                    $baseName = rand(0,999) . '-' . time() . '.' . pathinfo($_FILES['files']['name'][$key], PATHINFO_EXTENSION);
                                    $uploadFile = $faxingOptionFile->getUploadRootDir() . '/' . $baseName;
                                    if(move_uploaded_file($tmpName, $uploadFile)) {
                                        $faxingOptionFile->setFileDesc($_FILES['files']['name'][$key]);
                                        $faxingOptionFile->setParsedFileDesc($baseName);
                                        $em->persist($faxingOptionFile);
                                    }
                                }
                            }
                        }

                        if(isset($faxingOption_form['faxCoverSelection'])) {
                            $faxCoverSelection = implode(',', $faxingOption_form['faxCoverSelection']);
                            $faxingOption->setFaxCoverSelection($faxCoverSelection);
                        }

                        $template = null;
                        if (isset($company)) {
                            if ($company->getDescription() == 'Freedom Respiratory & Sleep Centre') {
                                $template = 'Freedom Respiratory & Sleep Centre';
                            } elseif ($company->getDescription() == 'Perfect Sleep Solutions WC Inc.') {
                                $template = 'Perfect Sleep Solutions WC Inc.';
                            } elseif ($company->getDescription() == 'Dynamic Sleep and Respiratory Care') {
                                $template = 'Dynamic Sleep and Respiratory Care';
                            } else {
                                $template = null;
                            }
                        }

                        $fileType = $em->getRepository('RxConnexionBundle:FileTypeEntity')->findOneBy(array(
                            'description' => 'Faxing Option'
                        ));

                        $faxingOption->setTemplate($template);
                        $faxingOption->setCompany($company);
                        $em->persist($faxingOption);
                        $em->flush();

                        if ($faxingOption->getPatient()) {
                            $patientFile = new PatientFileEntity();
                            $patientFile->setPatient($faxingOption->getPatient());
                            $patientFile->setFaxingOption($faxingOption);
                            $patientFile->setFileType($fileType);
                            $patientFile->setParsedDescription($faxingOption->getIdEncoded().' - PDF File');
                            $patientFile->setDescription($faxingOption->getIdEncoded().' - PDF File');
                            $patientFile->setNote('Faxing Option Fax');
                            $em->persist($patientFile);
                            $em->flush();
                        }


                        /*$newAT = new AuditTrailEntity();
                        $newAT->setUser($em->getReference('RxConnexionBundle:UserEntity', base64_decode($_COOKIE['userId'])));
                        $newAT->entity = $patientNote;
                        $newAT->setRefTable('provider');
                        $newAT->parseInformation('New');
                        $em->persist($newAT);
                        $em->flush();*/

                        $this->get('session')->getFlashBag()->set('success_messages', 'Record Successfully Saved.');
                        $result['success'] = true;
                        $result['successMessages'][] = 'Record Successfully Saved.';

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

                    break;

                // TODO: FIX WHEN UPDATING FAX OPTION RECORD, CREATED_AT CHANGES
                case 'u': // update
                    /*$newAT = new AuditTrailEntity();
                    $newAT->setUser($em->getReference('RxConnexionBundle:UserEntity', base64_decode($_COOKIE['userId'])));
                    $newAT->entity = $patientNote;
                    $newAT->setRefTable('provider');
                    $newAT->parseOriginalDetails();*/
                    $form->handleRequest($request);
                    if ($form->isValid()) {

                        $formFaxingOptionFile = $request->get('otherForm');
                        $faxingOptionFile = $em->getRepository('RxConnexionBundle:FaxingOptionFileEntity')->findBy(array(
                            'faxingOption' => $faxingOption->getId(),
                            'isDeleted' => false
                        ));

                        $faxingOptionForm = $request->get('faxingOptionForm');
                        $company = $em->getRepository(CompanyEntity::class)->find(base64_decode($faxingOptionForm['template']));

                        if(isset($_FILES['files']['tmp_name'])) {
                            foreach($_FILES['files']['tmp_name'] as $key => $tmpName) {
                                if(!empty($tmpName)) {

                                    $newFaxingOptionFile = new FaxingOptionFileEntity();
                                    $newFaxingOptionFile->setFaxingOption($faxingOption);

                                    $baseName = rand(0,999) . '-' . time() . '.' . pathinfo($_FILES['files']['name'][$key], PATHINFO_EXTENSION);
                                    $uploadFile = $newFaxingOptionFile->getUploadRootDir() . '/' . $baseName;

                                    if(move_uploaded_file($tmpName, $uploadFile)) {
                                        $newFaxingOptionFile->setFileDesc($_FILES['files']['name'][$key]);
                                        $newFaxingOptionFile->setParsedFileDesc($baseName);
                                        $em->persist($newFaxingOptionFile);
                                        $em->flush();
                                    }
                                }
                            }
                        }

                        if(isset($formFaxingOptionFile)) {
                            foreach($faxingOptionFile as $fof) {
                                if(!in_array($fof->getIdEncoded(), $formFaxingOptionFile['files'])) {
                                    $faxingOptionFile2 = $em->getRepository('RxConnexionBundle:FaxingOptionFileEntity')->find($fof->getId());
                                    $faxingOptionFile2->removeFile();
                                    $faxingOptionFile2->setIsDeleted(true);
                                    $em->flush();
                                }
                            }
                        } else {
                            foreach ($faxingOptionFile as $fof2) {
                                $fof2->removeFile();
                                $fof2->setIsDeleted(true);
                                $em->flush();
                            }
                        }

                        if(isset($faxingOption_form['faxCoverSelection'])) {
                            $faxCoverSelection = implode(',', $faxingOption_form['faxCoverSelection']);
                            $faxingOption->setFaxCoverSelection($faxCoverSelection);
                        }

                        $template = null;
                        if (isset($company)) {
                            if ($company->getDescription() == 'Freedom Respiratory & Sleep Centre') {
                                $template = 'Freedom Respiratory & Sleep Centre';
                            } elseif ($company->getDescription() == 'Perfect Sleep Solutions WC Inc.') {
                                $template = 'Perfect Sleep Solutions WC Inc.';
                            } elseif ($company->getDescription() == 'Dynamic Sleep and Respiratory Care') {
                                $template = 'Dynamic Sleep and Respiratory Care';
                            } else {
                                $template = null;
                            }
                        }

                        $faxingOption->setTemplate($template);
                        $faxingOption->setCompany($company);
                        $em->flush();

                        $this->get('session')->getFlashBag()->set('success_messages', 'Record Successfully Updated.');
                        $result['success'] = true;
                        $result['successMessages'][] = 'Record Successfully Updated.';
                    }else{
                        $result['errorMessages'][] = 'Something went wrong. Please try again.';
                    }

                    break;

                case 'd': // delete
                    /*$newAT = new AuditTrailEntity();
                    $newAT->setUser($em->getReference('RxConnexionBundle:UserEntity', base64_decode($_COOKIE['userId'])));
                    $newAT->entity = $patientNote;
                    $newAT->setRefTable('provider');
                    $newAT->parseInformation('Delete');
                    $em->persist($newAT);*/

                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        //$em->remove($faxTran);
                        $faxingOption->setIsDeleted(true);

                        $em->flush();

                        $this->get('session')->getFlashBag()->set('success_messages', 'Record Successfully Deleted.');

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

                    } else {

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

                    break;
            }
        } else {

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


    /**
     * @Route(
     *      "/send/{faxingOption_id}",
     *      name = "faxing_option_send"
     * )
     */
    public function fax_option_send_faxAction(Request $request, $faxingOption_id) {

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

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

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

        $em = $this->getDoctrine()->getManager();
        $faxingOption = $em->getRepository('RxConnexionBundle:FaxingOptionEntity')->find(base64_decode($faxingOption_id));
        $generatedLetter = $this->faxing_option_generate($faxingOption);
        $generatedLetter_fileName = $faxingOption->getFaxNo() . '-' . uniqid() . '.pdf';

        $receiver = preg_replace("/[^0-9]/", "", $faxingOption->getFaxNo());

        if($receiver != null && $receiver != ''){

            /**@var SRFaxService $srFax*/
            $srFax = $this->get('rx_connexion.srFaxService');
            $faxType = $srFax::FAX_TYPE_SINGLE;
            if(!empty($cc) && !is_null($cc)){
                $receiver = implode('|', array($receiver,$cc));
                $faxType = $srFax::FAX_TYPE_BROADCAST;
            }
            $newFaxTranOut = new FaxingOptionOutboundEntity();
            $newFaxTranOut->setSource(FaxingOptionOutboundEntity::FAXING_OPTION);
            $newFaxTranOut->setFaxingOption($faxingOption);
            $newFaxTranOut->setFaxType($faxType);
            $newFaxTranOut->setFaxNo($receiver);
            $newFaxTranOut->setFileName($generatedLetter_fileName);

            $queueOptions = array();
            $queueOptions['sFaxType'] = $faxType;
            $queueOptions['sToFaxNumber'] = $receiver;
            $queueOptions['sFileName_1'] = $generatedLetter_fileName;
            $queueOptions['sFileContent_1'] = base64_encode($generatedLetter->getContent());
            $queueOptions['sNotifyURL'] = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] ? 'https' : 'http') . '://' . $_SERVER['SERVER_NAME'] . $this->generateUrl('faxing_option_status_receipt');
            $status = $srFax->Queue_Fax($queueOptions);

            $newFaxTranOut->setStatus($status);

            if($status){
                $newFaxTranOut->setFaxId($srFax->getRequestResponse());
                $faxingOption->setStatus(FaxingOptionEntity::FAXING_OPTION_STATUS_SENT);

                $newFaxTranOut->setMsg('Fax successfully queued.');

                $this->get('session')->getFlashBag()->set('success_messages', 'Fax successfully queued.');
            } else {
                $newFaxTranOut->setMsg($srFax->getRequestResponse());
                $this->get('session')->getFlashBag()->set('error_messages', $srFax->getRequestResponse());
            }

            $em->persist($newFaxTranOut);
            $em->flush();

        } else {
            $this->get('session')->getFlashBag()->set('error_messages', 'Fax Option Doesn\'t have fax number.');
        }

        return $this->redirect($this->generateUrl('faxing_option'), 302);

    }

    /**
     * @Route(
     *      "/preview/{faxingOption_id}",
     *      name = "faxing_option_preview"
     * )
     */
    public function faxing_option_previewAction(Request $request, $faxingOption_id) {

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

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

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

        $em = $this->getDoctrine()->getManager();
        $faxingOption = $em->getRepository('RxConnexionBundle:FaxingOptionEntity')->find(base64_decode($faxingOption_id));

        $generatedLetter = $this->faxing_option_generate($faxingOption);
        return $generatedLetter;
    }

    /**
     * @Route(
     *      "/faxing_option_patient_file_download/{faxingOption_id}",
     *      name = "faxing_option_patient_file_download"
     * )
     */
    public function faxing_option_patient_file_downloadAction(Request $request, $faxingOption_id) {

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

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

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

        $em = $this->getDoctrine()->getManager();
        $faxingOption = $em->getRepository('RxConnexionBundle:FaxingOptionEntity')->find(base64_decode($faxingOption_id));

        $generatedLetter = $this->faxing_option_download($faxingOption);
        return $generatedLetter;
    }

    /**
     * @Route(
     *      "/faxing_option_status_receipt",
     *      name = "faxing_option_status_receipt"
     * )
     */
    public function faxing_option_status_receiptAction(Request $request) {
        $result['success'] = false;
        $result['msg'] = 'No matching remote id.';
        $filName = $request->get('FileName');
        $sentStatus = $request->get('SentStatus');
        $dateQueued = $request->get('DateQueued');
        $dateSent = $request->get('DateSent');
        $toFaxNumber = $request->get('ToFaxNumber');
        $noPage = $request->get('Pages');
        //$duration = $request->get('Duration');
        $fileNameDetails = explode('|', $filName);
        $remoteId = $fileNameDetails[1];
        $faxDetails = array(
            'fileName' => $filName,
            'sentStatus' => $sentStatus,
            'dateQueued' => $dateQueued,
            'dateSent' => $dateSent,
            'toFaxNumber' => $toFaxNumber,
            'pages' => $noPage
        );

        $em = $this->getDoctrine()->getManager();
        $faxOptionOutBound = $em->getRepository('RxConnexionBundle:FaxingOptionOutboundEntity')->findOneBy(array(
            'faxId' => $remoteId
        ));

        $fileType = $em->getRepository('RxConnexionBundle:FileTypeEntity')->findOneBy(array(
            'description' => 'Fax Confirmation'
        ));

        if($faxOptionOutBound){
            if($faxOptionOutBound->getFaxingOption()){
                $faxingOption = $faxOptionOutBound->getFaxingOption();
                $content = $this->renderView('@RxConnexion/Referral/FaxTemplate/FaxReceipt.wkpdf.twig', array(
                    'response' => $faxDetails
                ));
                $fileName = $remoteId . ' - Fax Confirmation';
                $patientFile = new FaxingOptionConfirmationEntity();
                $patientFile->setFileType($fileType);
                $patientFile->setFaxingOption($faxingOption);
                $em->persist($patientFile);
                $em->flush();
                $baseName = $patientFile->getId() . '-' . time() . '.pdf';
                $uploadFile = $patientFile->getUploadRootDir() . '/' . $baseName;
                $this->get('knp_snappy.pdf')->generateFromHtml($content, $uploadFile);
                $patientFile->removeFile();
                $patientFile->setDescription($fileName.'.pdf');
                $patientFile->setParsedDescription($baseName);
                $em->flush();
                $result['success'] = true;
                $result['msg'] = 'Confirmation received.';
            }
        }

        $logData = '[' . date('Y-m-d H:i:s') . ']';
        $logData .= ' Post Data: ' . json_encode($faxDetails);
        $logData .= '[' . date('Y-m-d H:i:s') . ']';

        $logFileName = $this->getParameter('fax_api_log_dir') . '/notify/fax_notify.log';
        if(file_exists($logFileName)){
            $logFile = fopen($logFileName, "a+");
            fwrite($logFile, PHP_EOL . $logData);
        }else{
            $logFile = fopen($logFileName, "w");
            fwrite($logFile, $logData);
        }
        fclose($logFile);
        $logSize = $this->getParameter('api_log_max_size');
        if($logSize >= $this->getParameter('api_log_max_size')) {
            rename($logFileName, $this->getParameter('fax_api_log_dir') . '/notify/fax_notify' . '-' . date('Y-m-d-H-i-s') . '.log');
        }

        return new JsonResponse($result);

    }

    /**
     * @Route(
     *      "/faxing_option_outbound",
     *      name = "faxing_option_outbound"
     * )
     */
    public function faxOutboundAction(Request $request) {
        $authService = $this->get('rx_connexion.authService');

        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Fax Outbound'))) return $authService->redirectToHome();

        return $this->render('@RxConnexion/FaxingOption/faxing_option_outbound.html.twig', array(
            'title' => 'Faxing Option Outbound',
            'page_title' => 'Faxing Option Outbound',
            'javascripts' => array('rxconnexion/admin/js/faxingOption/faxingOptionOutbound.js?v=1.0.7'),
        ));
    }

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

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

        $result = array(
            "draw" => intval($get['draw']),
            "recordsTotal" => 0,
            "recordsFiltered" => 0,
            "data" => array()
        );

        $authService = $this->get('rx_connexion.authService');
        if($authService->isLoggedIn()) {

            $data = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:FaxingOptionEntity')->faxing_option_outbound_ajax_list($get);

            $action = "";
            foreach($data['results'] as $row) {

                $fileUrl = $this->generateUrl('faxing_option_preview', array(
                    'faxingOption_id' => base64_encode($row['faxing_option_id']),

                ));
                $action = "<a class='action-button-style' href='$fileUrl' target='_blank'>Preview</a>";


                $values = array(
                    $row['createdAt'],
                    $row['faxNo'],
                    $row['faxType'],
                    $row['file_name'],
                    $action
                );

                $result['data'][] = $values;
            }

            $result['recordsTotal'] = $data['total'];
            $result['recordsFiltered'] = $data['total'];
            $result['sql'] = $data['$sql'];
        }

        return new JsonResponse($result);
    }

    /**
     * @Route("/location/autocomplete", name="fax_location_autocomplete")
     */
    public function locationAutocompleteAction(Request $request) {

        $q = $request->get('query');

        $result = array(
            'query' => 'patients',
            'suggestions' => $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:PatientEntity')->autocomplete_suggestions($q)
        );

        return new JsonResponse($result);
    }

    /**
     * @Route("/download/{id}", name="faxing_option_file_download")
     */
    public function faxing_option_file_downloadAction($id) {

        if($this->get('rx_connexion.authService')->isLoggedIn()) {

            $faxingOptionFile = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:FaxingOptionFileEntity')->find(base64_decode($id));

            header('Content-Disposition: attachment; filename="' . $faxingOptionFile->getFileDesc() . '"');

            $handle = fopen(realpath($faxingOptionFile->getUploadRootDir()) . '/' . $faxingOptionFile->getParsedFileDesc(), 'rb');
            $chunkSize = 1024*1024;

            if($handle !== false) {

                while (!feof($handle)) {
                    $buffer = fread($handle, $chunkSize);
                    echo $buffer;
                    ob_flush();
                    flush();
                }

                fclose($handle);
            }
        }

        exit();
    }

    /**
     * @Route("/fax_confirmation_download/{id}", name="faxing_option_confirmation_download")
     */
    public function faxing_option_confirmation_downloadAction($id) {

        if($this->get('rx_connexion.authService')->isLoggedIn()) {

            $faxingConfirmationFile = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:FaxingOptionConfirmationEntity')->find(base64_decode($id));

            header('Content-Disposition: attachment; filename="' . $faxingConfirmationFile->getDescription() . '"');

            $handle = fopen(realpath($faxingConfirmationFile->getUploadRootDir()) . '/' . $faxingConfirmationFile->getParsedDescription(), 'rb');
            $chunkSize = 1024*1024;

            if($handle !== false) {

                while (!feof($handle)) {
                    $buffer = fread($handle, $chunkSize);
                    echo $buffer;
                    ob_flush();
                    flush();
                }

                fclose($handle);
            }
        }

        exit();
    }


    /************** Private Functions ******************/

    private function getFaxInbox(){
        $srFax = $this->get('rx_connexion.SRFaxService');

        $date3DaysAgo = date('Ymd', strtotime('-3 days', strtotime(date('Y-m-d'))));
        $dateToday = date('Ymd');
        $faxQuery = $srFax->Get_Fax_Inbox(array(
            'sResponseFormat'   =>  '', //OPTIONAL - XML or JSON(default)
            'sPeriod'           =>  'RANGE', //OPTIONAL - RANGE or ALL (default)
            'sStartDate'        =>  $date3DaysAgo, //OPTIONAL - Only required when using RANGE - must be YYYYMMDD
            'sEndDate'          =>  $dateToday, //OPTIONAL - Only required when usiing RANGE - must be YYYYMMDD
            'sViewedStatus'     =>  '', //OPTIONAL - UNREAD, READ, or ALL (default)
            'sIncludeSubUsers'  =>  '', //OPTIONAL - Set to Y to include all faxes received by sub users of the account
        ));
        return $faxQuery;
    }

    private function faxing_option_generate($faxingOption){
        $faxingOption_id = $faxingOption->getIdEncoded();
        $em = $this->getDoctrine()->getManager();

        $view = null;
        $template_header = null;
        $template_footer = null;

        switch ($faxingOption->getTemplate()) {
            case FaxingOptionEntity::FAXING_OPTION_TEMPLATE_DSRC :
                $template_header = '@RxConnexion/FaxingOption/faxing_option_header.wkpdf.twig';
                $template_footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/FaxingOption/faxing_option_template.html.twig';
                break;
            case FaxingOptionEntity::FAXING_OPTION_TEMPLATE_FRSC :
                $template_header = '@RxConnexion/FaxingOption/frsi_header.wkpdf.twig';
                $template_footer = '@RxConnexion/FaxingOption/frsi_footer.wkpdf.twig';
                $view = '@RxConnexion/FaxingOption/frsi_fax_cover.wkpdf.twig';
                break;
            case FaxingOptionEntity::FAXING_OPTION_TEMPLATE_PSS :
                $template_header = '@RxConnexion/FaxingOption/pss_header.wkpdf.twig';
                $template_footer = '@RxConnexion/FaxingOption/pss_footer.wkpdf.twig';
                $view = '@RxConnexion/FaxingOption/pss_fax_cover.wkpdf.twig';
                break;
        }

        if($view != ''){
            $userData = $this->get('session')->get('userData');
            $content = $this->renderView($view, array(
                'faxingOption' => $faxingOption,
                'dateToday' => date('F j, Y'),
                'userData'  => $userData,
                'cover'     =>  'pr' // u-urgent/fr-for review/pc-please comment/pr-please reply
            ));


            $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content, array(
                'page-size' => 'Letter',
                'margin-top' => '40mm',
                'margin-right' => '15mm',
                'margin-left' => '15mm',
                'margin-bottom' => '40mm',
                'header-html' => $this->renderView($template_header),
                'footer-html' => $this->renderView($template_footer),
                'header-spacing' => 37,
                'footer-spacing' => 10,
                'dpi' => 72,
                // 'disable-smart-shrinking',
                'zoom' => 'LINUX' == strtoupper(PHP_OS) ? 0.78 : 1
            ));

            $tmpLetterForPatientFile = $faxingOption->getTmpRootDir() . '/' . $faxingOption->getId() . '-' . uniqid() . '.pdf';
            file_put_contents($tmpLetterForPatientFile, $xml);

            try {

                $gs = $this->getParameter('ghostscript');

                $pdf = new \PDFMerger();

                // save the LETTER temporarily
                $tmpLetter = $faxingOption->getTmpRootDir() . '/' . $faxingOption->getId() . '-' . uniqid() . '.pdf';
                file_put_contents($tmpLetter, $xml);

                $pdf->addPDF($tmpLetter, 'all');

                $faxAttachment = $em->getRepository('RxConnexionBundle:FaxingOptionFileEntity')->findBy(array(
                    'faxingOption' => base64_decode($faxingOption_id),
                    'isDeleted' => false,
                ));

                //The PDF version that you want to convert
                //the file into.
                $pdfVersion = "1.4";
                $newFiles = array();
                if ($faxAttachment) {
                    foreach($faxAttachment as $faxAttachments) {
                        //The path that you want to save the new file to
                        $newFile = $faxAttachments->getUploadRootDir2().'/'.$faxAttachments->getParsedFileDesc();

                        //The path of the file that you want to convert
                        $currentFile = $faxAttachments->getUploadRootDir().'/'.$faxAttachments->getParsedFileDesc();

                        //Execute command of Ghostscript
                        shell_exec($gs.' -sDEVICE=pdfwrite -dCompatibilityLevel='.$pdfVersion.' -dPDFSETTINGS=/printer -dNOPAUSE -dBATCH -sOutputFile='.$newFile.' '.$currentFile.'');

                        $pdf->addPDF($newFile, 'all');
                        $newFiles[] = $newFile;
                    }
                }


                $binaryContent = $pdf->merge('string', "mergedpdf.pdf");
                $response = new Response($binaryContent);
                $response->headers->set('Content-type' , 'application/pdf');

                //DELETE TEMP LETTER PDF FILE
                unlink($tmpLetter);
                foreach($newFiles as $newFile){
                    unlink($newFile);
                }

                return $response;

            } catch(\Exception $e){
                $this->get('session')->getFlashBag()->set('error_messages', $e->getMessage());
                return $this->redirect($this->generateUrl('faxing_option', 302));
            }
        } else {
            $this->get('session')->getFlashBag()->set('error_messages', 'No template available.');
            return $this->redirect($this->generateUrl('faxing_option'), 302);
        }

    }

    private function faxing_option_download($faxingOption){
        $faxingOption_id = $faxingOption->getIdEncoded();
        $em = $this->getDoctrine()->getManager();

        $view = null;
        $template_header = null;
        $template_footer = null;

        switch ($faxingOption->getTemplate()) {
            case FaxingOptionEntity::FAXING_OPTION_TEMPLATE_DSRC :
                $template_header = '@RxConnexion/FaxingOption/faxing_option_header.wkpdf.twig';
                $template_footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/FaxingOption/faxing_option_template.html.twig';
                break;
            case FaxingOptionEntity::FAXING_OPTION_TEMPLATE_FRSC :
                $template_header = '@RxConnexion/FaxingOption/frsi_header.wkpdf.twig';
                $template_footer = '@RxConnexion/FaxingOption/frsi_footer.wkpdf.twig';
                $view = '@RxConnexion/FaxingOption/frsi_fax_cover.wkpdf.twig';
                break;
            case FaxingOptionEntity::FAXING_OPTION_TEMPLATE_PSS :
                $template_header = '@RxConnexion/FaxingOption/pss_header.wkpdf.twig';
                $template_footer = '@RxConnexion/FaxingOption/pss_footer.wkpdf.twig';
                $view = '@RxConnexion/FaxingOption/pss_fax_cover.wkpdf.twig';
                break;
        }

        if($view != ''){
            $userData = $this->get('session')->get('userData');
            $content = $this->renderView($view, array(
                'faxingOption' => $faxingOption,
                'dateToday' => date('F j, Y'),
                'userData'  => $userData,
                'cover'     =>  'pr' // u-urgent/fr-for review/pc-please comment/pr-please reply
            ));

            $patientFile = $em->getRepository('RxConnexionBundle:PatientFileEntity')->findOneBy(array(
                'patient' => $faxingOption->getPatient()
            ));


            $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content, array(
                'page-size' => 'Letter',
                'margin-top' => '40mm',
                'margin-right' => '15mm',
                'margin-left' => '15mm',
                'margin-bottom' => '40mm',
                'header-html' => $this->renderView($template_header),
                'footer-html' => $this->renderView($template_footer),
                'header-spacing' => 37,
                'footer-spacing' => 10,
                '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="Faxing Option -'. $patientFile->getIdEncoded() .' ' . date('m/d/Y') . '.pdf"'
                ));
            } else {
                $this->get('session')->getFlashBag()->set('error_messages', $pdfResponse['msg']);
                return $this->redirect($this->generateUrl('report_referral', 302));
            }

        } else {
            $this->get('session')->getFlashBag()->set('error_messages', 'No template available.');
            return $this->redirect($this->generateUrl('faxing_option'), 302);
        }

    }


}