<?php

namespace RxConnexionBundle\Repository;

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

        $errors = array();

        $action = $transferInventoryItemDelivery_form['action'];

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

            if(empty($transferInventoryItemDelivery_form['location']))
                //$errors[] = 'Please select location.';

                if(empty($transferInventoryItemDelivery_form['receive_date']))
                    $errors[] = 'Receive date should not be blank.';

            if(empty($transferInventoryItemDelivery_form['quantity']))
                $errors[] = 'Quantity should not be blank.';
            else {

                $transferInventoryItem = $this->getEntityManager()->getRepository('RxConnexionBundle:TransferInventoryItemEntity')->find(base64_decode($transferInventoryItemDelivery_form['transferInventoryItem']));
                $transferInventoryItemDelivery = $this->getEntityManager()->getRepository('RxConnexionBundle:TransferInventoryItemDeliveryEntity')->find($transferInventoryItemDelivery_form['id']);

                if(($transferInventoryItem->getQuantityReceived() - ($transferInventoryItemDelivery ? $transferInventoryItemDelivery->getQuantity() : 0)) + str_replace(',', '', $transferInventoryItemDelivery_form['quantity']) > $transferInventoryItem->getQuantity())
                    $errors[] = 'Item already exceed its required quantity';
            }
        }

        return $errors;
    }

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

        $columns = array(
            'ei.description',
            'l.description',
            'ptid.receiveDate',
            'ptid.quantity',
            'ptid.id',
        );
        $dtColumns = array(
            'ei.description as item_description',
            'l.description as location_description',
            'ptid.receiveDate',
            'ptid.quantity',
            'ptid.id',
        );
        $dbColumns = array('pti.id as transferInventoryItem_id');
        $asColumns = array();

        $query = $this->getEntityManager()
            ->getRepository('RxConnexionBundle:TransferInventoryItemDeliveryEntity')
            ->createQueryBuilder('ptid')
            ->leftJoin('ptid.transferInventoryItem', 'pti')
            ->leftJoin('pti.inventory', 'i')
            ->leftJoin('i.item', 'ei')
            ->leftJoin('ptid.location', 'l')
            ->select(array_merge($dtColumns, $dbColumns))
            ->where('pti.transferInventory = :transferInventory_id')
            ->setParameter('transferInventory_id', base64_decode($get['transferInventory_id']));

        /*
         * 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()
        );

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

        $dateTimeToStringTransformer = new DateTimeToStringTransformer();

        foreach($result as $row) {

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

            $action = '';

            if($hasUpdate)
                $action .= "<a href='javascript:void(0)' class='action-button-style href-transferInventoryItemDelivery-form' data-action='u' data-id='$id' data-ref-id='$transferInventoryItem_id'>Update</a>";

            $values = array(
                $row['item_description'],
                $row['location_description'],
                date('m/d/Y', strtotime($dateTimeToStringTransformer->transform($row['receiveDate']))),
                number_format($row['quantity'], 2),
                $action
            );

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

        unset($result);

        return $output;
    }

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

        $columns = array(
            array('ei.`description`', 'ei.`description`', 'item_description'),
            array('l.`description`', "l.`description`", 'location_description'),
            array('ptid.`receive_date`', "DATE_FORMAT(ptid.`receive_date`, '%m/%d/%Y')", 'receiveDate'),
            array('ptid.`quantity`', 'ptid.`quantity`'),
            array('pti.id', "pti.id", 'transferInventoryItem_id'),
            array('ptid.`id`', "ptid.`id`"),
        );
        $asColumns = array();

        $select = "SELECT";
        $from = "FROM `transfer_inventory_item_delivery` ptid";
        $joins = "
            LEFT JOIN `transfer_inventory_item` pti ON ptid.`transfer_inventory_item_id` = pti.`id`
            LEFT JOIN `item` ei ON pti.`item_id` = ei.`id`
            LEFT JOIN `location` l ON ptid.`location_id` = l.`id`
        ";

        $sqlWhere = "WHERE pti.`transfer_inventory_id` = :transferInventory_id";
        $groupBy = "";
        $orderBy = "";
        $limit = "";
        $stmtParams = array('transferInventory_id' => base64_decode($get['transferInventory_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'];
        }

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

        $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 Transfer Inventory Delivery Update', $userData['accesses']);

        foreach($result as $row) {

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

            $action = '';

            //if(($row['status'] === 'New' || $row['status'] === 'Rejected') && $hasUpdate)
            if($hasUpdate) {
                $action .= "<a href='javascript:void(0)' class='action-button-style href-transferInventoryItemDelivery-form' data-action='u' data-id='$id' data-ref-id='$transferInventoryItem_id'>Update</a>";
            }

            $values = array(
                $row['item_description'],
                $row['receiveDate'],
                $row['quantity'],
                $action,
                //$row['location_description'],
            );

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

        unset($result);

        return $output;
    }
}
