<?php

namespace RxConnexionBundle\Controller;

use RxConnexionBundle\Entity\AccountingBillingEntity;
use RxConnexionBundle\Entity\AccountingEncodeEntity;
use RxConnexionBundle\Entity\AccountingFileEntity;
use RxConnexionBundle\Form\AccountingBillingForm;
use RxConnexionBundle\Form\AccountingEncodeForm;
use RxConnexionBundle\Form\AccountingFileForm;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;

use RxConnexionBundle\Entity\AuditTrailEntity;
use RxConnexionBundle\Entity\DeviceEntity;

use RxConnexionBundle\Form\DeviceForm;

/**
 * @Route("/main/accounting")
 */
class AccountingController extends Controller
{
    /**
     * @Route("/dashboard", name="accounting_dashboard")
     */
    public function dashboardAction() {

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

        return $this->render('@RxConnexion/Accounting/dashboard.html.twig', array(
            'title' => 'Dashboard',
            'page_title' => 'Dashboard',
            'javascripts' => array('rxconnexion/admin/js/accounting/dashboard.js?v=1.0.1'),
            'stylesheets' => array('rxconnexion/admin/css/admin/index.css?v=1.0.5'),
        ));
    }

    /**
     * @Route("/file", name="accounting_file")
     */
    public function accountingFileAction() {

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

        return $this->render('@RxConnexion/Accounting/accounting_file.html.twig', array(
            'title' => 'Manage Accounting - File',
            'page_title' => 'Manage Accounting - File',
            'javascripts' => array('rxconnexion/admin/js/accounting/accounting_file/accounting_file.js?v=1.0.0')
        ));
    }

