<?php

namespace RxConnexionBundle\Repository;

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

        $errors = array();

        $action = $bank_form['action'];

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

            $bankExist = $this->getEntityManager()->getRepository('RxConnexionBundle:BankEntity')
                ->createQueryBuilder('eb')
                ->where('eb.id != :id')
                ->andWhere('eb.description = :description')
                ->setParameters(array(
                    'id' => $bank_form['id'],
                    'description' => $bank_form['description']
                ))
                ->getQuery()->getResult();

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

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

        return $errors;
    }

    public function ajax_list(array $get, $userData){

        $columns = array(
            'eb.code',
            'eb.description',
            'eb.id'
        );
        $dtColumns = array(
            'eb.code',
            'eb.description',
            'eb.id'
        );
        $dbColumns = array();
        $asColumns = array();

        $query = $this->getEntityManager()
            ->getRepository('RxConnexionBundle:BankEntity')
            ->createQueryBuilder('eb')
            ->select(array_merge($dtColumns, $dbColumns));

        /*
         * Ordering
         */
        foreach($get['columns'] as $key => $column) {
            if($column['orderable']=='true') {
                if(isSet($get['order'])) {
                    foreach($get['order'] as $order) {
                        if($order['column']==$key) {
                            $query->addOrderBy($columns[$key], $order['dir']);
                        }
                    }
                }
            }
        }

        /*
           * Filtering
           * NOTE this does not match the built-in DataTables filtering which does it
           * word by word on any field. It's possible to do here, but concerned about efficiency
           * on very large tables, and MySQL's regex functionality is very limited
           */
        if ( isset($get['search']) && $get['search']['value'] != '' ){
            $aLike = array();
            $search_value = $get['search']['value'];
            foreach($get['columns'] as $key => $column) {
                if($column['searchable']=='true') {
                    if(!empty($search_value))
                        $aLike[] = $query->expr()->like($columns[$key], '\'%'. $search_value .'%\'');
                }
            }
            foreach($asColumns as $asColumn) {
                $aLike[] = $query->expr()->like($asColumn, '\'%'. $search_value .'%\'');
            }
            if(count($aLike) > 0) $query->andWhere(new Expr\Orx($aLike));
            else unset($aLike);
        }

        $query_count = $query;
        $result_count = $query_count->getQuery()->getArrayResult();

        /* Set Limit and Length */
        if ( isset( $get['start'] ) && $get['length'] != '-1' ){
            $query->setFirstResult( (int)$get['start'] )
                ->setMaxResults( (int)$get['length'] );
        }

        $result = $query->getQuery()->getResult();

        /* Data Count */
        $recordsTotal = count($result_count);
        /* Data set length after filtering */
        $recordsFiltered = count($result);

        unset($result_count);

        /*
         * Output
         */
        $output = array(
            "draw" => intval($get['draw']),
            "recordsTotal" => $recordsTotal,
            "recordsFiltered" => $recordsTotal,
            "data" => array()
        );

        $url = $get['url'];
        $formUrl = $url . 'admin/bank/form';

        $hasUpdate = $userData['type'] === 'Super Admin' ||  in_array('Admin Bank Update', $userData['accesses']);

        foreach($result as $row) {

            $id = base64_encode($row['id']);

            $values = array(
                $row['code'],
                $row['description'],
                $hasUpdate ? "<a class='action-button-style' href='$formUrl/u/$id'>Update</a>" : ""
            );

            $output['data'][] = $values;
        }

        unset($result);

        return $output;
    }

    public function autoCompleteSuggestions($q) {

        $sql = "
            SELECT
                eb.`id`,
                eb.`description` AS data,
                eb.`description` AS value
            FROM `bank` eb
            WHERE eb.`description` LIKE :description
            ORDER BY eb.`description`
            LIMIT 0,20
        ";

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

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

        $result = $query->fetchAll();

        return $result;
    }
}
