<?php

namespace RxConnexionBundle\Repository;

use RxConnexionBundle\Entity\PatientPaymentEntity;

/**
 * PatientPaymentRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class PatientPaymentRepository extends \Doctrine\ORM\EntityRepository
{
    public function validate($patientPayment_form, $patientPaymentBreakdown_form=null) {

        $errors = array();

        $action = $patientPayment_form['action'];

        // d = delete
        if($action !== 'd') {

        	if($action == 'v') {
        		/**@var PatientPaymentEntity $patientPayment*/
        		$patientPayment = $this->find($patientPayment_form['id']);
        		if($patientPayment->getPatientBillingFinancing()) {
			        if($patientPayment->getPatientBillingFinancing()->getAmountPaid() > 0) {
				        $errors[] = 'The auto created financing invoice already has a payment';
			        }
		        }


	        }

            if(is_null($patientPaymentBreakdown_form) && $action == 'n'){
                $errors[] = 'Payment Breakdown is empty. Please try again.';
            } else {
                if($action === 'n' && count($patientPaymentBreakdown_form)){
                    foreach($patientPaymentBreakdown_form as $ppb){
//                        if(floatval(str_replace(',','',$ppb['amount'])) > floatval(str_replace(',','',$ppb['amount_balance']))){
//                            $errors[] = 'Amount to Pay for ' .$ppb['item']. ' must be less than or equal to it\'s Balance';
//                        }
                    }
                }elseif($action === 'u' && count($patientPaymentBreakdown_form)){
                    foreach($patientPaymentBreakdown_form as $ppb){
                        if(floatval(str_replace(',','',$ppb['amount'])) > (floatval(str_replace(',','',$ppb['amount_balance'])) + floatval(str_replace(',','',$ppb['amount_paid'])))){
                            $errors[] = 'Amount to Pay for ' .$ppb['item']. ' must be less than or equal to it\'s amount';
                        }
                    }
                }
            }



            if(empty($patientPayment_form['patient'])) {
                $errors[] = 'Something went wrong. Please try again.';
            }

            if(empty($patientPayment_form['pay_date'])) {
                $errors[] = 'Payment date should not be blank.';
            }

            if(empty($patientPayment_form['pay_type'])) {
                $errors[] = 'Payment type should not be blank.';
            }

            if(empty($patientPayment_form['amount'])) {
                $errors[] = 'Amount should not be blank.';
            }
            if(intval($patientPayment_form['amount']) <= 0) {
                $errors[] = 'Amount should not be less than or equal to 0.';
            }

            if(empty($patientPayment_form['patientBilling'])) {
                $errors[] = 'Please select invoice no.';
            }


            /* FOR FINANCING */
            if($patientPayment_form['pay_type'] == 'Financing') {

                if(empty($patientPayment_form['financingCompany'])) {
                    $errors[] = 'Financing Company should not be blank';
                }

                /*if(empty($patientPayment_form['newInvoiceNoForFinancing'])) {
                    $errors[] = 'Invoice number for financing should not be blank';
                }*/

                if(isset($patientPayment_form['is_payment_plan'])){
                    if(empty($patientPayment_form['start_date'])) {
                        $errors[] = 'Start Date should not be blank';
                    }

                    if(empty($patientPayment_form['end_date'])) {
                        $errors[] = 'End Date should not be blank';
                    }

                    if(empty($patientPayment_form['payment_day'])) {
                        $errors[] = 'Payment Day should not be blank';
                    }
                }

            }