    /**
     * @Route("/accounting_file_ajax_list", name="accounting_file_ajax_list")
     */
    public function accountingFile_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()) {

            $hasUpdate = $authService->isUserHasAccesses(array('Admin Accounting File Update'), false);

            $data = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:AccountingFileEntity')->ajax_list($get, $this->get('session')->get('userData'));

            foreach($data['results'] as $row) {

                $id = base64_encode($row['id']);
                $action = '';

                if($hasUpdate) {
                    $url = $this->generateUrl('accounting_file_form', array(
                        'action' => 'u',
                        'id' => $id
                    ));
                    $action = "<a class='action-button-style' href='$url'>Update</a>";
                }

                $attachmentWithLink = '';
                if(isset($row['attachmentFile'])){
                    $attachmentWithLinks = array();
                    $attachmentDetails = explode(',' , $row['attachmentFile']);
                    foreach ($attachmentDetails as $attachmentDetail){
                        $attachmentDetailForIds = explode('~', $attachmentDetail);
                        $attachmentLink = !empty($attachmentDetailForIds[0]) ? $this->generateUrl('accounting_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);
                }

                $values = array(
                    $row['fileTypeDesc'],
                    $attachmentWithLink,
                    $row['note'],
                    $action
                );

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/file/form/{action}/{id}",
     *      defaults = {
     *          "action":  "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "accounting_file_form"
     * )
     */
    public function accountingFileFormAction($action, $id, Request $request) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Accounting File New', 'Admin Accounting File Update'))) return $authService->redirectToHome();

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

        $accounting_file = $em->getRepository('RxConnexionBundle:AccountingFileEntity')->find(base64_decode($id));
        if(!$accounting_file) {
            $accounting_file = new AccountingFileEntity();
        }

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

        if($request->getMethod() === 'POST') {

            $accounting_file_form = $request->get($form->getName());
            $result = $this->accountingFileProcessForm($accounting_file_form, $accounting_file, $form, $request);

            if($result['success']) {
                if($result['redirect'] === 'index') {
                    return $this->redirect($this->generateUrl('accounting_file'), 302);
                } else if($result['redirect'] === 'form') {
                    return $this->redirect($this->generateUrl('accounting_file_form', array(
                        'action' => 'u',
                        'id' => base64_encode($result['id'])
                    )), 302);
                } else if($result['redirect'] === 'form with error') {
                    return $this->redirect($this->generateUrl('accounting_file_form'), 302);
                }
            } else {
                $form->submit($accounting_file_form, false);
            }
        }

        $title = ($action === 'n' ? 'New' : 'Update') . ' Accounting - File';

        return $this->render('@RxConnexion/Accounting/accounting_file_form.html.twig', array(
            'title' => $title,
            'page_title' => $title,
            'stylesheets' => array('rxconnexion/dropzone/min/dropzone.min.css'),
            'javascripts' => array('rxconnexion/admin/js/accounting/accounting_file/accounting_file_form.js?v=1.0.0', 'rxconnexion/dropzone/min/dropzone.min.js'),
            'form' => $form->createView(),
            'action' => $action,
            'id' => $id
        ));
    }

    private function accountingFileProcessForm($accounting_file_form, $accounting_file, $form, Request $request) {

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

        $errors = $em->getRepository('RxConnexionBundle:AccountingFileEntity')->validate($accounting_file_form);

        if(!count($errors)) {

            switch($accounting_file_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if ($form->isValid()) {

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

                        $this->processTmpFiles($accounting_file, $accounting_file_form);

                        $newAT = new AuditTrailEntity(
                            'Accounting - File',
                            $em->getClassMetadata(AccountingFileEntity::class)->getTableName(),
                            AuditTrailEntity::AXN_NEW
                        );
                        $newAT->entity = $accounting_file;
                        $newAT->parseDetails();
                        $em->persist($newAT);
                        $em->flush();

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

                        $result['redirect'] = 'index';

                    } else {

                        $this->get('session')->getFlashBag()->set('error_messages', 'Something went wrong. Please try again.');
                        $result['redirect'] = 'form with error';
                    }

                    break;

                case 'u': // update
                    $newAT = new AuditTrailEntity(
                        'Accounting - File',
                        $em->getClassMetadata(AccountingFileEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $accounting_file;
                    $newAT->parseOriginalDetails();

                    $form->handleRequest($request);

                    if ($form->isValid()) {
                        $accounting_file_obj = $em->getRepository('RxConnexionBundle:AccountingFileEntity')->find($accounting_file_form['id']);
                        $this->processTmpFiles($accounting_file_obj, $accounting_file_form);

                        $newAT->parseDetails();
                        $em->persist($newAT);

                        $em->flush();

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

                        $result['redirect'] = 'index';

                    } else {

                        $this->get('session')->getFlashBag()->set('error_messages', 'Something went wrong. Please try again.');
                        $result['redirect'] = 'form with error';
                    }

                    break;

                case 'd': // delete

                    $newAT = new AuditTrailEntity(
                        'Accounting - File',
                        $em->getClassMetadata(AccountingFileEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_DELETE
                    );
                    $newAT->entity = $accounting_file;
                    $newAT->parseDetails();
                    $em->persist($newAT);

                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        //$em->remove($device);
                        $accounting_file->setIsDeleted(true);

                        $em->flush();

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

                        $result['redirect'] = 'index';

                    } else {

                        $this->get('session')->getFlashBag()->set('error_messages', 'Something went wrong. Please try again.');
                        $result['redirect'] = 'form with error';
                    }

                    break;
            }

            $result['success'] = true;

        } else {

            foreach($errors as $error) {
                $this->get('session')->getFlashBag()->add('error_messages', $error);
            }

            $result['success'] = false;
        }

        return $result;
    }


    /**
     * @Route("/accounting_encoding", name="accounting_encoding")
     */
    public function accountingEncodingAction() {

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

        return $this->render('@RxConnexion/Accounting/accounting_encode.html.twig', array(
            'title' => 'Manage Accounting - Encoding',
            'page_title' => 'Manage Accounting - Encoding',
            'javascripts' => array('rxconnexion/admin/js/accounting/accounting_encode/accounting_encode.js?v=1.0.0')
        ));
    }

    /**
     * @Route("/accounting_encode_ajax_list", name="accounting_encode_ajax_list")
     */
    public function accounting_encode_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()) {

            $hasUpdate = $authService->isUserHasAccesses(array('Admin Accounting Encoding Update'), false);

            $data = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:AccountingEncodeEntity')->ajax_list($get, $this->get('session')->get('userData'));

            foreach($data['results'] as $row) {

                $id = base64_encode($row['id']);
                $action = '';

                if($hasUpdate) {
                    $url = $this->generateUrl('accounting_encoding_form', array(
                        'action' => 'u',
                        'id' => $id
                    ));
                    $action = "<a class='action-button-style' href='$url'>Update</a>";
                }

                $values = array(
                    $row['accounting_file_id'],
                    $row['fileDesc'],
                    $row['encodeDate'],
                    $row['checkDate'],
                    $action
                );

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/encoding/form/{action}/{id}",
     *      defaults = {
     *          "action":  "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "accounting_encoding_form"
     * )
     */
    public function accountingEncodingFormAction($action, $id, Request $request) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Accounting Encoding New', 'Admin Accounting Encoding Update'))) return $authService->redirectToHome();

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

        $accounting_encoding = $em->getRepository('RxConnexionBundle:AccountingEncodeEntity')->find(base64_decode($id));
        if(!$accounting_encoding) {
            $accounting_encoding = new AccountingEncodeEntity();
        }

        $formOptions = array(
            'action' => $action,
//            'accounting_file' => $accounting_encoding->getAccountingFile()->getId()
        );
        $form = $this->createForm(AccountingEncodeForm::class, $accounting_encoding, $formOptions);

        if($request->getMethod() === 'POST') {

            $accounting_encoding_form = $request->get($form->getName());
            $result = $this->accountingEncodingProcessForm($accounting_encoding_form, $accounting_encoding, $form, $request);

            if($result['success']) {
                if($result['redirect'] === 'index') {
                    return $this->redirect($this->generateUrl('accounting_encoding'), 302);
                } else if($result['redirect'] === 'form') {
                    return $this->redirect($this->generateUrl('accounting_encoding_form', array(
                        'action' => 'u',
                        'id' => base64_encode($result['id'])
                    )), 302);
                } else if($result['redirect'] === 'form with error') {
                    return $this->redirect($this->generateUrl('accounting_encoding_form'), 302);
                }
            } else {
                $form->submit($accounting_encoding_form, false);
            }
        }

        $title = ($action === 'n' ? 'New' : 'Update') . ' Accounting - Encode';

        return $this->render('@RxConnexion/Accounting/accounting_encode_form.html.twig', array(
            'title' => $title,
            'page_title' => $title,
            'javascripts' => array('rxconnexion/admin/js/accounting/accounting_encode/accounting_encoding_form.js?v=1.0.0'),
            'form' => $form->createView(),
            'action' => $action,
            'id' => $id,
            'accounting_encoding' => $accounting_encoding
        ));
    }

    private function accountingEncodingProcessForm($accounting_encoding_form, $accounting_encoding, $form, Request $request) {

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

        $errors = $em->getRepository('RxConnexionBundle:AccountingEncodeEntity')->validate($accounting_encoding_form);

        if(!count($errors)) {

            switch($accounting_encoding_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if ($form->isValid()) {

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

                        $newAT = new AuditTrailEntity(
                            'Accounting - Encoding',
                            $em->getClassMetadata(AccountingEncodeEntity::class)->getTableName(),
                            AuditTrailEntity::AXN_NEW
                        );
                        $newAT->entity = $accounting_encoding;
                        $newAT->parseDetails();
                        $em->persist($newAT);
                        $em->flush();

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

                        $result['redirect'] = 'index';

                    } else {

                        $this->get('session')->getFlashBag()->set('error_messages', 'Something went wrong. Please try again.');
                        $result['redirect'] = 'form with error';
                    }

                    break;

                case 'u': // update

                    $newAT = new AuditTrailEntity(
                        'Accounting - Encoding',
                        $em->getClassMetadata(AccountingEncodeEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $accounting_encoding;
                    $newAT->parseOriginalDetails();

                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        $newAT->parseDetails();
                        $em->persist($newAT);

                        $em->flush();

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

                        $result['redirect'] = 'index';

                    } else {

                        $this->get('session')->getFlashBag()->set('error_messages', 'Something went wrong. Please try again.');
                        $result['redirect'] = 'form with error';
                    }

                    break;

                case 'd': // delete

                    $newAT = new AuditTrailEntity(
                        'Accounting - Encoding',
                        $em->getClassMetadata(AccountingEncodeEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_DELETE
                    );
                    $newAT->entity = $accounting_encoding;
                    $newAT->parseDetails();
                    $em->persist($newAT);

                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        //$em->remove($device);
                        $accounting_encoding->setIsDeleted(true);

                        $em->flush();

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

                        $result['redirect'] = 'index';

                    } else {

                        $this->get('session')->getFlashBag()->set('error_messages', 'Something went wrong. Please try again.');
                        $result['redirect'] = 'form with error';
                    }

                    break;
            }

            $result['success'] = true;

        } else {

            foreach($errors as $error) {
                $this->get('session')->getFlashBag()->add('error_messages', $error);
            }

            $result['success'] = false;
        }

        return $result;
    }

    /**
     * @Route("/accounting_billing", name="accounting_billing")
     */
    public function accountingBillingAction() {

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

        return $this->render('@RxConnexion/Accounting/accounting_billing.html.twig', array(
            'title' => 'Manage Accounting - Billing',
            'page_title' => 'Manage Accounting - Billing',
            'javascripts' => array('rxconnexion/admin/js/accounting/accounting_billing/accounting_billing.js?v=1.0.0')
        ));
    }

    /**
     * @Route("/accounting_billing_ajax_list", name="accounting_billing_ajax_list")
     */
    public function accounting_billing_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()) {

            $hasUpdate = $authService->isUserHasAccesses(array('Admin Accounting Billing Update'), false);

            $data = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:AccountingBillingEntity')->ajax_list($get, $this->get('session')->get('userData'));

            foreach($data['results'] as $row) {

                $id = base64_encode($row['id']);
                $action = '';

                if($hasUpdate) {
                    $url = $this->generateUrl('accounting_billing_form', array(
                        'action' => 'u',
                        'id' => $id
                    ));
                    $action = "<a class='action-button-style' href='$url'>Update</a>";
                }

                $values = array(
                    $row['type'],
                    $row['invoiceNo'],
                    $row['patientPaymentId'],
                    $row['patientBillingRefundId'],
                    $row['status'],
                    $row['amount'],
                    $row['encodeDate'],
                    $row['checkDate'],
                    $action
                );

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/billing/form/{action}/{id}",
     *      defaults = {
     *          "action":  "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "accounting_billing_form"
     * )
     */
    public function accountingBillingFormAction($action, $id, Request $request) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Accounting Billing New', 'Admin Accounting Billing Update'))) return $authService->redirectToHome();

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

        $accounting_billing = $em->getRepository('RxConnexionBundle:AccountingBillingEntity')->find(base64_decode($id));
        if(!$accounting_billing) {
            $accounting_billing = new AccountingBillingEntity();
        }

        $formOptions = array(
            'action' => $action,
//            'accounting_file' => $accounting_encoding->getAccountingFile()->getId()
        );
        $form = $this->createForm(AccountingBillingForm::class, $accounting_billing, $formOptions);

        if($request->getMethod() === 'POST') {

            $accounting_billing_form = $request->get($form->getName());
            $result = $this->accountingBillingProcessForm($accounting_billing_form, $accounting_billing, $form, $request);

            if($result['success']) {
                if($result['redirect'] === 'index') {
                    return $this->redirect($this->generateUrl('accounting_billing'), 302);
                } else if($result['redirect'] === 'form') {
                    return $this->redirect($this->generateUrl('accounting_billing_form', array(
                        'action' => 'u',
                        'id' => base64_encode($result['id'])
                    )), 302);
                } else if($result['redirect'] === 'form with error') {
                    return $this->redirect($this->generateUrl('accounting_billing_form'), 302);
                }
            } else {
                $form->submit($accounting_billing_form, false);
            }
        }

        $title = ($action === 'n' ? 'New' : 'Update') . ' Accounting - Billing';

        return $this->render('@RxConnexion/Accounting/accounting_billing_form.html.twig', array(
            'title' => $title,
            'page_title' => $title,
            'javascripts' => array('rxconnexion/admin/js/accounting/accounting_billing/accounting_billing_form.js?v=1.0.0'),
            'form' => $form->createView(),
            'action' => $action,
            'id' => $id,
            'accounting_billing' => $accounting_billing
        ));
    }

    private function accountingBillingProcessForm($accounting_billing_form, $accounting_billing, $form, Request $request) {

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

        $errors = $em->getRepository('RxConnexionBundle:AccountingBillingEntity')->validate($accounting_billing_form);

        if(!count($errors)) {

            switch($accounting_billing_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if ($form->isValid()) {

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

                        $newAT = new AuditTrailEntity(
                            'Accounting - Billing',
                            $em->getClassMetadata(AccountingBillingEntity::class)->getTableName(),
                            AuditTrailEntity::AXN_NEW
                        );
                        $newAT->entity = $accounting_billing;
                        $newAT->parseDetails();
                        $em->persist($newAT);
                        $em->flush();

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

                        $result['redirect'] = 'index';

                    } else {

                        $this->get('session')->getFlashBag()->set('error_messages', 'Something went wrong. Please try again.');
                        $result['redirect'] = 'form with error';
                    }

                    break;

                case 'u': // update

                    $newAT = new AuditTrailEntity(
                        'Accounting - Billing',
                        $em->getClassMetadata(AccountingBillingEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $accounting_billing;
                    $newAT->parseOriginalDetails();

                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        $newAT->parseDetails();
                        $em->persist($newAT);

                        $em->flush();

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

                        $result['redirect'] = 'index';

                    } else {

                        $this->get('session')->getFlashBag()->set('error_messages', 'Something went wrong. Please try again.');
                        $result['redirect'] = 'form with error';
                    }

                    break;

                case 'd': // delete

                    $newAT = new AuditTrailEntity(
                        'Accounting - Billing',
                        $em->getClassMetadata(AccountingBillingEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_DELETE
                    );
                    $newAT->entity = $accounting_billing;
                    $newAT->parseDetails();
                    $em->persist($newAT);

                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        //$em->remove($device);
                        $accounting_billing->setIsDeleted(true);

                        $em->flush();

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

                        $result['redirect'] = 'index';

                    } else {

                        $this->get('session')->getFlashBag()->set('error_messages', 'Something went wrong. Please try again.');
                        $result['redirect'] = 'form with error';
                    }

                    break;
            }

            $result['success'] = true;

        } else {

            foreach($errors as $error) {
                $this->get('session')->getFlashBag()->add('error_messages', $error);
            }

            $result['success'] = false;
        }

        return $result;
    }

    private function processTmpFiles($accounting_file, $accounting_file_form){
        $em = $this->getDoctrine()->getManager();
        $tmpDir = AccountingEncodeEntity::TMP_UPLOAD_DIR;
        $files = scandir($tmpDir);

        if(count($files) - 2){

            foreach($files as $fileName) {
                if(FALSE === strpos($fileName, $accounting_file_form['file_temp_name'] . '-')) {
                    continue;
                }
                $accountingFileUpload = new AccountingEncodeEntity();
                $accountingFileUpload->setAccountingFile($accounting_file);
                $em->persist($accountingFileUpload);
                $em->flush();

                $baseName = $accountingFileUpload->getId() . '-' . time() . '.' . pathinfo($fileName, PATHINFO_EXTENSION);
                $dir = $accountingFileUpload->getUploadRootDir();
                $accountingFileUpload->setFileDesc($fileName);
                $accountingFileUpload->setParsedFileDesc($baseName);

                copy(($tmpDir . '/' . $fileName), ($dir . '/' . $baseName));

                $em->flush();

                unlink($tmpDir . '/' . $fileName);
            }
        }
    }

    /**
     * @Route("/accounting_file/download/{id}", name="accounting_file_download")
     */
    public function accounting_file_downloadAction($id) {

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

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

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

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

            if($handle !== false) {

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

                fclose($handle);
            }
        }

        exit();
    }

    /**
     * @Route(
     *      "/process_file",
     *      name = "accounting_file_proccess_file"
     * )
     */
    public function process_fileAction(Request $request)
    {
        $tmpFileName = $request->get('tmpFileName');
        $fileName = $_FILES['file']['name'];
        $uploadDir = AccountingEncodeEntity::TMP_UPLOAD_DIR;

        move_uploaded_file($_FILES['file']['tmp_name'], $uploadDir . '/' . $tmpFileName . '-' . $fileName);

        return new JsonResponse(array(
            'success' => true,
            'msg' => 'File successfully uploaded.'
        ));
    }


        /**
     * @Route(
     *      "/proccess_remove_file",
     *      name = "accounting_file_process_remove_file"
     * )
     */
    public function process_remove_fileAction(Request $request){
        $tmpFileName = $request->get('file_temp_name');
        $fileName = $request->get('fileName');

        $uploadDir = AccountingEncodeEntity::TMP_UPLOAD_DIR;

        $file = $uploadDir . '/' . $tmpFileName . '-' . $fileName;
        if(file_exists($file)) unlink($file);

        return new JsonResponse(array(
            'success' => true,
            'msg' => 'File successfully removed.'
        ));

    }

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

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

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

        return new JsonResponse($result);
    }

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

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

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

        $json = array(
            'overview' => $dashboardData['overview'],
            'accounting_billing' => $dashboardData['accounting_billing'],
        );

        return new JsonResponse($json);
    }

    /**
     * @Route("/billing/autocomplete", name="patient_billing_autocomplete")
     */
    public function patientBillingAutocompleteAction(Request $request) {

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route("/payment/autocomplete", name="patient_payment_autocomplete")
     */
    public function patientPaymentAutocompleteAction(Request $request) {

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route("/refund/autocomplete", name="patient_refund_autocomplete")
     */
    public function patientRefundAutocompleteAction(Request $request) {

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

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

        return new JsonResponse($result);
    }

}
