<?php

namespace RxConnexionBundle\Repository;

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

        $errors = array();

        $action = $postalCode_form['action'];

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

            $postalCodeExist = $this->getEntityManager()->getRepository('RxConnexionBundle:PostalCodeEntity')
                ->createQueryBuilder('ep')
                ->where('ep.id != :id')
                ->andWhere('ep.description = :description')
                ->andWhere('ep.city = :city_id')
                ->andWhere('ep.isDeleted = 0')
                ->setParameters(array(
                    'id' => $postalCode_form['id'],
                    'description' => $postalCode_form['description'],
                    'city_id' => $postalCode_form['city']
                ))
                ->getQuery()->getResult();

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

            if(empty($postalCode_form['description']))
                $errors[] = 'Description should not be blank.';

            if(empty($postalCode_form['city']))
                $errors[] = 'Province should not be blank.';
        }

        return $errors;
    }

    public function ajax_list(array $get){

        $columns = array(
            array('p.`description`', 'p.`description`', 'city_desc'),
            array('c.`code`', 'c.`code`'),
            array('c.`description`', 'c.`description`'),
            array('c.`id`', "c.`id`")
        );
        $asColumns = array();

        $selectCount = "SELECT COUNT(DISTINCT c.`id`) AS cnt";
        $select = "SELECT";
        $from = "FROM `postal_code` c";
        $joins = "LEFT JOIN `city` p ON c.`city_id` = p.`id`";
        $sqlWhere = "WHERE c.`is_deleted` = 0";
        $groupBy = "";
        $orderBy = "";
        $limit = "";
        $stmtParams = array();

        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'];
        }

        $conn = $this->getEntityManager()->getConnection();
        $sql = "$selectCount $from $joins $sqlWhere $groupBy";
        $query = $conn->prepare($sql);
        $query->execute($stmtParams);
        $result_count = $query->rowCount() ? $query->fetch(0)['cnt'] : 0;

        $sql = "$select $from $joins $sqlWhere $groupBy $orderBy $limit";
        $query = $conn->prepare($sql);
        $query->execute($stmtParams);
        $result = $query->fetchAll();

        return array(
            'results' => $result,
            'total' => $result_count
        );
    }

    public function autocomplete_suggestions($q, $city_id) {

        $params = array(
            'description' => "%$q%"
        );
        $andWhere = '';
        if(isset($city_id) && $city_id != ''){
            $andWhere .= " AND c.`city_id` = :city_id";
            $params['city_id'] = $city_id;
        }
        $sql = "
            SELECT
                c.`id`,
                p.`description` AS city,
                p.`id` AS cityId,
                CONCAT_WS(' - ', c.`description`, p.`description`) AS data,
                CONCAT_WS(' - ', c.`description`, p.`description`) AS value
            FROM `postal_code` c
            LEFT JOIN `city` p ON c.`city_id` = p.`id`
            WHERE c.`is_deleted` = 0
            AND c.`description` LIKE :description
            $andWhere
            ORDER BY c.`description`
            LIMIT 0,20
        ";

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

        $query->execute($params);

        $result = $query->fetchAll();

        return $result;
    }

    public function autocomplete_suggestions_for_map($q, $city_id) {

        $conn = $this->getEntityManager()->getConnection();
        $stmt = $conn->prepare("
            
            CREATE TEMPORARY TABLE IF NOT EXISTS `patient_temp`
            (INDEX pt_index_temp (`postal_code_id`))
             AS (
              SELECT
                   GROUP_CONCAT(CONCAT_WS(';', p.`id`, CONCAT_WS(' ', p.`first_name`, p.`middle_name`, p.`last_name`), p.`address`, p.`geo_lat`, p.`geo_long`) SEPARATOR '|') AS patientDetails,
                   p.`postal_code_id`
                   FROM `patient` p
                   WHERE p.`is_deleted` = 0
              GROUP BY p.`postal_code_id`
            );
            
        ");
        $stmt->execute();

        $params = array(
            'description' => "%$q%"
        );
        $andWhere = '';
        if(isset($city_id) && $city_id != ''){
            $andWhere .= " AND c.`city_id` = :city_id";
            $params['city_id'] = $city_id;
        }

        $sql = $conn->prepare("
            SELECT
                c.`id`,
                pt.patientDetails,
                CONCAT_WS(' - ', c.`description`, p.`description`) AS data,
                CONCAT_WS(' - ', c.`description`, p.`description`) AS value
            FROM `postal_code` c
            LEFT JOIN `city` p ON c.`city_id` = p.`id`
            LEFT JOIN `patient_temp` pt ON c.`id` = pt.`postal_code_id`
            WHERE c.`is_deleted` = 0
            AND c.`description` LIKE :description
            $andWhere
            ORDER BY data
            LIMIT 0,20
        ");

        $sql->execute($params);

        return $sql->fetchAll();
    }
}
