<?php

namespace RxConnexionBundle\Repository;

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

        $errors = array();

        $action = $transferInventoryDelivery_form['action'];

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

            if(empty($transferInventoryDelivery_form['transferInventory']))
                $errors[] = 'Something went wrong, please try again. If problem persist please contact the administrator.';

            /*            if(empty($transferInventoryDelivery_form['dr_no']))
                            $errors[] = 'DR no. should not be blank.';*/

            if(empty($transferInventoryDelivery_form['drDate']))
                $errors[] = 'DR date should not be blank.';

            $qtyToDlvr = 0;
            if(isset($other_form['items'])) {
                foreach($other_form['items'] as $idx => $itemForm) {
                    $qty = str_replace(' ', '', str_replace(',', '', $itemForm['qty']));
                    if(!($qty > 0)) {
                        continue;
                    }
                    if($action == 'n'){
                        if((float)$qty > (float)$itemForm['qtyForDelivery']) {
                            $errors[] = 'Qty. to delivery for item ' . $itemForm['itemDesc'] . ' is greater than it\'s remaining quantity for delivery.';
                        } else if((float)$itemForm['qtyOnStock'] < (float)$qty || $itemForm['qtyOnStock'] <= 0) {
                            $errors[] = 'Item ' . $itemForm['itemDesc'] . ' does not have enough stock.';
                        }
                    } else {
                        if((float)$qty > ((float)$itemForm['qtyForDelivery'] + (float)$itemForm['qtyDelivered'])) {
                            $errors[] = 'Qty. to delivery for item ' . $itemForm['itemDesc'] . ' is greater than it\'s quantity requested.';
                        }
                        if((float)$itemForm['qtyOnStock'] < (float)$qty || $itemForm['qtyOnStock'] <= 0) {
                            $errors[] = 'Item ' . $itemForm['itemDesc'] . ' does not have enough stock.';
                        }
                    }
                    $qtyToDlvr += $qty;
                    $other_form['items'][$idx]['qty'] = $qty;
                    $other_form['items'][$idx]['isValid'] = true;
                }
            }
            if(!($qtyToDlvr > 0)) {
                $errors[] = 'Please enter quantities to deliver.';
            }
        }

        return $errors;
    }

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

        $columns = array(
            array(
                "IF(bf.`code` = bt.`code`, CONCAT(DATE_FORMAT(tid.`dr_date`, '%Y.%m.'), LPAD(tid.`dr_no`, 4, 0)), IF(bf.`code` = 'RCC', CONCAT('IN-',DATE_FORMAT(tid.`dr_date`, '%Y.%m.'), LPAD(tid.`dr_no`, 4, 0)), CONCAT('EG-',DATE_FORMAT(tid.`dr_date`, '%Y.%m.'), LPAD(tid.`dr_no`, 4, 0))))",
                "IF(bf.`code` = bt.`code`, CONCAT(DATE_FORMAT(tid.`dr_date`, '%Y.%m.'), LPAD(tid.`dr_no`, 4, 0)), IF(bf.`code` = 'RCC', CONCAT('IN-',DATE_FORMAT(tid.`dr_date`, '%Y.%m.'), LPAD(tid.`dr_no`, 4, 0)), CONCAT('EG-',DATE_FORMAT(tid.`dr_date`, '%Y.%m.'), LPAD(tid.`dr_no`, 4, 0))))", 'drNo'),
            array('tid.`dr_date`', "DATE_FORMAT(tid.`dr_date`, '%m/%d/%Y')", 'drDate'),
            //array('tidi.`itemCtr`', 'tidi.`itemCtr`'),
            array('tid.`note`', 'tid.`note`'),
            array('tid.`id`', "tid.`id`")
        );
        $asColumns = array();

        $select = "SELECT";
        $from = "FROM `transfer_inventory_delivery` tid";
        $joins = "
            LEFT JOIN `transfer_inventory` ti ON tid.`transfer_inventory_id` = ti.`id`
            LEFT JOIN `branch` bf ON ti.`branch_id_from` = bf.`id`
            LEFT JOIN `branch` bt ON ti.`branch_id_to` = bt.`id`
            LEFT JOIN `transfer_inventory_delivery_item_tmp` tidi ON tid.`id` = tidi.`transfer_inventory_delivery_id`
        ";

        $sqlWhere = "WHERE tid.`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();

        $q = $conn->prepare("
            CREATE TEMPORARY TABLE IF NOT EXISTS `transfer_inventory_delivery_item_tmp` (
                INDEX `IDX_TMP_000AAA` (`transfer_inventory_delivery_id`)
            ) AS (
                SELECT
                    tidi.`transfer_inventory_delivery_id`,
                    COUNT(DISTINCT tidi.`id`) AS itemCtr
                FROM `transfer_inventory_delivery_item` tidi
                GROUP BY tidi.`transfer_inventory_delivery_id`
            )
        ");
        $q->execute();

        $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']);

            $action = '';

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

            $values = array(
                $row['drNo'],
                $row['drDate'],
                //number_format($row['itemCtr'], 0),
                $row['note'],
                $action
            );

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

        unset($result);

        return $output;
    }

    public function nativeInsert($transferInventoryDelivery_form) {

        $conn = $this->getEntityManager()->getConnection();
        $conn->beginTransaction();
        $todayDT = new \DateTime();
        $conn->executeQuery("
            SET @transferInventoryDelivery = (
                SELECT tid.`dr_no` * 1 as deliveryNo
                FROM `transfer_inventory_delivery` tid
                WHERE DATE_FORMAT(tid.`dr_date`, '%m%Y') = :deliveryDate
                ORDER BY deliveryNo DESC
                LIMIT 1
            );
        ", array('deliveryDate' => $todayDT->format('mY')));

        $rawQuery = "
            INSERT INTO `transfer_inventory_delivery` (
                `dr_no`,
                `dr_date`,  
                `note`, 
                `created_by`, 
                `created_at`, 
                `updated_by`, 
                `updated_at`,
                `transfer_inventory_id`
            ) VALUES (
                IF(@transferInventoryDelivery IS NULL, 0, @transferInventoryDelivery) + 1, 
                :drDate, 
                :note,
                :created_by, 
                :created_at, 
                :updated_by, 
                :updated_at,
                :transferInventoryId
            );
            -- SET @lastInsertID := LAST_INSERT_ID();
        ";
        $drDateDT = new \DateTime($transferInventoryDelivery_form['dr_date']);
        $stmtParams = array(
            'drDate' => $drDateDT->format('Y-m-d 00:00:00'),
            'created_by' => isSet($_COOKIE['username']) ? $_COOKIE['username'] : 'System',
            'created_at' => $todayDT->format('Y-m-d H:i:s'),
            'updated_by' => isSet($_COOKIE['username']) ? $_COOKIE['username'] : 'System',
            'updated_at' => $todayDT->format('Y-m-d H:i:s'),
            'transferInventoryId' => base64_decode($transferInventoryDelivery_form['transferInventory']),
            'note'   => $transferInventoryDelivery_form['note'],
        );

        // We need to execute the insert of patient billing table here so that we can get the ID into a return variable
        // This is because we can't perform a select statement after an insert statement, we need to release the buffer in order to do that
        // thus we will lose the value of @lastInsertID variable

        // We need to assign this in a variable so that we will have a in the lastInsertId() method
        $stmt = $conn->executeQuery($rawQuery, $stmtParams);
        $transferInventoryDelivery_id = $conn->lastInsertId();
        // We also need to call closeCursor in order to release buffered data otherwise it will cause general error: 2014
        $stmt->closeCursor();

        /*$rawQuery .= "
            SELECT @lastInsertID AS lastInsertId;
        ";*/
        $conn->commit();

        return $transferInventoryDelivery_id;
    }
}
