<?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['city']) && $params['city'] !== 'NULL' && $params['city'] !== 'all' && !empty($params['city']) && is_numeric($params['city'])) {
            $sqlWhere .= (empty($sqlWhere) ? "WHERE " : " AND ") . "pat.`city_id` = :city";
            $stmtParams['city'] = $params['city'];
        }

        if ($params['status'] == 'active') {
            $sqlWhere .= ' AND pat.`is_active` = 1';
        }

        if ($params['status'] == 'inactive') {
            $sqlWhere .= ' AND pat.`is_active` = 0';
        }

//        if (isset($params['no_email']) && $params['no_email'] != 'NULL') {
//            $sqlWhere .= ' AND pat.`email` IS NULL';
//        }
//
//        if (isset($params['no_contact_no']) && $params['no_contact_no'] != 'NULL') {
//            $sqlWhere .= ' AND pat.`phone_no` IS NULL';
//        }
//
//        if (isset($params['no_mobile_no']) &&$params['no_mobile_no'] != 'NULL') {
//            $sqlWhere .= ' AND pat.`mobile_no` IS NULL';
//        }

        $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 `city` c ON c.`id` = pat.`city_id`
            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.`start_date` <= :now
                      AND (prhf.`end_date` IS NULL OR prhf.`end_date` > :now)
            ) 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.`start_date` <= :now
                      AND (prp.`end_date` IS NULL OR prp.`end_date` > :now)
            ) temp_prp ON temp_prp.`patientId` = pat.`id`
            $sqlWhere
            AND (pat.`is_deleted` = 0 OR pat.`is_deleted` IS NOT NULL)
            AND (pat.`is_not_count_as_referral` = 0 OR pat.`is_not_count_as_referral` IS NULL)
            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
            ORDER BY rhf.`description` ASC
        ";

        $stmtParams['now'] = date('Y-m-d');

        $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' => isset($referringProvider[1]) ? $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;
    }
}
