<?php

namespace RxConnexionBundle\Repository;

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

        $errors = array();

        /*$action = $healthFacility_form['action'];

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

            $healthFacilityExist = $this->getEntityManager()->getRepository('RxConnexionBundle:HealthFacilityEntity')
                ->createQueryBuilder('ep')
                ->where('ep.id != :id')
                ->andWhere('ep.description = :description')
                ->andWhere('ep.account = :account')
                ->setParameters(array(
                    'id' => $healthFacility_form['id'],
                    'description' => $healthFacility_form['description'],
                    'account' => $healthFacility_form['account']
                ))
                ->getQuery()->getResult();

            if($healthFacilityExist)
                $errors[] = 'Description already exist.';

            if(empty($healthFacility_form['description']))
                $errors[] = 'Description 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('hf.`id`', "hf.`id`")
        );
        $asColumns = array();

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

        if($get['status'] != 'All'){
            //$sqlWhere .= (empty($sqlWhere) ? "WHERE " : " AND ") . " hf.`is_active` = :status";

            if($get['status'] == '0') {
                $sqlWhere .= " AND (hf.`is_active` = :status OR hf.`is_active` IS NULL)";
            }

            if($get['status'] == '1') {
                $sqlWhere .= " AND hf.`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('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('hf.`id`', "hf.`id`"),
            array('hf.`street`', "hf.`street`"),
            array('hf.`city_id`', "hf.`city_id`"),
            array('c.`description`', "c.`description`", 'city_desc'),
            array('hf.`phone_no`', 'hf.`phone_no`'),
            array('hf.`fax_no`', 'hf.`fax_no`')
        );
        $asColumns = array();

        $select = "SELECT";
        $from = "FROM `referring_health_facility` hf";
        $joins = "LEFT JOIN `city` c ON hf.`city_id` = c.`id`";
        $sqlWhere = "WHERE hf.`is_deleted` = 0";
        $sqlWhere .= " AND hf.`is_active` = 1";
        $groupBy = "";
        $orderBy = "";
        $limit = "";
        $stmtParams = array();
        /*if(isset($get['referringProvider_id']) && $get['referringProvider_id'] != ''){
            $sqlWhere .= "WHERE hf.`id` IN (
                        SELECT rhfp.`referring_health_facility_id`
                        FROM `referring_health_facility_provider` rhfp
                        WHERE rhfp.`referring_provider_id` = :referringProvider_id
                        GROUP BY rhfp.`referring_health_facility_id`
        )";
            $stmtParams['referringProvider_id'] = $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) {

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

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

        $query->execute(array(
            'description' => "%$q%"
        ));

        $result = $query->fetchAll();

        return $result;
    }

    public function referringHealthFacilityForMultiple() {

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

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

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

        return $result;
    }
}
