<?php

namespace RxConnexionBundle\Repository;

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

        $errors = array();

        $action = $location_form['action'];

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

//            $locationExist = $this->getEntityManager()->getRepository('RxConnexionBundle:LocationEntity')
//                ->createQueryBuilder('ep')
//                ->where('ep.id != :id')
//                ->andWhere('ep.description = :description')
//                ->andWhere('ep.branch = :branch_id')
//                ->setParameters(array(
//                    'id' => $location_form['id'],
//                    'description' => $location_form['description'],
//                    'branch_id' => $location_form['branch_id']
//                ))
//                ->getQuery()->getResult();

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

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

            if(empty($location_form['healthFacility']))
                $errors[] = 'Please enter branch.';
        }

        return $errors;
    }

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

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

        $select = "SELECT";
        $from = "FROM `location` c";
        $joins = "LEFT JOIN `health_facility` b ON c.`health_facility_id` = b.`id`";
        $sqlWhere = "";
        $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'];
        }

        $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();

        /* Data Count */
        $recordsTotal = count($result_count);

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

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

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

        foreach($result as $row) {

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

            $values = array(
                $row['branch_desc'],
                $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($get, $userData) {

        $stmtParamas = array('description' => "%{$get['query']}%");
        $andWhere = '';

        if(isset($get['health_facility_id'])) {
            $andWhere .= " AND ep.`health_facility_id` = :health_facility_id";
            $stmtParamas['health_facility_id'] = base64_decode($get['health_facility_id']);
        }

        $sql = "
            SELECT
                ep.`id`,
                CONCAT(ep.`description`, ' - ', b.`description`) AS data,
                CONCAT(ep.`description`, ' - ', b.`description`) AS value,
                b.`id` AS branch_id,
                b.`description` AS branch_description
            FROM `location` ep
            LEFT JOIN `health_facility` b ON ep.`health_facility_id` = b.`id`
            WHERE CONCAT(ep.`description`, ' - ', b.`description`) LIKE :description 
            $andWhere
            ORDER BY ep.`description`
            LIMIT 0,20
        ";
        $query = $this->getEntityManager()->getConnection()->prepare($sql);

        $query->execute($stmtParamas);

        $result = $query->fetchAll();

        return $result;
    }

    public function getAllIdsToArray() {

        $query = $this->getEntityManager()->getConnection()->prepare("
            SELECT l.`id`
            FROM `location` l
        ");
        $query->execute();
        $result = $query->fetchAll();

        $ids = array();

        if(count($result)) {
            foreach($result as $row) {
                $ids[] = $row['id'];
            }
        }

        return $ids;
    }
}
