<?php

namespace RxConnexionBundle\Repository;

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

class MaterialRequisitionItemRepository extends EntityRepository
{
    public function validate($materialRequisitionItem_form) {

        $errors = array();

        $action = $materialRequisitionItem_form['action'];

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

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

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

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

        return $errors;
    }

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

        $columns = array(
            'ei.description',
            //'l.description',
            'pmri.quantity',
            'pmri.initialPrice',
            'pmri.tax',
            'pmri.totalPrice',
            'pmri.note',
            'pmri.id',
            //'pmri.controlNo',
            //'ium.code',
            //'ei.receivingUnitMeasurement'
            'mr.status AS mr_status',
        );
        $dtColumns = array(
            'ei.description as item_description',
            //'l.description as location_description',
            'pmri.quantity',
            'pmri.initialPrice',
            'pmri.tax',
            'pmri.totalPrice',
            //'pmri.controlNo',
            'pmri.note',
            'pmri.id',
            //'ium.code as unit_measurement',
            //'ei.receivingUnitMeasurement'
            'mr.status AS mr_status',
        );
        $dbColumns = array();
        $asColumns = array();

        $query = $this->getEntityManager()
            ->getRepository('RxConnexionBundle:MaterialRequisitionItemEntity')
            ->createQueryBuilder('pmri')
            ->leftJoin('pmri.item', 'ei')
	        ->leftJoin('pmri.materialRequisition', 'mr')
            //->leftJoin('pmri.location', 'l')
            //->leftJoin('pmri.itemUnitMeasurement' ,'ium')
            ->select(array_merge($dtColumns, $dbColumns))
            ->where('pmri.materialRequisition = :materialRequisition_id')
            ->setParameter('materialRequisition_id', base64_decode($get['materialRequisition_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 Material Requisition Item Update', $userData['accesses']);

        foreach($result as $row) {

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

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

            $sql = "SELECT
                    GROUP_CONCAT(CONCAT(mrium.`quantity` , '/' ,ium.`code` ) SEPARATOR '|') as quantity
                   FROM material_requisition_item_unit_measurement mrium
                   LEFT JOIN item_unit_measurement ium ON mrium.`item_unit_measurement_id` = ium.`id`
                   WHERE mrium.`material_requisition_item_id` = :material_requisition_item_id
                   ";


            $query = $conn->prepare($sql);
            $query->execute(array(
                'material_requisition_item_id' => $row['id']
            ));

            $material_requisition_unit_measurement = $query->fetchAll();*/

            $values = array(
                $row['item_description'],
                //$row['location_description'],
                number_format($row['quantity'], 0),
                number_format($row['initialPrice'], 2, '.', ','),
                number_format($row['tax'], 2, '.', ','),
                number_format($row['totalPrice'], 2, '.', ','),
                //$row['quantity'] .'/'. $row['unit_measurement'],
                //$row['controlNo'],
                $row['note'],
                //  $hasUpdate ? "<a href='javascript:void(0)' class='action-button-style href-materialRequisitionItem-form' data-action='u' data-id='$id'>Update</a>" : ""
                $hasUpdate && !in_array($row['mr_status'], ['Closed', 'Active']) ? "<a href='javascript:void(0)' class='action-button-style href-materialRequisitionItem-remove' data-id='$id'>Remove</a>" : ""
            );

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

        unset($result);

        return $output;
    }

}