<?php

namespace RxConnexionBundle\Repository;

/**
 * ReferringHealthFacilityProviderRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class ReferringHealthFacilityProviderRepository extends \Doctrine\ORM\EntityRepository
{
    public function validate($referringHealthFacilityProvider_form) {

        $errors = array();

        $action = $referringHealthFacilityProvider_form['action'];

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

            $referringHealthFacilityProviderExist = $this->getEntityManager()->getRepository('RxConnexionBundle:ReferringHealthFacilityProviderEntity')
                ->createQueryBuilder('ep')
                ->where('ep.id != :id')
                ->andWhere('ep.referringProvider = :referringProvider_id')
                ->andWhere('ep.referringHealthFacility = :referringHealthFacility_id')
                ->andWhere('ep.isDeleted = 0')
                ->setParameters(array(
                    'id' => $referringHealthFacilityProvider_form['id'],
                    'referringHealthFacility_id' => base64_decode($referringHealthFacilityProvider_form['referringHealthFacility']),
                    'referringProvider_id' => $referringHealthFacilityProvider_form['referringProvider']
                ))
                ->getQuery()->getResult();

            if($referringHealthFacilityProviderExist)
                $errors[] = 'Referring provider already exist.';

            if(empty($referringHealthFacilityProvider_form['referringProvider_desc']))
                $errors[] = 'Referring provider should not be blank.';
        }

        return $errors;
    }
    public function ajax_list(array $get){
        $columns = array(
            array('hf.`full_name`', 'hf.`full_name`', 'fullName'),
            array('hf.`address`', 'hf.`address`'),
            array("CONCAT_WS('<br />', hf.`phone_no`, hf.`phone_no_two`)", "CONCAT_WS('<br />', hf.`phone_no`, hf.`phone_no_two`)", 'phoneNos'),
            array("CONCAT_WS('<br />', hf.`mobile_no`, hf.`mobile_no_two`)", "CONCAT_WS('<br />', hf.`mobile_no`, hf.`mobile_no_two`)", 'mobileNos'),
            array("CONCAT_WS('<br />', hf.`email`, hf.`email_two`)", "CONCAT_WS('<br />', hf.`email`, hf.`email_two`)", 'emails'),
            array('phf.`start_date`', "DATE_FORMAT(phf.`start_date`, '%m/%d/%Y')", 'startDate'),
            array('phf.`end_date`', "DATE_FORMAT(phf.`end_date`, '%m/%d/%Y')", 'endDate'),
            array('phf.`id`', 'phf.`id`'),
            array('phf.`referring_provider_id`', 'phf.`referring_provider_id`')
        );
        $asColumns = array();

        $select = "SELECT";
        $from = "FROM `referring_health_facility_provider` phf";
        $joins = "LEFT JOIN `referring_provider` hf ON phf.`referring_provider_id` = hf.`id` ";
        $sqlWhere = "WHERE phf.`referring_health_facility_id` = :referringHealthFacility_id";
        $sqlWhere .= " AND phf.`is_deleted` = 0";
        $groupBy = "";
        $orderBy = "";
        $limit = "";
        $stmtParams = array(
            'referringHealthFacility_id' => base64_decode($get['referringHealthFacility_id'])
        );
        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'];
        }

        $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)
        );
    }

    public function autocomplete_suggestions($q, $get) {
        $andWhere = '';
        $params = array(
            'description' => "%$q%"
        );
        if(isset($get['referringProvider_id'])){
            $andWhere .= ' AND rphf.`referring_provider_id` = :referringProvider_id';
            $params['referringProvider_id'] = $get['referringProvider_id'];
        }

        $sql = "
            SELECT
                rphf.`id`,
                rp.`description` AS data,
                rp.`description` AS value
            FROM `referring_health_facility_provider` rphf
            LEFT JOIN `referring_health_facility` rp ON rphf.`referring_health_facility_id` = rp.`id`
            WHERE rp.`description` LIKE :description
            AND rphf.`is_deleted` = 0
            $andWhere
            ORDER BY DATA
            LIMIT 0,20
        ";

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

        $query->execute($params);

        $result = $query->fetchAll();

        return $result;
    }

    public function patientCountProviderReport($params) {

        $stmtParams = array();
        $stmtParams2 = array();
        $sqlWhere = "";
        $sqlWhere2 = "";

        if(!is_null($params['referring_health_facility']) && $params['referring_health_facility'] !== 'NULL' && $params['referring_health_facility'] !== 'all' && !empty($params['referring_health_facility']) && is_numeric($params['referring_health_facility'])) {
            $sqlWhere .= (empty($sqlWhere) ? "WHERE " : " AND ") . "temp_prhf.`rhfId` = :referring_health_facility";
            $stmtParams['referring_health_facility'] = $params['referring_health_facility'];
        }

        if(!is_null($params['referring_health_facility']) && $params['referring_health_facility'] !== 'NULL' && $params['referring_health_facility'] !== 'all' && !empty($params['referring_health_facility']) && is_numeric($params['referring_health_facility'])) {
            $sqlWhere2 .= (empty($sqlWhere2) ? "WHERE " : " AND ") . "rhfp.`referring_health_facility_id` = :referring_health_facility";
            $stmtParams2['referring_health_facility'] = $params['referring_health_facility'];
        }

        $sql1 = "
            SELECT
                temp_prp.`rpId`,
                temp_prhf.`rhfId`,
                temp_prp.`full_name`,
                temp_prhf.`description`,
                COUNT(DISTINCT pat.`id`) patientCount
            FROM `patient` pat
            LEFT JOIN(SELECT
                        rhf.`id` rhfId,
                        pat.`id` patientId,
                        rhf.`description`
                      FROM `patient_referring_health_facility` prhf
                      LEFT JOIN `patient` pat ON pat.`id` = prhf.`patient_id`
                      LEFT JOIN `referring_health_facility` rhf ON rhf.`id` = prhf.`referring_health_facility_id`
                      WHERE (prhf.`end_date` = '0000-00-00 00:00:00' OR prhf.`end_date` IS NULL)
            ) temp_prhf ON temp_prhf.`patientId` = pat.`id`
            LEFT JOIN(SELECT
                        rp.`id` rpId,
                        pat.`id` patientId,
                        rp.`full_name`,
                        rp.`fax_no`,
                        rp.`phone_no`
                      FROM `patient_referring_provider` prp
                      LEFT JOIN `patient` pat ON pat.`id` = prp.`patient_id`
                      LEFT JOIN `referring_provider` rp ON rp.`id` = prp.`referring_provider_id`
                      WHERE (prp.`end_date` = '0000-00-00 00:00:00' OR prp.`end_date` IS NULL)
            ) temp_prp ON temp_prp.`patientId` = pat.`id`
            $sqlWhere
            AND pat.`is_deleted` = 0
            AND temp_prhf.`rhfId` IS NOT NULL
            AND temp_prp.`rpId` IS NOT NULL
            GROUP BY temp_prp.`rpId`
        ";

        $sql2 = "
            SELECT 
                rhf.`id`,
                rhfp.`details`,
                rhf.`description`
            FROM `referring_health_facility` rhf
            LEFT JOIN (
                    SELECT GROUP_CONCAT(CONCAT_WS('~', rp.`id`,rp.`full_name`) SEPARATOR '|') as details,
                            rhfp.`referring_health_facility_id`
                    FROM `referring_health_facility_provider` rhfp
                    LEFT JOIN `referring_provider` rp ON rhfp.`referring_provider_id` = rp.`id`
                    $sqlWhere2
                    AND rhfp.`referring_provider_id` IS NOT NULL
                    GROUP BY rhfp.`referring_health_facility_id`
            ) rhfp ON rhfp.`referring_health_facility_id` = rhf.`id`
            WHERE rhfp.`details` IS NOT NULL
            AND rhf.`id` IS NOT NULL
        ";


        $query1 = $this->getEntityManager()->getConnection()->prepare($sql1);
        $query2 = $this->getEntityManager()->getConnection()->prepare($sql2);
        $query1->execute($stmtParams);
        $query2->execute($stmtParams2);

        $result1 = $query1->fetchAll();
        $result2 = $query2->fetchAll();

        $referringHealthFacilities = array();

        foreach ($result2 as $result) {

            $referringProviders = array();
            $totalArray = array();

            foreach (explode('|', $result['details']) as $row) {
                $referringProvider = explode('~', $row);
                $referringProviders[] = array(
                    'id' => $referringProvider[0],
                    'name' => $referringProvider[1]
                );
            }

            foreach ($result1 as $res) {
                if($result['id'] == $res['rhfId']) {
                    $totalArray[] = array(
                        'id' => $res['rpId'],
                        'count' => $res['patientCount'],
                    );
                }
            }

            $referringHealthFacilities[] = array(
                'id' => $result['id'],
                'description' => $result['description'],
                'referringProviders' => $referringProviders,
                'total' => $totalArray,
            );
        }



        unset($result1);
        unset($result2);

        return $referringHealthFacilities;
    }
}
