<?php
/**
 * Created by PhpStorm.
 * User: Moldedcraft 1
 * Date: 27 Feb 2019
 * Time: 3:35 PM
 */

namespace RxConnexionBundle\Controller;

use RxConnexionBundle\Entity\FaxingOptionEntity;
use RxConnexionBundle\Entity\FaxingOptionFileEntity;
use RxConnexionBundle\Entity\FaxingOptionOutboundEntity;
use RxConnexionBundle\Entity\FaxTranEntity;
use RxConnexionBundle\Form\FaxingOptionForm;
use RxConnexionBundle\Form\FaxTranForm;
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\BinaryFileResponse;
use Symfony\Component\HttpFoundation\Response;


/**
 * @Route("/main/fax")
 */
class FaxTranController extends Controller
{

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

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

        // fax api
        $this->getFaxInbox();


        $monthNow = date('n');
        $yearNow = date('Y');
        $yr=$yearNow;
        $monthFilter = array();
        $i = 0;
        for ($m=$monthNow; $m > $monthNow-12; $m--) {
            if($m < 1){
                $yr = $yearNow-1;
            }
            $month = date('F', mktime(0,0,0,$m, 1, date('Y')));
            $monthFilter[$i]['display'] = $yr.' - '.$month;
            $monthFilter[$i]['value'] = $yr.'|'.abs($m);
            $i++;
        }

        $em = $this->getDoctrine()->getManager();
        $moaUsers = $em->getRepository('RxConnexionBundle:AccountUserEntity')->getMOAUserType();

        if($request->getMethod() === 'POST'){
            $get = $request->get('forms');
            if(isset($get['faxTran'])){
                foreach ($get['faxTran'] as $faxTran){
                    $faxTran = $em->getRepository('RxConnexionBundle:FaxTranEntity')->find($faxTran);
                    $faxTran->setAccountUser($em->getReference('RxConnexionBundle:AccountUserEntity', $get['accountUser']));
                    $em->flush();
                }
                $this->get('session')->getFlashBag()->set('success_messages', count($get['faxTran']) . ' fax assigned to ' . $faxTran->getAccountUser()->getFullName() . '.');
            }else{
                $this->get('session')->getFlashBag()->set('error_messages', 'Please select a fax to assign.');
            }
        }


