<?php

namespace RxConnexionBundle\Repository;

/**
 * ItemItemRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class ItemItemRepository extends \Doctrine\ORM\EntityRepository
{

    public function validate($form)
    {
        $errors = array();

        $action = $form['action'];

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

            $exists = $this->createQueryBuilder('ii')
                ->where('ii.id != :id')
                ->andWhere('ii.mainItem = :mainItem')
                ->andWhere('ii.item = :item')
                ->setParameters(array(
                    'id' => $form['id'],
                    'mainItem' => $form['mainItem'],
                    'item' => $form['item'],
                ))
                ->getQuery()->getResult();

            if($exists)
                $errors[] = 'Item already exist.';

            if(empty($form['item_description']))
                $errors[] = 'Item should not be blank.';

        }

        return $errors;
    }

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

        $conn = $this->getEntityManager()->getConnection();

        $columns = array(
            array('i.`description`', 'i.`description`'),
            array('ii.`id`', "ii.`id`")
        );
        $asColumns = array();
        $select = "SELECT";
        $from = "FROM `item_item` ii";
        $joins = " INNER JOIN item i ON ii.item_id = i.id";
        $sqlWhere = "WHERE ii.`main_item_id` = :item_id";
        $groupBy = "";
        $orderBy = "";
        $limit = "";
        $stmtParams = array(
            'item_id' => base64_decode($get['item_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 = $conn->prepare($sql);
        $query->execute($stmtParams);
        $result_count = $query->fetchAll();

        $sql = "$select $from $joins $sqlWhere $groupBy $orderBy $limit";
        $query = $conn->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()
        );

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

        foreach($result as $key => $row) {

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

            if($hasUpdate) {
                $action .= "<a class='action-button-style href-new-item' data-action='u' data-id='$id'>Update</a>";
            }

            $values = array(
                $row['description'],
                $action
            );

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

        unset($result);

        return $output;
    }
}
