<?php

namespace RxConnexionBundle\Repository;

use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Query\Expr;
use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToStringTransformer;
use RxConnexionBundle\Entity\TransferInventoryEntity;

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

        $errors = array();

        $action = $transferInventoryItem_form['action'];

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

            if(empty($transferInventoryItem_form['transferInventory_id']))
                $errors[] = 'Please select consume supply.';

            if(empty($transferInventoryItem_form['inventory_id']))
                $errors[] = 'Please enter item.';

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

            if(!count($errors)) {
                $inventory = $this->getEntityManager()->getRepository('RxConnexionBundle:InventoryEntity')->find($transferInventoryItem_form['inventory_id']);
                if(floatval($inventory->getQuantity()) < floatval(str_replace(',', '', $transferInventoryItem_form['quantity'])))
                    $errors[] = 'Available quantity for the entered item is only ' . $inventory->getQuantity();
            }
        }

        return $errors;
    }

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

        $columns = array(
            'ei.description',
            //'l.description',
            'iuii.quantityRequested',
            'iuii.quantity',
            'iuii.quantityDelivered',
            'iuii.quantityReceived',
            'iuii.note',
            'iuii.isConsumable',
            'iuii.id'
        );
        $dtColumns = array(
            'ei.description as item_description',
            //'l.description as location_description',
            'iuii.quantityRequested',
            'iuii.quantity',
            'iuii.quantityDelivered',
            'iuii.quantityReceived',
            'iuii.note',
            'iuii.isConsumable',
            'iuii.id'
        );
        $dbColumns = array('iui.status as transferInventory_status');
        $asColumns = array();

        $query = $this->getEntityManager()
            ->getRepository('RxConnexionBundle:TransferInventoryItemEntity')
            ->createQueryBuilder('iuii')
            ->leftJoin('iuii.transferInventory', 'iui')
            ->leftJoin('iuii.inventory', 'ii')
            ->leftJoin('iuii.item', 'ei')
            //->leftJoin('ii.location', 'l')
            ->select(array_merge($dtColumns, $dbColumns))
            ->where('iuii.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 Update', $userData['accesses']);

        foreach($result as $row) {

            $id = base64_encode($row['id']);
            $idNotEncoded = $row['id'];
            $quantity = number_format($row['quantity'], 0);
            $quantityRequested = number_format($row['quantityRequested'], 0);
            $consumable = $row['isConsumable'] == 1 ? 'checked' : '';
            $note = $row['note'];
            $values = array(
                $row['item_description'],
                //$row['location_description'],
                number_format($row['quantityRequested'], 0), #$row['transferInventory_status'] != TransferInventoryEntity::STATUS_NEW ? number_format($row['quantityRequested'], 0) : "<input type='text'  name='$idNotEncoded-qtyReq' data-qtyReq='$quantityRequested' value=$quantityRequested>",
                '',
                number_format($row['quantity'], 0), #$row['transferInventory_status'] != TransferInventoryEntity::STATUS_NEW ? number_format($row['quantity'], 0) : "<input type='text' name='$idNotEncoded-qty' data-qty='$quantity' value=$quantity>",
//                "<span class='transferInventoryItem-approvedQuantity-span'>$quantity</span><div class='input-group'><input class='input-group-field' type='number'><div class='input-group-button'><input type='submit' class='button' value='Submit'></div></div><input type='text' class='transferInventoryItem-approvedQuantity-txt numeric' data-id='$id' value='$quantity'><button><i class='fa fa-check'></i></button>",
                number_format($row['quantityDelivered'], 0),
                number_format($row['quantityReceived'], 0),
                $row['transferInventory_status'] != TransferInventoryEntity::STATUS_NEW ? $row['note'] : "<textarea data-note='$note' name='$idNotEncoded-note'>$note</textarea>",
                $row['transferInventory_status'] != TransferInventoryEntity::STATUS_NEW ? ($row['isConsumable'] == 1 ? 'Yes' : '-') : "<input type='checkbox' name='$idNotEncoded-consumable' data-consumable='$consumable' $consumable>",
                //$hasUpdate && ($row['transferInventory_status'] === 'New' || $row['transferInventory_status'] === 'Rejected') ? "<a href='javascript:void(0)' class='action-button-style href-transferInventoryItem-form' data-action='u' data-id='$id'>Update</a>" : ""
                $hasUpdate && ($row['transferInventory_status'] === 'New' || $row['transferInventory_status'] === 'Rejected') ? "<a href='javascript:void(0)' class='action-button-style href-transferInventoryItem-remove' data-id='" . $id . "'>Remove</a>" : "",
                array('DT_RowData' => array(
                    'quantity' => $quantity,
                    'id'       => $id
                ))
            );

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

        unset($result);

        return $output;
    }
    public function ajax_list(array $get, $userData){
        $columns = array(
            array("ei.description", "ei.`description`", 'item_description'),
            array("iuii.quantity_requested", "iuii.quantity_requested", 'quantityRequested'),
            array("iuii.quantity", "iuii.quantity", 'quantity'),
            array("iuii.quantity_delivered", "iuii.quantity_delivered", 'quantityDelivered'),
            array("iuii.quantity_received", "iuii.quantity_received", 'quantityReceived'),
            array("iuii.note", "iuii.note", 'note'),
            array("iuii.is_consumable", "iuii.is_consumable", 'isConsumable'),
            array("iuii.id", "iuii.id"),
            array("tiiisn.serialNos_only", "tiiisn.serialNos_only"),
            array("iui.status", "iui.status", 'transferInventory_status'),
        );
        $asColumns = array();

        $select = "SELECT";
        $from = "FROM `transfer_inventory_item` iuii";
        $joins = "LEFT JOIN `transfer_inventory` iui ON iuii.`transfer_inventory_id` = iui.`id`";
        $joins .= " LEFT JOIN `inventory` ii ON iuii.`inventory_id` = ii.`id`";
        $joins .= " LEFT JOIN `item` ei ON iuii.`item_id` = ei.`id`";
        $joins .= " LEFT JOIN (
              SELECT 
                GROUP_CONCAT(CONCAT(tiiisn.id, '~', inv_so.serial_no) ORDER BY CAST(inv_so.serial_no AS INTEGER) ASC) AS serialNos,
                GROUP_CONCAT(inv_so.serial_no ORDER BY CAST(inv_so.serial_no AS INTEGER) ASC SEPARATOR '<br>') AS serialNos_only,
                tiiisn.transfer_inventory_item_id
              FROM transfer_inventory_item_inventory_serial_no tiiisn
              LEFT JOIN inventory_serial_no inv_so ON tiiisn.inventory_serial_no_id = inv_so.id
              GROUP BY tiiisn.transfer_inventory_item_id
            ) tiiisn ON iuii.id = tiiisn.transfer_inventory_item_id";
        $sqlWhere = " WHERE iuii.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'];
        }

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

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

        foreach($result as $row) {

            $id = base64_encode($row['id']);
            $idNotEncoded = $row['id'];
            $quantity = number_format($row['quantity'], 0);
            $quantityRequested = number_format($row['quantityRequested'], 0);
            $consumable = $row['isConsumable'] == 1 ? 'checked' : '';
            $note = $row['note'];
            $values = array(
                $row['item_description'],
                //$row['location_description'],
                number_format($row['quantityRequested'], 0), #$row['transferInventory_status'] != TransferInventoryEntity::STATUS_NEW ? number_format($row['quantityRequested'], 0) : "<input type='text'  name='$idNotEncoded-qtyReq' data-qtyReq='$quantityRequested' value=$quantityRequested>",
                $row['serialNos_only'],
                number_format($row['quantity'], 0), #$row['transferInventory_status'] != TransferInventoryEntity::STATUS_NEW ? number_format($row['quantity'], 0) : "<input type='text' name='$idNotEncoded-qty' data-qty='$quantity' value=$quantity>",
//                "<span class='transferInventoryItem-approvedQuantity-span'>$quantity</span><div class='input-group'><input class='input-group-field' type='number'><div class='input-group-button'><input type='submit' class='button' value='Submit'></div></div><input type='text' class='transferInventoryItem-approvedQuantity-txt numeric' data-id='$id' value='$quantity'><button><i class='fa fa-check'></i></button>",
                number_format($row['quantityDelivered'], 0),
                number_format($row['quantityReceived'], 0),
                $row['note'], #$row['transferInventory_status'] != TransferInventoryEntity::STATUS_NEW ? $row['note'] : "<textarea data-note='$note' name='$idNotEncoded-note'>$note</textarea>",
                $row['transferInventory_status'] != TransferInventoryEntity::STATUS_NEW ? ($row['isConsumable'] == 1 ? 'Yes' : '-') : "<input type='checkbox' name='$idNotEncoded-consumable' data-consumable='$consumable' $consumable>",
                //$hasUpdate && ($row['transferInventory_status'] === 'New' || $row['transferInventory_status'] === 'Rejected') ? "<a href='javascript:void(0)' class='action-button-style href-transferInventoryItem-form' data-action='u' data-id='$id'>Update</a>" : ""
                $hasUpdate && ($row['transferInventory_status'] === 'New' || $row['transferInventory_status'] === 'Rejected') ? "<a href='javascript:void(0)' class='action-button-style href-transferInventoryItem-remove' data-id='" . $id . "'>Remove</a>" : "",
                array('DT_RowData' => array(
                    'quantity' => $quantity,
                    'id'       => $id
                ))
            );

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

        unset($result);

        return $output;
    }

    public function projectManagementInventoryItems($projectManagement_id){
        $stmtParams = array();

        $sql = "
            SELECT tii.`id`        as transferInventory_id,
                   i.`description` as item_desc,
                   ium.description as item_unit,
                   tii.`quantity`  as qtyRequested,
                   tii.`note`,
                   tii.`is_consumable`
            FROM `transfer_inventory_item` tii
            LEFT JOIN `transfer_inventory` ti on tii.`transfer_inventory_id` = ti.`id`
            LEFT JOIN `item` i ON tii.`item_id` = i.`id`
            LEFT JOIN `item_unit_measurement` ium ON ium.`id` = (SELECT iumt.`id`
                FROM `item_unit_measurement` iumt
                WHERE iumt.`id` = i.`id`
                LIMIT 1
            )
            WHERE EXISTS(SELECT pmti.`id`
                         FROM `project_management_transfer_inventory` pmti
                         WHERE pmti.`project_management_id` = :pmId
                           AND (pmti.`transfer_inventory_id_ingress` = tii.`transfer_inventory_id`));
        ";
        $stmtParams['pmId'] = $projectManagement_id;

        $stmt = $this->getEntityManager()->getConnection()->prepare($sql);
        $stmt->execute($stmtParams);
        $result = $stmt->fetchAll();
        return $result;
    }
}
