<?php

namespace RxConnexionBundle\Repository;

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

        $errors = array();

        $action = $referringProvider_form['action'];

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

            /*    $referringProviderExist = $this->getEntityManager()->getRepository('RxConnexionBundle:ReferringProviderEntity')
                    ->createQueryBuilder('ep')
                    ->where('ep.id != :id')
                    ->andWhere('ep.description = :description')
                    ->setParameters(array(
                        'id' => $referringProvider_form['id'],
                        'description' => $referringProvider_form['description']
                    ))
                    ->getQuery()->getResult();
    
                if($referringProviderExist)
                    $errors[] = 'Description already exist.';*/

            /*if(empty($referringProvider_form['description']))
                $errors[] = 'Description should not be blank.';*/
        }

        return $errors;
    }

    public function ajax_list(array $get){

        $columns = array(
            array('p.`full_name`', 'p.`full_name`'),
            array('p.`address`', 'p.`address`'),
            array("CONCAT_WS('<br />', p.`phone_no`, p.`phone_no_two`)", "CONCAT_WS('<br />', p.`phone_no`, p.`phone_no_two`)", 'phoneNos'),
            array("CONCAT_WS('<br />', p.`mobile_no`, p.`mobile_no_two`)", "CONCAT_WS('<br />', p.`mobile_no`, p.`mobile_no_two`)", 'mobileNos'),
            array("CONCAT_WS('<br />', p.`email`, p.`email_two`)", "CONCAT_WS('<br />', p.`email`, p.`email_two`)", 'emails'),
            array('p.`id`', "p.`id`")
        );
        $asColumns = array();

        $select = "SELECT";
        $from = "FROM `referring_provider` p";
        $joins = "";
        $sqlWhere = "WHERE p.`is_deleted` = 0";
        $groupBy = "";
        $orderBy = "";
        $limit = "";
        $stmtParams = array();

        if($get['status'] != 'All'){
            $sqlWhere .= (empty($sqlWhere) ? "WHERE " : " AND ") . " p.`is_active` = :status";
            $stmtParams['status'] = $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'];
        }

        $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 ajax_list_for_referral_form(array $get){

        $columns = array(
            array('p.`full_name`', 'p.`full_name`'),
            array('p.`address`', 'p.`address`'),
            array("CONCAT_WS('<br />', p.`phone_no`, p.`phone_no_two`)", "CONCAT_WS('<br />', p.`phone_no`, p.`phone_no_two`)", 'phoneNos'),
            array("CONCAT_WS('<br />', p.`mobile_no`, p.`mobile_no_two`)", "CONCAT_WS('<br />', p.`mobile_no`, p.`mobile_no_two`)", 'mobileNos'),
            array("CONCAT_WS('<br />', p.`email`, p.`email_two`)", "CONCAT_WS('<br />', p.`email`, p.`email_two`)", 'emails'),
            array('p.`id`', "p.`id`"),
            array('p.`first_name`', "p.`first_name`"),
            array('p.`middle_name`', "p.`middle_name`"),
            array('p.`last_name`', "p.`last_name`"),
            array('p.`gender`', "p.`gender`"),
            array('p.`street`', "p.`street`"),
            array('p.`city_id`', "p.`city_id`"),
            array('c.`description`', "c.`description`", 'city_desc')
        );
        $asColumns = array();

        $select = "SELECT";
        $from = "FROM `referring_provider` p";
        $joins = "LEFT JOIN `city` c ON p.`city_id` = c.`id`";
        $sqlWhere = "WHERE p.`is_deleted` = 0";
        $sqlWhere .= " AND p.`is_active` = 1";
        $groupBy = "";
        $orderBy = "";
        $limit = "";
        $stmtParams = array();

        /*if(isset($get['referringHealthFacility_id']) && $get['referringHealthFacility_id'] != ''){
            $sqlWhere .= "WHERE p.`id` IN (
                        SELECT rhfp.`referring_provider_id`
                        FROM `referring_health_facility_provider` rhfp
                        WHERE rhfp.`referring_health_facility_id` = :referringHealthFacility_id
                        GROUP BY rhfp.`referring_provider_id`
        )";
            $stmtParams['referringHealthFacility_id'] = $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) {
        $andWhere = '';
        $params = array(
            'description' => "%$q%"
        );

        $sql = "
            SELECT
                p.`id`,
                p.`fax_no`,
                p.`full_name` AS data,
                p.`full_name` AS value
            FROM `referring_provider` p
            WHERE p.`full_name` LIKE :description
            AND p.`is_deleted` = 0
            AND p.`is_active` = 1
            $andWhere
            ORDER BY p.`full_name`
            LIMIT 0,20
        ";

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

        $query->execute($params);

        $result = $query->fetchAll();

        return $result;
    }

    public function referringProviderForMultiple() {

        $sql = "
            SELECT
                ct.`id`,
                ct.`full_name`
            FROM `referring_provider` ct
            WHERE ct.`is_deleted` = 0
            AND ct.`is_active` = 1
            ORDER BY ct.`full_name` ASC
        ";

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

        $query->execute();
        $result = $query->fetchAll();

        return $result;
    }
}
