<?php

namespace RxConnexionBundle\Repository;

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

        $errors = array();

        $action = $referringHealthFacilitySalesAgent_form['action'];

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

            $referringHealthFacilitySalesAgentExist = $this->getEntityManager()->getRepository('RxConnexionBundle:SalesAgentReferringHealthFacilityEntity')
                ->createQueryBuilder('ep')
                ->where('ep.id != :id')
                ->andWhere('ep.salesAgent = :salesAgent_id')
                ->andWhere('ep.referringHealthFacility = :referringHealthFacility_id')
                ->andWhere('ep.isDeleted = 0')
                ->setParameters(array(
                    'id' => $referringHealthFacilitySalesAgent_form['id'],
                    'referringHealthFacility_id' => base64_decode($referringHealthFacilitySalesAgent_form['referringHealthFacility']),
                    'salesAgent_id' => $referringHealthFacilitySalesAgent_form['salesAgent']
                ))
                ->getQuery()->getResult();

            if($referringHealthFacilitySalesAgentExist)
                $errors[] = 'Referring Sales Agent already exist.';

            if(empty($referringHealthFacilitySalesAgent_form['referringHealthFacility']))
                $errors[] = 'Referring affiliate should not be blank.';

            if(empty($referringHealthFacilitySalesAgent_form['start_date']))
                $errors[] = 'Start date should not be blank.';
        }

        return $errors;
    }
    public function ajax_list(array $get){
        $columns = array(
            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('srhf.`start_date`', "DATE_FORMAT(srhf.`start_date`, '%m/%d/%Y')", 'startDate'),
            array('srhf.`end_date`', "DATE_FORMAT(srhf.`end_date`, '%m/%d/%Y')", 'endDate'),
            array('srhf.`sales_agent_id`', 'srhf.`sales_agent_id`'),
            array('srhf.`id`', 'srhf.`id`')
        );
        $asColumns = array();

        $select = "SELECT";
        $from = "FROM `sales_agent_referring_health_facility` srhf";
        $joins = "LEFT JOIN `referring_health_facility` hf ON srhf.`referring_health_facility_id` = hf.`id` ";
        $sqlWhere = "WHERE srhf.`sales_agent_id` = :salesAgent_id";
        $sqlWhere .= " AND srhf.`is_deleted` = 0";
        $groupBy = "";
        $orderBy = "";
        $limit = "";
        $stmtParams = array(
            'salesAgent_id' => base64_decode($get['salesAgent_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;
    }
}
