<?php

namespace RxConnexionBundle\Repository;

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

class ConvertInventoryItemBiRepository extends EntityRepository
{
    public function validate($convertInventoryItemBi_form) {

        $errors = array();

        $action = $convertInventoryItemBi_form['action'];

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

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

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

            if(empty($convertInventoryItemBi_form['location']))
                $errors[] = 'Please enter location.';

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

        return $errors;
    }

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

        $columns = array(
            'ei.description',
            'iuii.serialNo',
            'l.description',
            'iuii.quantity',
            'iuii.totalCost',
            'iuii.id'
        );
        $dtColumns = array(
            'ei.description as item_description',
            'iuii.serialNo',
            'l.description as location_description',
            'iuii.quantity',
            'iuii.totalCost',
            'iuii.id'
        );
        $dbColumns = array('iui.status as convertInventory_status');
        $asColumns = array();

        $query = $this->getEntityManager()
            ->getRepository('RxConnexionBundle:ConvertInventoryItemBiEntity')
            ->createQueryBuilder('iuii')
            ->leftJoin('iuii.convertInventory', 'iui')
            ->leftJoin('iuii.item', 'ei')
            ->leftJoin('iuii.location', 'l')
            ->select(array_merge($dtColumns, $dbColumns))
            ->where('iuii.convertInventory = :convertInventory_id')
            ->setParameter('convertInventory_id', base64_decode($get['convertInventory_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 Convert Inventory Item Update', $userData['accesses']);
        $totalCost = 0;

        foreach($result as $row) {

            $totalCost += $row['totalCost'];
            $id = base64_encode($row['id']);

            $values = array(
                $row['item_description'],
                $row['serialNo'],
                $row['location_description'],
                number_format($row['quantity'], 2),
                //number_format($row['totalCost'], 2),
                ($hasUpdate && $row['convertInventory_status'] === 'New' ? "<a href='javascript:void(0)' class='action-button-style href-convertInventoryItemBi-form' data-action='u' data-id='$id'>Update</a>" : "") .
                ($row['convertInventory_status'] === 'Pending Costing' ? "<a href='javascript:void(0)' class='action-button-style href-convertInventoryItemBi-form-costing' data-id='$id'>Add Cost</a>" : "")
            );

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

        /*$output['data'][] = array(
            '',
            '',
            'Total Cost',
            number_format($totalCost, 2),
            ''
        );*/

        unset($result);

        return $output;
    }
}