<?php

namespace RxConnexionBundle\Repository;

use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToStringTransformer;

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

        $errors = array();

        $action = $addInventory_form['action'];

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

            if(empty($addInventory_form['add_date']))
                $errors[] = 'Date should not be blank.';

            if(empty($addInventory_form['healthFacility']))
                $errors[] = 'Please select branch.';
//
//            if(empty($addInventory_form['supplier_id']))
//                $errors[] = 'Please select supplier.';
        }

        return $errors;
    }

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

        $columns = array(
            'iui.id',
            'iui.addDate',
            'eb.description',
//            's.description',
            'iui.status',
            'iui.note',
            'iui.id'
        );
        $dtColumns = array(
            'iui.id',
            'iui.addDate',
            'eb.description as branch_description',
//            's.description as supplier_description',
            'iui.status',
            'iui.note',
            'iui.id'
        );
        $dbColumns = array();
        $asColumns = array();

        $query = $this->getEntityManager()
            ->getRepository('RxConnexionBundle:AddInventoryEntity')
            ->createQueryBuilder('iui')
            ->leftJoin('iui.healthFacility', 'eb')
//            ->leftJoin('iui.supplier', 's')
            ->select(array_merge($dtColumns, $dbColumns));
//            ->where('iui.branch IN (:user_branchIds)')
//            ->setParameter('user_branchIds', $userData['branchIds']);

//        if(isSet($get['status']) && $get['status'] !== 'all') {
//
//            $query->where('iui.status = :status')
//                ->setParameter('status', $get['status']);
//        }

        /*
         * 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()
        );

        $url = $get['url'];
        $formUrl = $url . '/admin/add_inventory/form';
        $addInventoryItemUrl = $url . '/admin/add_inventory/item/index';

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

        $dateTimeToStringTransformer = new DateTimeToStringTransformer();

        foreach($result as $row) {

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

            $action = '';

            if($row['status'] === 'New' && $hasUpdate)
                $action = "<a class='action-button-style' href='$formUrl/u/$id'>Update</a>";

            if($hasAddInventoryItemAccess)
                $action .= "<a class='action-button-style' href='$addInventoryItemUrl/$id'>Items</a>";

            $values = array(
                sprintf('%012d', $row['id']),
                date('m/d/Y', strtotime($dateTimeToStringTransformer->transform($row['addDate']))),
                $row['branch_description'],
//                $row['supplier_description'],
                $row['status'],
                $row['note'],
                $action
            );

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

        unset($result);

        return $output;
    }

}