        return $this->render('@RxConnexion/Fax/index.html.twig', array(
            'title' => 'Fax',
            'page_title' => 'Fax',
            'javascripts' => array('rxconnexion/admin/js/faxTran/faxTran.js?v=1.0.5'),
            'monthFilter'  => $monthFilter,
            'statusFilter'  => FaxTranEntity::STATUS,
            'moaUsers' => $moaUsers
        ));
    }

    /**
     * @Route("/view/{id}/{sDirection}",
     *      defaults = {
     *          "id": "0",
     *          "sDirection": "IN"
     *      },
     *     name="fax_view")
     */
    public function viewFaxById($id, $sDirection, Request $request) {

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

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

        $srFax = $this->get('rx_connexion.SRFaxService');

        $em = $this->getDoctrine()->getManager();
        $faxTran = $em->getRepository('RxConnexionBundle:FaxTranEntity')->find($id);

        if($faxTran){
            $sFaxDetailsID = $faxTran->getFaxId();
            $faxData = array(
                'sFaxFormat' => 'PDF',
                'sFaxDetailsID' => $sFaxDetailsID,
                'sDirection' => $sDirection,
            );
            $faxQuery = $srFax->Retrieve_Fax($faxData);
            if($faxQuery){
                $uploadDir = __DIR__ . '/../../../web/uploads/fax/';
                $uploadName = $faxData['sFaxDetailsID'];
                // Check first if the file is already saved
                if(!file_exists($uploadDir.$uploadName.'.pdf')) {
                    $srFax->saveLastResponseAsFile($uploadName.'.pdf',$uploadDir);
                }
                return new BinaryFileResponse($uploadDir.$uploadName.'.pdf');
            } else {
//                $error = $srFax->getRequestResponse();
//                $this->get('session')->getFlashBag()->set('error_messages', $error);
//                return $this->redirect($this->generateUrl('fax'));

                $uploadName = $sFaxDetailsID;
                $uploadDir = __DIR__ . '/../../../web/uploads/fax/';
                // Check first if the file is already saved
                if(file_exists($uploadDir.$uploadName.'.pdf')) {
                    return new BinaryFileResponse($uploadDir.$uploadName.'.pdf');
                } else {
                    $error = $srFax->getRequestResponse();
                    $this->get('session')->getFlashBag()->set('error_messages', $error);
                    return $this->redirect($this->generateUrl('fax'));
                }

            }
        } else {
            $this->get('session')->getFlashBag()->set('error_messages', 'Fax not found');
            return $this->redirect($this->generateUrl('fax'));
        }

        if($faxTran){
            $sFaxDetailsID = $faxTran->getFaxId();
            $faxData = array(
                'sFaxFormat' => 'PDF',
                'sFaxDetailsID' => $sFaxDetailsID,
                'sDirection' => $sDirection,
            );
//            $faxQuery = $srFax->Retrieve_Fax($faxData);
            if($sFaxDetailsID){
                $uploadDir = __DIR__ . '/../../../web/uploads/fax/';
                $uploadName = $sFaxDetailsID;
                // Check first if the file is already saved
//                if(!file_exists($uploadDir.$uploadName.'.pdf')) {
//                    $srFax->saveLastResponseAsFile($uploadName.'.pdf',$uploadDir);
//                }
                return new BinaryFileResponse($uploadDir.$uploadName.'.pdf');
            } else {
//                $error = $srFax->getRequestResponse();
                $this->get('session')->getFlashBag()->set('error_messages', 'Fax not found');
                return $this->redirect($this->generateUrl('fax'));
            }
        } else {
            $this->get('session')->getFlashBag()->set('error_messages', 'Fax not found');
            return $this->redirect($this->generateUrl('fax'));
        }


    }

    /**
     * @Route("/ajax_list", name="fax_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()) {

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

            foreach($data['results'] as $row) {
                $url = $this->generateUrl('fax_view', array(
                    'id' => $row['id'],
                    'sDirection' => 'IN',
                ));
                $encryptId = base64_encode($row['id']);
                $viewBtn = "<a  class='action-button-style' href='$url' target='_blank'>View</a>";
                $updateBtn = "<a data-action='u' data-id='$encryptId' class='action-button-style href-faxTran-form' href='javascript:void(0)'>Details</a>";

                if($row['fax_category']=='Referral') {
                    $referral = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:ReferralEntity')->findOneBy(array('faxTran'=>$row['id']));
                    if($referral){
                        $referralUrl = $this->generateUrl('referral_form',array('action'=> 'u', 'id' => base64_encode($referral->getId()), 'faxTranId' => $row['id']));
                        $referralBtn = "<a class='action-button-style href-faxTran-link' href='$referralUrl' data-faxTranId='".$row['id']."'>View Referral</a>";
                    } else {
                        $referralUrl = $this->generateUrl('referral_form',array('faxTranId' => $row['id']));
                        $referralBtn = "<a class='action-button-style href-faxTran-link' href='$referralUrl' data-faxTranId='".$row['id']."'>Create Referral</a>";
                    }
                } else {
                    $referralBtn = '';
                }
                $values = array(
                    $row['account_user_id'] === null ? "<input type='checkbox' style='margin:10px;' name='forms[faxTran][$row[id]]' value='$row[id]'>".$row['fax_date'] : $row['fax_date'],
//                    $row['remote_id'] == null ? '-' : $row['remote_id'],
                    $row['remote_id'] == null ? '8332624798' : $row['remote_id'],
                    $row['pages'],
                    $row['fax_category'],
                    $row['patient'],
                    $row['health_facility'],
                    $row['assignedTo'],
                    $row['fax_status'] == '1' ? 'Closed' : 'Active',
                    $viewBtn.$updateBtn.$referralBtn
                );

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

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

        return new JsonResponse($result);
    }


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

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

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

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


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

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

    /**
     * @Route(
     *      "/form/save_action",
     *      name = "fax_form_save"
     * )
     */
    public function 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 Fax', 'Admin Fax Update'))) return $authService->redirectToHome();

        $faxTran_form = $request->get('faxTran');
        $em = $this->getDoctrine()->getManager();
        $faxTran = $em->getRepository('RxConnexionBundle:FaxTranEntity')->find($faxTran_form['id']);
        if(!$faxTran) {
            $faxTran = new FaxTranEntity();
        }
        $formOptions = array(
            'action' => $faxTran_form['action'],
        );
        $form = $this->createForm(FaxTranForm::class, $faxTran, $formOptions);
        $errors = $em->getRepository('RxConnexionBundle:FaxTranEntity')->validate($faxTran_form);


        if(!count($errors)) {

            switch($faxTran_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if($form->isValid()) {

                        $em->persist($faxTran_form);
                        $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 LETTER 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()) {
                        $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);
                        $faxTran->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("/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);
    }


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