<?php

namespace RxConnexionBundle\Repository;

/**
 * FaxTranRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class FaxTranRepository extends \Doctrine\ORM\EntityRepository
{

    public function validate($faxTran_form) {

        $errors = array();

        $action = $faxTran_form['action'];

        // d = delete
        if($action !== 'd') {
            /*if(empty($faxTran_form['health_facility'])){
                $errors[] = 'Health facility should not be empty';
            }*/
//            if(empty($faxTran_form['fax_category'])){
//                $errors[] = 'Category should not be empty';
//            }
//            if(empty($faxTran_form['fax_status'])){
//                $errors[] = 'Status should not be empty';
//            }
        }

        return $errors;
    }


    public function ajax_list(array $get){

        $columns = array(
            array('f.`fax_date`', "DATE_FORMAT(f.`fax_date`, '%m/%d/%Y %h:%i %p')", 'fax_date'),
            array('f.`remote_id`', 'f.`remote_id`'),
            array('f.`fax_category`', "f.`fax_category`"),
            array('temp_pat.`patient`', "temp_pat.`patient`"),
            array('hf.`description`', "hf.`description`", 'health_facility'),
            array('f.`pages`', "f.`pages`"),
            array('au.`full_name`', 'au.`full_name`', 'assignedTo'),
            array('f.`fax_status`', 'f.`fax_status`'),
            array('f.`id`', 'f.`id`'),
            array('f.`fax_id`', 'f.`fax_id`'),
            array('f.`account_user_id`', 'f.`account_user_id`'),
        );
        $asColumns = array(
            'DATE_FORMAT(f.`fax_date`, \'%m/%d/%Y %h:%i %p\')',
            'CONCAT(ROUND(CAST(f.`size` AS UNSIGNED)/1000,0),"KB")',
        );

        $select = "SELECT";
        $from = "FROM `fax_tran` f";
        $joins = "LEFT JOIN `health_facility` hf ON f.`health_facility_id` = hf.`id`";
        $joins .= " LEFT JOIN `account_user` au ON f.`account_user_id` = au.`id`";
        $joins .= " LEFT JOIN (SELECT
                                    ref.`fax_tran_id` faxTranId,
                                    pat.`full_name` patient
                               FROM `referral` ref
                               LEFT JOIN `fax_tran` ft ON ft.`id` = ref.`fax_tran_id`
                               LEFT JOIN `patient` pat ON pat.`referral_id` = ref.`id`
                    ) temp_pat ON temp_pat.`faxTranId` = f.`id`";
        $sqlWhere = "";
        $groupBy = "";
        $orderBy = "";
        $limit = "";
        $stmtParams = array();

        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'] . "%";
            }
        }
        if($get['month'] != "all"){
            $yearMonth = explode("|",$get['month']);
            $year = $yearMonth[0];
            $month = $yearMonth[1];
            $sqlWhere .= (!empty($sqlWhere) ? ' AND ' : 'WHERE ') . ' YEAR(`fax_date`) = :year AND MONTH(`fax_date`) = :month ';
            $stmtParams['year'] = $year;
            $stmtParams['month'] = $month;
        }
        if($get['status'] != 'all'){
            $sqlWhere .= (!empty($sqlWhere) ? ' AND ' : 'WHERE ') . ' fax_status = :status';
            $stmtParams['status'] = $get['status'];
        }

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

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

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

        return array(
            'results' => $result,
            'total' => count($result_count),
            '$sql' => $sql
        );
    }
    //DASHBOARD
    public function dashboardNewFaxes() {

        $conn = $this->getEntityManager()->getConnection();
        $sql = $conn->prepare(
            "
            SELECT
                ft.`id` AS faxTranId
            FROM `fax_tran` ft
            WHERE ft.`fax_status` = 0
        "
        );
        $sql->execute();
        return $sql->fetchAll();
    }
    public function dashboardNewFaxesCount() {

        $conn = $this->getEntityManager()->getConnection();
        $sql = $conn->prepare(
            "
            SELECT
                COUNT(DISTINCT ft.`id`) AS data
            FROM `fax_tran` ft
            WHERE ft.`fax_status` = 0
        "
        );
        $sql->execute();
        return $sql->rowCount() ? $sql->fetch(0)['data'] : 0;
    }

    public function dashboardWithFaxNoEncounters($params) {
        $conn = $this->getEntityManager()->getConnection();
        $andWhere = '';
        $stmtParams = array();
        if(isset($params['branch']) && $params['branch'][0] != 'All'){
            $ors = "";
            foreach ($params['branch'] as $key => $branch) {
                $ors .= (empty($ors) ? '' : ' OR ').'p.`health_facility_id` = :hf_id'.$key;
                $stmtParams['hf_id'.$key] = $branch;
            }
            $andWhere .= " AND ($ors)";
        }

        if(isset($params['month']) && $params['month'] != '' && $params['month'] != 'All'){
            $month = $params['month'];
            $andWhere .= ' AND MONTH(r.`referral_date`) = :month';
            $stmtParams['month'] = $month;
        }

        if(isset($params['year']) && $params['year'] != '' && $params['year'] != 'All'){
            $year = $params['year'];
            $andWhere .= ' AND YEAR(r.`referral_date`) = :year';
            $stmtParams['year'] = $year;
        }

        $sql = $conn->prepare(
            "
            SELECT
                p.`full_name` AS fullName,
                p.`id` AS patientId,
                hf.`description` as healthFacility,
                DATE_FORMAT(r.`referral_date`, '%m/%d/%Y') AS referralDate,
                CONCAT('[ ' , DATE_FORMAT(pn.`created_at`, '%m/%d/%Y %h:%i %p'), ' - ', pn.`created_by`, ' ] : ', pn.`note`) AS latestNotes,
                IF(DATE_FORMAT(NOW(), '%m/%d/%Y') > DATE_FORMAT(DATE_ADD(pn.`created_at`, INTERVAL 1 DAY), '%m/%d/%Y')   , 'red', NULL) noteInterval
            FROM `patient` p
            LEFT JOIN `referral` r ON p.`referral_id` = r.`id`
            LEFT JOIN `fax_tran` f ON r.`fax_tran_id` = f.`id`
            LEFT JOIN `health_facility` hf ON hf.`id` = p.`health_facility_id` 
            LEFT JOIN (
                  SELECT pn.`id`, pn.`patient_id`, MAX(pn.`created_at`) AS created_at
                  FROM patient_note pn
                  GROUP BY pn.`patient_id`
             ) pnt ON pnt.`patient_id` = p.`id`
             LEFT JOIN (
                  SELECT pn.`note`, pn.`patient_id`, pn.`created_at`, pn.`created_by`
                  FROM patient_note pn
                  GROUP BY pn.`patient_id`, pn.`created_at`
             ) pn ON pn.`patient_id` = p.`id` AND pnt.`created_at` = pn.`created_at`
             LEFT JOIN (
	              SELECT
		          COUNT(DISTINCT pc.`id`) AS chartCtr,
                  ct.`description` AS chartType_desc,
                  pc.`patient_id`
                FROM `patient_chart` pc
                LEFT JOIN `chart_type` ct ON pc.`chart_type_id` = ct.`id`
                GROUP BY pc.`patient_id`
            ) pc ON p.`id` = pc.`patient_id`
            WHERE (p.`id` NOT IN (
              SELECT pc.`patient_id`
              FROM `patient_chart` pc
              LEFT JOIN `chart_type` ct ON pc.`chart_type_id` = ct.`id`
              WHERE pc.`patient_id` = p.`id`
              AND pc.`is_deleted` = 0
              GROUP BY pc.`patient_id`
            ) OR pc.`chartCtr` = 1 AND pc.`chartType_desc` = 'Intro Phone Call')
            AND p.`is_active` = 1
            AND p.`is_deleted` = 0
            $andWhere
            AND r.`fax_tran_id` IS NOT NULL
            AND p.`id` NOT IN (
               SELECT pt.`patient_id`
               FROM `patient_ticket` pt
               LEFT JOIN `patient` pat2 ON pt.`patient_id` = pat2.`id`
               WHERE pat2.`is_active` = 1
               AND pat2.`is_deleted` = 0
             )
            ORDER BY pn.`created_at`, pn.`note`
        "
        );
        $sql->execute($stmtParams);
        return $sql->fetchAll();
    }

    public function dashboardWithFaxNoEncountersSummary($params) {
        $conn = $this->getEntityManager()->getConnection();
        $andWhere = '';
        $stmtParams = array();
        if(isset($params['branch']) && $params['branch'] != 'All'){
            $ors = "";
            foreach ($params['branch'] as $key => $branch) {
                $ors .= (empty($ors) ? '' : ' OR ').'p.`health_facility_id` = :hf_id'.$key;
                $stmtParams['hf_id'.$key] = $branch;
            }
            $andWhere .= " AND ($ors)";
        }

        if(isset($params['month']) && $params['month'] != '' && $params['month'] != 'All'){
            $month = $params['month'];
            $andWhere .= ' AND MONTH(r.`referral_date`) = :month';
            $stmtParams['month'] = $month;
        }

        if(isset($params['year']) && $params['year'] != '' && $params['year'] != 'All'){
            $year = $params['year'];
            $andWhere .= ' AND YEAR(r.`referral_date`) = :year';
            $stmtParams['year'] = $year;
        }

        $sql = $conn->prepare(
            "
            SELECT
				CONCAT_WS(' : ', EXTRACT(YEAR FROM r.`referral_date`), CONVERT(COUNT(EXTRACT(YEAR FROM r.`referral_date`)), INT)) summaryCount
            FROM `patient` p
            LEFT JOIN `referral` r ON p.`referral_id` = r.`id`
            LEFT JOIN `fax_tran` f ON r.`fax_tran_id` = f.`id`
            LEFT JOIN `health_facility` hf ON hf.`id` = p.`health_facility_id` 
            LEFT JOIN (
                  SELECT pn.`id`, pn.`patient_id`, MAX(pn.`created_at`) AS created_at
                  FROM patient_note pn
                  GROUP BY pn.`patient_id`
             ) pnt ON pnt.`patient_id` = p.`id`
             LEFT JOIN (
                  SELECT pn.`note`, pn.`patient_id`, pn.`created_at`, pn.`created_by`
                  FROM patient_note pn
                  GROUP BY pn.`patient_id`, pn.`created_at`
             ) pn ON pn.`patient_id` = p.`id` AND pnt.`created_at` = pn.`created_at`
             LEFT JOIN (
	              SELECT
		          COUNT(DISTINCT pc.`id`) AS chartCtr,
                  ct.`description` AS chartType_desc,
                  pc.`patient_id`
                FROM `patient_chart` pc
                LEFT JOIN `chart_type` ct ON pc.`chart_type_id` = ct.`id`
                GROUP BY pc.`patient_id`
            ) pc ON p.`id` = pc.`patient_id`
            WHERE (p.`id` NOT IN (
              SELECT pc.`patient_id`
              FROM `patient_chart` pc
              LEFT JOIN `chart_type` ct ON pc.`chart_type_id` = ct.`id`
              WHERE pc.`patient_id` = p.`id`
              AND pc.`is_deleted` = 0
              GROUP BY pc.`patient_id`
            ) OR pc.`chartCtr` = 1 AND pc.`chartType_desc` = 'Intro Phone Call')
            AND p.`is_active` = 1
            AND p.`is_deleted` = 0
            $andWhere
            AND r.referral_date IS NOT NULL
            AND r.`fax_tran_id` IS NOT NULL
            AND EXTRACT(YEAR FROM r.`referral_date`) >= '2014'
            AND p.`id` NOT IN (
               SELECT pt.`patient_id`
               FROM `patient_ticket` pt
               LEFT JOIN `patient` pat2 ON pt.`patient_id` = pat2.`id`
               WHERE pat2.`is_active` = 1
               AND pat2.`is_deleted` = 0
             )
            GROUP BY EXTRACT(YEAR FROM r.`referral_date`)
        "
        );
        $sql->execute($stmtParams);
        return $sql->fetchAll();
    }

    public function dashboardWithFaxNoEncountersCount() {
        $conn = $this->getEntityManager()->getConnection();
        $sql = $conn->prepare(
            "
            SELECT
                COUNT(DISTINCT p.`id`) AS data
            FROM `patient` p
            LEFT JOIN `referral` r ON p.`referral_id` = r.`id`
              LEFT JOIN `fax_tran` f ON r.`fax_tran_id` = f.`id`
            WHERE p.`id` NOT IN (
              SELECT pc.`patient_id`
              FROM `patient_chart` pc
              WHERE pc.`patient_id` = p.`id`
              AND pc.`is_deleted` = 0
              GROUP BY pc.`patient_id`
            )
            AND r.`fax_tran_id` IS NOT NULL
            AND p.`is_active` = 1
            AND p.`is_deleted` = 0
        "
        );
        $sql->execute();
        return $sql->rowCount() ? $sql->fetch(0)['data'] : 0;
    }


    //Referral No Encounters
    public function dashboardWithReferralNoEncounters($params) {
        $conn = $this->getEntityManager()->getConnection();
        $andWhere = ' AND p.`is_deleted` = 0';
        $stmtParams = array();
        if(isset($params['branch']) && $params['branch'][0] != 'All'){
            $ors = "";
            foreach ($params['branch'] as $key => $branch) {
                $ors .= (empty($ors) ? '' : ' OR ').'p.`health_facility_id` = :hf_id'.$key;
                $stmtParams['hf_id'.$key] = $branch;
            }
            $andWhere .= " AND ($ors)";
        }

        if(isset($params['month']) && $params['month'] != '' && $params['month'] != 'All'){
            $month = $params['month'];
            $andWhere .= ' AND MONTH(r.`referral_date`) = :month';
            $stmtParams['month'] = $month;
        }

        if(isset($params['year']) && $params['year'] != '' && $params['year'] != 'All'){
            $year = $params['year'];
            $andWhere .= ' AND YEAR(r.`referral_date`) = :year';
            $stmtParams['year'] = $year;
        }

        $sql = $conn->prepare(
            "
            SELECT
                p.`full_name` AS fullName,
                p.`id` AS patientId,
                hf.`description` as healthFacility,
                DATE_FORMAT(r.`referral_date`, '%m/%d/%Y') AS referralDate,
                CONCAT('[ ' , DATE_FORMAT(pn.`created_at`, '%m/%d/%Y %h:%i %p'), ' - ', pn.`created_by`, ' ] : ', pn.`note`) AS latestNotes,
                IF(DATE_FORMAT(NOW(), '%m/%d/%Y') > DATE_FORMAT(DATE_ADD(pn.`created_at`, INTERVAL 1 DAY), '%m/%d/%Y')   , 'red', NULL) noteInterval
            FROM `patient` p
            LEFT JOIN `referral` r ON p.`referral_id` = r.`id`
            LEFT JOIN `fax_tran` f ON r.`fax_tran_id` = f.`id`
            LEFT JOIN `health_facility` hf ON hf.`id` = p.`health_facility_id` 
            LEFT JOIN (
                  SELECT pn.`id`, pn.`patient_id`, MAX(pn.`created_at`) AS created_at
                  FROM patient_note pn
                  GROUP BY pn.`patient_id`
             ) pnt ON pnt.`patient_id` = p.`id`
             LEFT JOIN (
                  SELECT pn.`note`, pn.`patient_id`, pn.`created_at`, pn.`created_by`
                  FROM patient_note pn
                  GROUP BY pn.`patient_id`, pn.`created_at`
             ) pn ON pn.`patient_id` = p.`id` AND pnt.`created_at` = pn.`created_at`
             LEFT JOIN (
	              SELECT
		          COUNT(DISTINCT pc.`id`) AS chartCtr,
                  ct.`description` AS chartType_desc,
                  pc.`patient_id`
                FROM `patient_chart` pc
                LEFT JOIN `chart_type` ct ON pc.`chart_type_id` = ct.`id`
                GROUP BY pc.`patient_id`
            ) pc ON p.`id` = pc.`patient_id`
            WHERE (p.`id` NOT IN (
              SELECT pc.`patient_id`
              FROM `patient_chart` pc
              LEFT JOIN `chart_type` ct ON pc.`chart_type_id` = ct.`id`
              WHERE pc.`patient_id` = p.`id`
              AND pc.`is_deleted` = 0
              GROUP BY pc.`patient_id`
            ) OR pc.`chartCtr` = 1 AND pc.`chartType_desc` = 'Intro Phone Call')
            AND p.`is_active` = 1
            AND p.`is_deleted` = 0
            $andWhere
            AND r.`id` IS NOT NULL
            AND p.`id` NOT IN (
               SELECT pt.`patient_id`
               FROM `patient_ticket` pt
               LEFT JOIN `patient` pat2 ON pt.`patient_id` = pat2.`id`
               WHERE pat2.`is_active` = 1
               AND pat2.`is_deleted` = 0
             )
            ORDER BY pn.`created_at`, pn.`note`
        "
        );
        $sql->execute($stmtParams);
        return $sql->fetchAll();
    }

    public function dashboardWithRefferalNoEncountersSummary($params) {
        $conn = $this->getEntityManager()->getConnection();
        $andWhere = '';
        $stmtParams = array();
        if(isset($params['branch']) && $params['branch'] != 'All'){
            $ors = "";
            foreach ($params['branch'] as $key => $branch) {
                $ors .= (empty($ors) ? '' : ' OR ').'p.`health_facility_id` = :hf_id'.$key;
                $stmtParams['hf_id'.$key] = $branch;
            }
            $andWhere .= " AND ($ors)";
        }

        if(isset($params['month']) && $params['month'] != '' && $params['month'] != 'All'){
            $month = $params['month'];
            $andWhere .= ' AND MONTH(r.`referral_date`) = :month';
            $stmtParams['month'] = $month;
        }

        if(isset($params['year']) && $params['year'] != '' && $params['year'] != 'All'){
            $year = $params['year'];
            $andWhere .= ' AND YEAR(r.`referral_date`) = :year';
            $stmtParams['year'] = $year;
        }

        $sql = $conn->prepare(
            "
            SELECT
				CONCAT_WS(' : ', EXTRACT(YEAR FROM r.`referral_date`), CONVERT(COUNT(EXTRACT(YEAR FROM r.`referral_date`)), INT)) summaryCount
            FROM `patient` p
            LEFT JOIN `referral` r ON p.`referral_id` = r.`id`
            LEFT JOIN `fax_tran` f ON r.`fax_tran_id` = f.`id`
            LEFT JOIN `health_facility` hf ON hf.`id` = p.`health_facility_id` 
            LEFT JOIN (
                  SELECT pn.`id`, pn.`patient_id`, MAX(pn.`created_at`) AS created_at
                  FROM patient_note pn
                  GROUP BY pn.`patient_id`
             ) pnt ON pnt.`patient_id` = p.`id`
             LEFT JOIN (
                  SELECT pn.`note`, pn.`patient_id`, pn.`created_at`, pn.`created_by`
                  FROM patient_note pn
                  GROUP BY pn.`patient_id`, pn.`created_at`
             ) pn ON pn.`patient_id` = p.`id` AND pnt.`created_at` = pn.`created_at`
             LEFT JOIN (
	              SELECT
		          COUNT(DISTINCT pc.`id`) AS chartCtr,
                  ct.`description` AS chartType_desc,
                  pc.`patient_id`
                FROM `patient_chart` pc
                LEFT JOIN `chart_type` ct ON pc.`chart_type_id` = ct.`id`
                GROUP BY pc.`patient_id`
            ) pc ON p.`id` = pc.`patient_id`
            WHERE (p.`id` NOT IN (
              SELECT pc.`patient_id`
              FROM `patient_chart` pc
              LEFT JOIN `chart_type` ct ON pc.`chart_type_id` = ct.`id`
              WHERE pc.`patient_id` = p.`id`
              AND pc.`is_deleted` = 0
              GROUP BY pc.`patient_id`
            ) OR pc.`chartCtr` = 1 AND pc.`chartType_desc` = 'Intro Phone Call')
            AND p.`is_active` = 1
            AND p.`is_deleted` = 0
            $andWhere
            AND r.referral_date IS NOT NULL
            AND r.`id` IS NOT NULL
            AND EXTRACT(YEAR FROM r.`referral_date`) >= '2014'
            AND p.`id` NOT IN (
               SELECT pt.`patient_id`
               FROM `patient_ticket` pt
               LEFT JOIN `patient` pat2 ON pt.`patient_id` = pat2.`id`
               WHERE pat2.`is_active` = 1
               AND pat2.`is_deleted` = 0
             )
            GROUP BY EXTRACT(YEAR FROM r.`referral_date`)
        "
        );
        $sql->execute($stmtParams);
        return $sql->fetchAll();
    }

    public function dashboardWithRefferalNoEncountersCount() {
        $conn = $this->getEntityManager()->getConnection();
        $sql = $conn->prepare(
            "
            SELECT
                COUNT(DISTINCT p.`id`) AS data
            FROM `patient` p
            LEFT JOIN `referral` r ON p.`referral_id` = r.`id`
              LEFT JOIN `fax_tran` f ON r.`fax_tran_id` = f.`id`
            WHERE p.`id` NOT IN (
              SELECT pc.`patient_id`
              FROM `patient_chart` pc
              WHERE pc.`patient_id` = p.`id`
              AND pc.`is_deleted` = 0
              GROUP BY pc.`patient_id`
            )
            AND r.`id` IS NOT NULL
            AND p.`is_active` = 1
            AND p.`is_deleted` = 0
        "
        );
        $sql->execute();
        return $sql->rowCount() ? $sql->fetch(0)['data'] : 0;
    }

    public function reportFax($params) {
        $sqlWhere = "WHERE ft.`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 ") . "ft.`fax_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'])){
            $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['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 ') . "ft.`health_facility_id` = :healthFacility_id_$key";
                    $stmtParams["healthFacility_id_$key"] = $branchId;
                }
                $sqlWhere .= " AND ($hf_ors) ";
            }
        }

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

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

        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 ') . "ft.`health_facility_id` = $branchId";
                        }
                        $sqlWhere .= (empty($andWhere) ? " AND " : "") . " ($hf_ors) ";
                    } else {
                        $sqlWhere .= (empty($andWhere) ? " AND " : "") . " (1 != 1) ";
                    }
                }
            }
        }

        $sql = "SELECT 
                    ft.`id`,
                    DATE_FORMAT(ft.`fax_date`, '%m/%d/%Y') AS faxDate,
                    ft.`fax_category`,
                    ft.`remote_id` AS faxNo,
                    co.`description` AS companyDesc,
                    hf.`description` AS branchDesc,
                    au.`full_name` AS assignTo,
                    ft.`file_name`,
                    ft.`pages`,
                    IF(ft.`is_duplicate` IS TRUE, 'Yes', 'No') AS isDuplicate,
                    IF(ft.`is_existing` IS TRUE, 'Yes', 'No') AS isExisting,
                    IF(ft.`is_unable_to_process` IS TRUE, 'Yes', 'No') AS isUnableToProcess
                FROM `fax_tran` ft
                LEFT JOIN `health_facility` hf ON hf.`id` = ft.`health_facility_id`
                LEFT JOIN `company` co ON hf.`company_id` = co.`id`
                LEFT JOIN `account_user` au ON au.`id` = ft.`account_user_id` 
                $sqlWhere
                AND hf.`description` IS NOT NULL
                AND hf.`description` NOT IN('DemoLocation', 'test', 'Demo_Test')
                ORDER BY ft.`fax_date` DESC
                ";

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

        $query->execute($stmtParams);

        $result = $query->fetchAll();

        return $result;
    }
}
