<?php

namespace RxConnexionBundle\Controller;

use RxConnexionBundle\Entity\ClinicmasterFileEntity;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;

/**
 * @Route("/main/clinicmaster_file")
 */
class ClinicmasterFileController extends Controller
{
    /**
     * @Route("", name="clinicmaster_file")
     */
    public function indexAction() {

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

        return $this->render('@RxConnexion/ClinicmasterFile/index.html.twig', array(
            'title' => 'Manage Clinicmaster Files',
            'page_title' => 'Manage Clinicmaster Files',
            'javascripts' => array('rxconnexion/admin/js/clinicmasterFile/clinicmasterFile.js?v=1.0.0')
        ));
    }

    /**
     * @Route("/ajax_list", name="clinicmaster_file_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:ClinicmasterFileEntity')->ajax_list($get);

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

                $id = base64_encode($row['id']);
                $url = $this->generateUrl('clinicmaster_file_download', array(
                    'id' => $id
                ));
                $action = "<a class='action-button-style' href='$url'><i class='fa fa-download'></i> Download</a>";

                if($row['patient_id'] > 0) {
                    $url = $this->generateUrl('patient_detail', array(
                        'patient_id' => base64_encode($row['patient_id']),
                        'tab' => 'cmf'
                    ));
                    $patient = '<a target="_blank" href="'.$url.'">'.$row['patientName'].'</a>';
                } else {
                    $patient = $row['patientName'];
                }

                $values = array(
                    $row['branchName'],
                    $patient,
                    $row['description'],
                    $action
                );

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route("/ajax_list_patient", name="clinicmaster_file_ajax_list_patient")
     */
    public function ajax_list_patient(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:ClinicmasterFileEntity')->ajax_list_patient($get);

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

                $id = base64_encode($row['id']);
                $url = $this->generateUrl('clinicmaster_file_download', array(
                    'id' => $id
                ));
                $action = "<a class='action-button-style' href='$url'><i class='fa fa-download'></i> Download</a>";

                $values = array(
                    $row['description'],
                    $action
                );

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

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

        return new JsonResponse($result);
    }

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

        $clinicmasterFile = $this->getDoctrine()->getManager()->getRepository(ClinicmasterFileEntity::class)->find(base64_decode($id));

        $filePath = $this->getParameter('clinicmaster_file_dir') . '/' . $clinicmasterFile->getParsedDescription();
        $handle = fopen($filePath, 'rb');

        if(FALSE !== $handle) {

            header("Pragma: public");
            header('Content-Disposition: attachment; filename="' . $clinicmasterFile->getDescription() . '"');
            header('Expires: 0');
            header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
            header("Content-Transfer-Encoding: binary");
            header("Content-Type: " . mime_content_type($filePath));
            header("Content-Length: " . filesize($filePath));
            ob_clean();

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

            fclose($handle);
        }

        exit();
    }
}