<?php

namespace RxConnexionBundle\Repository;

use RxConnexionBundle\Entity\InventoryEntity;

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

        $errors = array();

        $action = $item_form['action'];

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

            $itemExist = $this->getEntityManager()->getRepository('RxConnexionBundle:ItemEntity')
                ->createQueryBuilder('ep')
                ->where('ep.id != :id')
                ->andWhere('ep.description = :description')
                ->andWhere('ep.isDeleted = 0')
                ->setParameters(array(
                    'id' => $item_form['id'],
                    'description' => $item_form['description'],
                ))
                ->getQuery()->getResult();

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

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

        }

        return $errors;
    }

    public function ajax_list(array $get){

        $columns = array(
            array('ic.`description`', 'ic.`description`', 'itemCat'),
            array('isc.`description`', 'isc.`description`', 'itemSubCat'),
            array('co.`description`', 'co.`description`', 'itemCompany'),
            array('c.`code`', 'c.`code`'),
            array('c.`type`', 'c.`type`'),
            array('c.`description`', 'c.`description`'),
            array('c.`start_date`', "DATE_FORMAT(c.`start_date`, '%m/%d/%Y')", 'startDate'),
            array('c.`end_date`', "DATE_FORMAT(c.`end_date`, '%m/%d/%Y')", 'endDate'),
            array('c.`id`', "c.`id`")
        );
        $asColumns = array();

        $select = "SELECT";
        $from = "FROM `item` c";
        $joins = "LEFT JOIN `item_subcategory` isc ON c.`item_subcategory_id` = isc.`id`";
        $joins .= " LEFT JOIN `item_category` ic ON isc.`item_category_id` = ic.`id`";
        $joins .= " LEFT JOIN `company` co ON c.`item_company_id` = co.`id`";
        $sqlWhere = "WHERE c.`is_deleted` = 0";
        $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();

        return array(
            'results' => $result,
            'total' => count($result_count)
        );
    }

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

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

        $itemDesc = "CONCAT_WS(' / ', it.`code` , it.`description`)";
        $columns = array(
            array('it.`description`', $itemDesc, 'item_desc'),
            //array('iv.qty', 'iv.qty'),
            array('it.`id`', "it.`id`"),
//            array('it.`is_consumable`', 'it.`is_consumable`'),
            array('it.`description`', "it.`description`"),
            array('it.`description`', "it.`description`"),
        );
        $asColumns = array();
        $select = "SELECT";
        $from = "FROM `item` it";
        $joins = "
            -- LEFT JOIN `item_size` isi ON it.`item_size_id` = isi.`id`
            -- LEFT JOIN `item_unit` iu ON it.`item_unit_id` = iu.`id`
            LEFT JOIN `inv_tmp` iv ON it.`id` = iv.`item_id`
        ";
        $sqlWhere = '';
        $groupBy = "";
        $orderBy = "";
        $limit = "";
        $stmtParams = array();

        if($get['itemCategory_id'] > 0){
            $sqlWhere = 'WHERE it.`item_category_id` = :itemCategory_id';
            $stmtParams['itemCategory_id'] = $get['itemCategory_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'];
        }

        $q = $conn->prepare("
            CREATE TEMPORARY TABLE IF NOT EXISTS `inv_tmp` (
                INDEX `IDX_TMP_000AAA` (`item_id`)
            ) AS (
                SELECT 
                    i.`item_id`,
                    SUM(i.`quantity`) AS qty
                FROM `inventory` i
                WHERE i.`health_facility_id` = :branch_id
                AND i.`status` = :status
                GROUP BY i.`item_id`
            )
        ");
        $q->execute(array(
            'branch_id' => base64_decode($get['branchId']),
            'status' => InventoryEntity::STATUS_STOCK_ON_HAND
        ));

        $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()
        );
        foreach($result as $key => $row) {
            $id = base64_encode($row['id']);
            //$consumable = $row['is_consumable'] == 1 ? 'checked' : '';
            $qty = '';
//            $consumable = '';
            $note = '';
//            $itemIsConsumable = 'false';
            if(isset($get['itemIdQtys'])){
                if(array_key_exists($row['id'], $get['itemIdQtys'])){
                    $qty = $get['itemIdQtys'][$row['id']]['itemQty'];
//                    $itemIsConsumable = $get['itemIdQtys'][$row['id']]['itemIsConsumable'];
                    $note = $get['itemIdQtys'][$row['id']]['itemNote'];
                }
//                $consumable = $itemIsConsumable === 'true' ? 'checked' : '';
            }
            $values = array(
                $row['item_desc'],
                //number_format($row['qty'], 0),
                "<input type='text' class='numeric' id='addItemForm-qty-$key' value='$qty'/>",
                "<input type='text' id='addItemForm-note-$key' value='$note' />",
//                "<input type='checkbox' id='addItemForm-consumable-$key' $consumable/>",
                "<a class='action-button-style href-item-add' data-key='$key' data-id='$id'>Add Item</a>"
            );

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

        unset($result);

        return $output;
    }

    public function autocomplete_suggestions($request)
    {
        $q = $request->get('query');
        $item_category_id = $request->get('item_category_id');
        $andWhere = '';
        $params = array(
            'description' => "%$q%",
            'now' => DATE('Y-m-d 00:00:00')
        );
        if(isset($item_category_id) && $item_category_id != ''){
            $andWhere .= ' AND ic.`item_category_id` = :itemCat';
            $params['itemCat'] = $item_category_id;
        }

        $sql = "
            SELECT
                i.`id`,
                ip.`price`,
                ic.`description` AS subCat,
                i.`description` AS data,
                i.`description` AS value
            FROM `item` i
            LEFT JOIN `item_subcategory` ic ON i.`item_subcategory_id` = ic.`id`
            LEFT JOIN `item_price` ip ON i.id = ip.item_id AND ip.`start_date` <= :now AND (ip.`end_date` >= :now OR ip.`end_date` is null) AND ip.`is_deleted` = 0
            WHERE i.`description` LIKE :description
            AND i.`is_deleted` = 0
            $andWhere
            ORDER BY i.`description`
            LIMIT 0,20
        ";

        $query = $this->getEntityManager()->getConnection()->prepare($sql);

        $query->execute($params);

        $result = $query->fetchAll();

        return $result;
    }

    public function itemExportToExcel() {

        $sql = "
            SELECT
                i.`id`,
                ic.`description` AS subCat,
                c.`description` AS company,
                i.`code`,
                i.`type`,
                i.`description`,
                i.`start_date`,
                i.`end_date`
            FROM `item` i
            LEFT JOIN `item_subcategory` ic ON i.`item_subcategory_id` = ic.`id`
            LEFT JOIN `company` c ON i.`item_company_id` = c.`id`
        ";

        $query = $this->getEntityManager()->getConnection()->prepare($sql);

        $query->execute();

        $result = $query->fetchAll();

        return $result;
    }
}
