<?php

namespace RxConnexionBundle\Repository;

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

        $errors = array();

        $action = $referringProviderHealthFacility_form['action'];

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

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

            if($referringProviderHealthFacilityExist)
                $errors[] = 'Referring medical facility already exist.';

            if(empty($referringProviderHealthFacility_form['referringHealthFacility_desc']))
                $errors[] = 'Referring medical facility should not be blank.';
        }

        return $errors;
    }
    public function ajax_list(array $get){
        $columns = array(
            array('hf.`company_description`', 'hf.`company_description`'),
            array('hf.`branch_description`', 'hf.`branch_description`'),
            array('hf.`description`', 'hf.`description`'),
            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_provider_health_facility` phf";
        $joins = "LEFT JOIN `referring_health_facility` hf ON phf.`referring_health_facility_id` = hf.`id` ";
        $sqlWhere = "WHERE phf.`referring_provider_id` = :referringProvider_id";
        $sqlWhere .= " AND phf.`is_deleted` = 0";
        $groupBy = "";
        $orderBy = "";
        $limit = "";
        $stmtParams = array(
            'referringProvider_id' => base64_decode($get['referringProvider_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_provider_health_facility` 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;
    }
}