/*            if(empty($patientPayment_form['note'])) {
                $errors[] = 'Notes should not be blank.';
            }*/
        }

        return $errors;
    }

    public function ajax_list(array $get){

        $columns = array(
            array('pb.`invoice_no`', "IF(pp.`patient_billing_id` IS NULL, CONCAT(pp.`prev_sys_invoice_no`, ' (Imported) ') ,IF((pb.`invoice_no` IS NULL OR pb.`invoice_no` = '') AND pb.`prev_sys_invoice_no` IS NOT NULL, CONCAT(pb.`prev_sys_invoice_no`, ' (Imported)'), pb.`invoice_no`))", 'invoiceNo'),
            array('hf.`description`', 'IF(pp.`patient_billing_id` IS NULL, pp.`prev_sys_invoice_branch`,hf.`description`)', 'healthFacility'),
            array('pp.`payment_status`', 'pp.`payment_status`', 'status'),
            /*array('pp.`id`', 'LPAD(pp.`id`, 6, 0)', 'payNo'),*/
            array('pp.`pay_date`',  "DATE_FORMAT(pp.`pay_date`, '%m/%d/%Y')", 'payDate'),
            array('pp.`pay_type`', 'pp.`pay_type`', 'payType'),
            array('pp.`amount`', 'pp.`amount`'),
            array('pp.`id`', 'pp.`id`')
        );
        $asColumns = array();

        $select = "SELECT";
        $from = "FROM `patient_payment` pp";
        $joins = "
            LEFT JOIN `patient_billing` pb ON pp.`patient_billing_id` = pb.`id`
            LEFT JOIN `health_facility` hf ON pb.`health_facility_for_address_id` = hf.`id` 
        ";
        $sqlWhere = "WHERE pp.`is_deleted` = 0";
        $sqlWhere .= " AND pp.`patient_id` = :patient_id";
        $groupBy = "";
        $orderBy = "";
        $limit = "";
        $stmtParams = array(
            'patient_id' => base64_decode($get['patient_id'])
        );

        if($get['status'] != 'All'){
            $sqlWhere .= " AND pp.`payment_status` = :paymentStatus";
            $stmtParams['paymentStatus'] = $get['status'];
        }

        foreach($columns as $key => $column) {
            $select .= ($key > 0 ? ', ' : ' ') . $column[1] . (isset($column[2]) ? ' AS ' . $column[2] : '');
        }

        /*
         * Ordering
         */
        foreach($get['columns'] as $key => $column) {
            if($column['orderable']=='true') {
                if(isSet($get['order'])) {
                    foreach($get['order'] as $order) {
                        if($order['column']==$key) {
                            $orderBy .= (!empty($orderBy) ? ', ' : 'ORDER BY ') . $columns[$key][0] . (!empty($order['dir']) ? ' ' . $order['dir'] : '');
                        }
                    }
                }
            }
        }

        /*
         * Filtering
         */
        if(isset($get['search']) && $get['search']['value'] != ''){
            $aLikes = array();
            foreach($get['columns'] as $key => $column) {
                if($column['searchable']=='true') {
                    $aLikes[] = $columns[$key][0] . ' LIKE :searchValue';
                }
            }
            foreach($asColumns as $asColumn) {
                $aLikes[] = $asColumn . ' LIKE :searchValue';
            }
            if(count($aLikes)) {
                $sqlWhere .= (!empty($sqlWhere) ? ' AND ' : 'WHERE ') . '(' . implode(' OR ', $aLikes) . ')';
                $stmtParams['searchValue'] = "%" . $get['search']['value'] . "%";
            }
        }

        /* Set Limit and Length */
        if(isset( $get['start'] ) && $get['length'] != '-1'){
            $limit = 'LIMIT ' . (int)$get['start'] . ',' . (int)$get['length'];
        }

        $conn = $this->getEntityManager()->getConnection();

        $sql = "$select $from $joins $sqlWhere $groupBy $orderBy";
        $query = $conn->prepare($sql);
        $query->execute($stmtParams);
        $result_count = $query->fetchAll();

        $sql = "$select $from $joins $sqlWhere $groupBy $orderBy $limit";
        $query = $conn->prepare($sql);
        $query->execute($stmtParams);
        $result = $query->fetchAll();

        return array(
            'results' => $result,
            'total' => count($result_count)
        );
    }

    public function reportPayment($params) {
        $sqlWhere = "WHERE pat.`is_deleted` = 0 AND pp.`is_deleted` = 0";
        $stmtParams = array();

        if (!is_null($params['date_from']) && $params['date_from'] !== 'null' && $params['date_from'] !== 'all' && !empty($params['date_from']) && !is_null($params['date_to']) && $params['date_to'] !== 'null' && $params['date_to'] !== 'all' && !empty($params['date_to'])) {
            $sqlWhere .= (empty($sqlWhere) ? "WHERE " : " AND ") . "pp.`pay_date` BETWEEN :date_from AND :date_to";
            $stmtParams['date_from'] = date('Y-m-d 00:00:00', strtotime(str_replace('-',  '/', $params['date_from'])));
            $stmtParams['date_to'] = date('Y-m-d 23:59:59', strtotime(str_replace('-', '/', $params['date_to'])));
        }

        if(isset($params['patient']) && !empty($params['patient']) && 'NULL' !== strtoupper($params['patient'])){
            $sqlWhere .= (empty($sqlWhere) ? "WHERE " : " AND ") . "pp.`patient_id` = :patient";
            $stmtParams['patient'] = $params['patient'];
        }

        if(isset($params['branch']) && !empty($params['branch']) && 'NULL' !== strtoupper($params['branch'])){
            $branches = explode(',' , $params['branch']);
            if(count($branches) > 0){
                $hf_ors = '';
                foreach($branches as $key => $branchId){
                    $hf_ors .= (empty($hf_ors) ? '' : ' OR ') . "pb.`health_facility_id` = :healthFacility_id_$key";
                    $stmtParams["healthFacility_id_$key"] = $branchId;
                }
                $sqlWhere .= " AND ($hf_ors) ";
            }
        }

        if(isset($params['branchAddress']) && !empty($params['branchAddress']) && 'NULL' !== strtoupper($params['branchAddress'])){
            $branchAddresses = explode(',' , $params['branchAddress']);
            if(count($branchAddresses) > 0){
                $hf_ors = '';
                foreach($branchAddresses as $key => $branchAddressId){
                    $hf_ors .= (empty($hf_ors) ? '' : ' OR ') . "pb.`health_facility_for_address_id` = :healthFacilityAddress_id_$key";
                    $stmtParams["healthFacilityAddress_id_$key"] = $branchAddressId;
                }
                $sqlWhere .= " AND ($hf_ors) ";
            }
        }

        if(isset($params['company']) && !empty($params['company']) && 'NULL' !== strtoupper($params['company'])){
            $companies = explode(',' , $params['company']);
            if(count($companies) > 0){
                $co_ors = '';
                foreach($companies as $key => $companyId){
                    $co_ors .= (empty($co_ors) ? '' : ' OR ') . "hf.`company_id` = :company_id_$key";
                    $stmtParams["company_id_$key"] = $companyId;
                }
                $sqlWhere .= " AND ($co_ors) ";
            }
        }

        if(isset($params['paymentType']) && !empty($params['paymentType']) && 'NULL' !== strtoupper($params['paymentType'])){
            $sqlWhere .= (empty($sqlWhere) ? "WHERE " : " AND ") . "pp.`pay_type` = :paymentType";
            $stmtParams['paymentType'] = $params['paymentType'];
        }

        if(isset($params['paymentStatus']) && !empty($params['paymentStatus']) && 'NULL' !== strtoupper($params['paymentStatus'])){
            $sqlWhere .= (empty($sqlWhere) ? "WHERE " : " AND ") . "pp.`payment_status` = :paymentStatus";
            $stmtParams['paymentStatus'] = $params['paymentStatus'];
        }

        if(isset($params['financingCompany']) && !empty($params['financingCompany']) && 'NULL' !== strtoupper($params['financingCompany'])){
            $financingCompanies = explode(',' , $params['financingCompany']);
            if(count($financingCompanies) > 0){
                $co_ors = '';
                foreach($financingCompanies as $key => $financingCompanyId){
                    $co_ors .= (empty($co_ors) ? '' : ' OR ') . "pp.`financing_company_id` = :financing_company_id_$key";
                    $stmtParams["financing_company_id_$key"] = $financingCompanyId;
                }
                $sqlWhere .= " AND ($co_ors) ";
            }
        }

        if($params['company'] == 'null' && $params['branch'] == 'null' && $params['branchAddress'] == 'null') {
            if (!is_null($params['userData']) && !empty($params['userData'])) {
                if ($params['userData']['type'] != 'Super Admin') {
                    if (count($params['userData']['company']['companyBranches']) > 0) {
                        $hf_ors = '';
                        foreach ($params['userData']['company']['companyBranches'] as $key => $branchId) {
                            $hf_ors .= (empty($hf_ors) ? '' : ' OR ') . "pb.`health_facility_id` = $branchId";
                        }
                        $sqlWhere .= (empty($andWhere) ? " AND " : "") . " ($hf_ors) ";
                    } else {
                        $sqlWhere .= (empty($andWhere) ? " AND " : "") . " (1 != 1) ";
                    }
                }
            }
        }

        $sql = "
            SELECT
                pp.`id`,
                pat.`id` AS patientId,
                pp.`pay_type`,
                pat.`full_name` AS patientName,
                IF(pp.`patient_billing_id` IS NULL, CONCAT(pp.`prev_sys_invoice_no`, ' (Imported) ') ,IF((pb.`invoice_no` IS NULL OR pb.`invoice_no` = '') AND pb.`prev_sys_invoice_no` IS NOT NULL, CONCAT(pb.`prev_sys_invoice_no`, ' (Imported)'), pb.`invoice_no`)) AS invoiceNo,
                IF(pp.`patient_billing_id` IS NULL, pp.`prev_sys_invoice_branch`,hf.`description`) AS billingBranch,
                IF(pp.`patient_billing_id` IS NULL, pp.`prev_sys_invoice_branch`,hf_add.`description`) AS branchAddress,
                DATE_FORMAT(pp.`pay_date`, '%m/%d/%Y') pay_date,
                pp.`amount`,
                pp.`bill_due_amount`,
                pp.`bill_paid_amount`,
                pp.`bill_bal_amount`,
                pp.`note`,
                pp.`payment_status`,
                fc.`description` AS financingCompany,
                ppb.patientPayment_breakdowns
            FROM `patient_payment` pp
            LEFT JOIN `patient` pat ON pp.`patient_id` = pat.`id`
            LEFT JOIN `patient_billing` pb ON pb.`id` = (
					SELECT pb1.`id`
					FROM `patient_billing` pb1
					WHERE pb1.`patient_id` = pat.`id`
					AND pb1.`id` = pp.`patient_billing_id`
					LIMIT 1
			)
			LEFT JOIN (
			  SELECT pptmp.`id` AS patientPayment_id,
                       GROUP_CONCAT(CONCAT_WS('|', ppbtmp.`id`, pbbtmp.`type`, ppbtmp.`amount`, CASE
                                                                                   WHEN pbbtmp.`type` = 'Chart Procedure'
                                                                                     THEN CONCAT_WS(' - ', pctmp.`id`, pctmp.`chart_date`, cttmp.`description`)
                                                                                   WHEN pbbtmp.`type` = 'Item' THEN i.`description`
                                                                                   ELSE pbbtmp.`description`
                         END) SEPARATOR '~') AS patientPayment_breakdowns
              FROM `patient_payment_breakdown` ppbtmp
              LEFT JOIN `patient_payment` pptmp on ppbtmp.`patient_payment_id` = pptmp.`id`
              LEFT JOIN `patient_billing_breakdown` pbbtmp on ppbtmp.`patient_billing_breakdown_id` = pbbtmp.`id`
              LEFT JOIN `item` i on pbbtmp.`item_id` = i.`id`
              LEFT JOIN `patient_chart` pctmp on pbbtmp.`patient_chart_id` = pctmp.`id`
              LEFT JOIN `chart_type` cttmp on pctmp.`chart_type_id` = cttmp.`id`
              WHERE pptmp.`is_deleted` = 0 AND ppbtmp.`is_deleted` = 0 AND ppbtmp.amount > 0
              GROUP BY ppbtmp.`patient_payment_id`
			) ppb ON pp.`id` = ppb.`patientPayment_id`
			LEFT JOIN `health_facility` hf ON pb.`health_facility_id` = hf.`id`
			LEFT JOIN `health_facility` hf_add ON pb.health_facility_for_address_id = hf_add.`id`
			LEFT JOIN `company` co ON hf.`company_id` = co.`id`
            LEFT JOIN `financing_company` fc ON pp.`financing_company_id` = fc.`id`
            $sqlWhere
            AND pat.`is_test_patient` != 1
           -- AND hf.`description` NOT IN('Demo_Test', 'DemoLocation')
            ORDER BY pp.`pay_date` DESC
        ";

        $sqlSummary = "
            SELECT
               IF(pp.`patient_billing_id` IS NULL, pp.`prev_sys_invoice_branch`,hf_add.`description`) AS billingBranch,
               COUNT(pp.`id`) AS transactionCount,
               SUM(pp.`amount`) AS totalAmt
            FROM `patient_payment` pp
            LEFT JOIN `patient` pat ON pp.`patient_id` = pat.`id`
            LEFT JOIN `patient_billing` pb ON pb.`id` = (
					SELECT pb1.`id`
					FROM `patient_billing` pb1
					WHERE pb1.`patient_id` = pat.`id`
					AND pb1.`id` = pp.`patient_billing_id`
					LIMIT 1
			)
			LEFT JOIN `health_facility` hf ON pb.`health_facility_id` = hf.`id`
			LEFT JOIN `health_facility` hf_add ON pb.health_facility_for_address_id = hf_add.`id`
			LEFT JOIN `company` co ON hf.`company_id` = co.`id`
            LEFT JOIN `financing_company` fc ON pp.`financing_company_id` = fc.`id`
            $sqlWhere
            AND pat.`is_test_patient` != 1
           -- AND hf.`description` NOT IN('Demo_Test', 'DemoLocation')
            GROUP BY IF(pp.`patient_billing_id` IS NULL, pp.`prev_sys_invoice_branch`,hf_add.`description`)
        ";

        $sqlBreakdown = "
            SELECT
               pp.`pay_type` AS paymentType,
               COUNT(pp.`id`) AS transactionCount,
               SUM(pp.`amount`) AS totalAmt
            FROM `patient_payment` pp
            LEFT JOIN `patient` pat ON pp.`patient_id` = pat.`id`
            LEFT JOIN `patient_billing` pb ON pb.`id` = (
					SELECT pb1.`id`
					FROM `patient_billing` pb1
					WHERE pb1.`patient_id` = pat.`id`
					AND pb1.`id` = pp.`patient_billing_id`
					LIMIT 1
			)
			LEFT JOIN `health_facility` hf ON pb.`health_facility_id` = hf.`id`
			LEFT JOIN `health_facility` hf_add ON pb.health_facility_for_address_id = hf_add.`id`
			LEFT JOIN `company` co ON hf.`company_id` = co.`id`
            LEFT JOIN `financing_company` fc ON pp.`financing_company_id` = fc.`id`
            $sqlWhere
            AND pat.`is_test_patient` != 1
           -- AND hf.`description` NOT IN('Demo_Test', 'DemoLocation')
            GROUP BY pp.`pay_type`
        ";

        $conn = $this->getEntityManager()->getConnection();

        $query1 = $conn->prepare($sql);
        $query2 = $conn->prepare($sqlSummary);
        $query3 = $conn->prepare($sqlBreakdown);

        $query1->execute($stmtParams);
        $query2->execute($stmtParams);
        $query3->execute($stmtParams);

        $result['payment'] = $query1->fetchAll();
        $result['summary'] = $query2->fetchAll();
        $result['breakdown'] = $query3->fetchAll();

        return $result;
    }

    public function reportPaymentWithoutInvoice($params) {
        $sqlWhere = "WHERE pat.`is_deleted` = 0 AND pp.`patient_billing_id` IS NULL";
        $stmtParams = array();

        if (!is_null($params['date_from']) && $params['date_from'] !== 'null' && $params['date_from'] !== 'all' && !empty($params['date_from']) && !is_null($params['date_to']) && $params['date_to'] !== 'null' && $params['date_to'] !== 'all' && !empty($params['date_to'])) {
            $sqlWhere .= (empty($sqlWhere) ? "WHERE " : " AND ") . "pp.`pay_date` BETWEEN :date_from AND :date_to";
            $stmtParams['date_from'] = date('Y-m-d 00:00:00', strtotime(str_replace('-',  '/', $params['date_from'])));
            $stmtParams['date_to'] = date('Y-m-d 23:59:59', strtotime(str_replace('-', '/', $params['date_to'])));
        }

        if(isset($params['company']) && !empty($params['company']) && 'NULL' !== strtoupper($params['company'])){
            $sqlWhere .= (empty($sqlWhere) ? "WHERE " : " AND ") . "hf.`company_id` = :company";
            $stmtParams['company'] = $params['company'];
        }

        if(isset($params['branch']) && !empty($params['branch']) && 'NULL' !== strtoupper($params['branch'])){
            $sqlWhere .= (empty($sqlWhere) ? "WHERE " : " AND ") . "temp_hf.`healthFacilityId` = :branch";
            $stmtParams['branch'] = $params['branch'];
        }

        if(isset($params['patient']) && !empty($params['patient']) && 'NULL' !== strtoupper($params['patient'])){
            $sqlWhere .= (empty($sqlWhere) ? "WHERE " : " AND ") . "pp.`patient_id` = :patient";
            $stmtParams['patient'] = $params['patient'];
        }

        if($params['company'] == 'null' && $params['branch'] == 'null') {
            if (!is_null($params['userData']) && !empty($params['userData'])) {
                if ($params['userData']['type'] != 'Super Admin') {
                    if (count($params['userData']['company']['companyBranches']) > 0) {
                        $hf_ors = '';
                        foreach ($params['userData']['company']['companyBranches'] as $key => $branchId) {
                            $hf_ors .= (empty($hf_ors) ? '' : ' OR ') . "temp_hf.`healthFacilityId` = $branchId";
                        }
                        $sqlWhere .= (empty($andWhere) ? " AND " : "") . " ($hf_ors) ";
                    } else {
                        $sqlWhere .= (empty($andWhere) ? " AND " : "") . " (1 != 1) ";
                    }
                }
            }
        }


        $sql = "
            SELECT
                pp.`id`,
                pat.`id` AS patientId,
                pp.`pay_type`,
                hf.`description` AS branchDesc,
                co.`description` AS companyDesc,
                pat.`full_name` AS patientName,
                DATE_FORMAT(pp.`pay_date`, '%m/%d/%Y') pay_date,
                pp.`amount`,
                pp.`note`,
                pp.`payment_status`,
                pp.`prev_sys_invoice_no`,
                pp.`prev_sys_invoice_branch`
            FROM `patient_payment` pp
            LEFT JOIN `patient` pat ON pp.`patient_id` = pat.`id`
            LEFT JOIN (SELECT
                          phf.`patient_id` AS patientId,
                          phf.`health_facility_id` AS healthFacilityId
                       FROM `patient_health_facility` phf
                       LEFT JOIN `health_facility` hf ON phf.`health_facility_id` = hf.`id`
                       WHERE phf.`end_date` IS NULL
                       ORDER BY phf.`created_at` DESC
            ) temp_hf ON temp_hf.`patientId` = pat.`id`
            LEFT JOIN `health_facility` hf ON temp_hf.`healthFacilityId` = hf.`id`
            LEFT JOIN `company` co ON hf.`company_id` = co.`id`
            $sqlWhere
            AND pat.`is_test_patient` != 1
            ORDER BY pp.`pay_date` DESC
        ";

        $query = $this->getEntityManager()->getConnection()->prepare($sql);
        $query->execute($stmtParams);

        $result = $query->fetchAll();

        return $result;
    }

    public function findFinancingPaymentForThisMonth($patientId, $billingId){
        $date = new \DateTime();
        $m = $date->format('m');


        $sqlWhere = "WHERE pat.`is_deleted` = 0 AND 
                            pp.`patient_id` = :patient_id AND 
                            pb.`id` = :billing_id AND 
                            MONTH(pp.`pay_date`) = :month_today 
                            AND pp.`payment_status` != :status";
        $stmtParams = array(
           'patient_id' => $patientId,
           'billing_id' => $billingId,
           'month_today' => $m,
           'status' => PatientPaymentEntity::PAYMENT_STATUS_VOID,
        );

        $sql = "
            SELECT
                pp.`id`,
                pat.`id` AS patientId,
                pp.`pay_type`,
                pat.`full_name` AS patientName,
                DATE_FORMAT(pp.`pay_date`, '%m/%d/%Y') pay_date,
                pp.`amount`,
                pp.`bill_due_amount`,
                pp.`bill_paid_amount`,
                pp.`bill_bal_amount`,
                pp.`note`,
                pp.`payment_status`,
                fc.`description` AS financingCompany,
                pb.`health_facility_id` AS patientBillingBranchId
            FROM `patient_payment` pp
            LEFT JOIN `patient` pat ON pp.`patient_id` = pat.`id`
            LEFT JOIN `patient_billing` pb ON pp.`patient_billing_id` = pb.`id`
            LEFT JOIN `financing_company` fc ON pp.`financing_company_id` = fc.`id`
            $sqlWhere
            ORDER BY pp.`pay_date` DESC
        ";

        $query = $this->getEntityManager()->getConnection()->prepare($sql);
        $query->execute($stmtParams);

        $result = $query->fetchAll();

        return $result;
    }

    public function autocomplete_suggestions($q)
    {
        $sql = "
            SELECT
                pb.`id`,
                CONCAT_WS(' - ', pb.`invoice_no`, DATE_FORMAT(pp.`pay_date`, '%Y/%m/%d'), pp.`amount`) AS data,
                CONCAT_WS(' - ', pb.`invoice_no`, DATE_FORMAT(pp.`pay_date`, '%Y/%m/%d'), pp.`amount`) AS value,
                pb.`billing_status` AS billingStatus,
                pp.`amount` AS amountDue
            FROM `patient_payment` pp
            LEFT JOIN `patient_billing` pb ON pp.`patient_billing_id` = pb.`id`
            WHERE pb.`invoice_no` LIKE :description
            AND pb.`is_deleted` = 0
            AND (pb.`invoice_no` IS NOT NULL OR pb.`invoice_no` != '')
            ORDER BY pb.`invoice_no`
            LIMIT 0,20
        ";

        $query = $this->getEntityManager()->getConnection()->prepare($sql);

        $query->execute(array(
            'description' => "%$q%"
        ));

        $result = $query->fetchAll();

        return $result;
    }
}
