<?php

namespace RxConnexionBundle\Repository;

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

class CanvassItemRepository extends EntityRepository
{
    public function ajax_list(array $get, $userData){

        $columns = array(
            array('it.`description`', "it.`description`", 'item_desc'),
            array('ci.`quantity`', "ci.`quantity`"),
            array('ci.`quantity_voided`', "ci.`quantity_voided`"),
            array('ci.`quantity_canvassed`', "ci.`quantity_canvassed`"),
            array('cis.supplierCtr', "cis.supplierCtr"),
            array('cis2.supplierSelectedCtr', "cis2.supplierSelectedCtr"),
            array('ci.`id`', "ci.`id`"),
            array('c.`status`', "c.`status`")
        );
        $asColumns = array();

        $select = "SELECT";
        $from = "FROM `canvass_item` ci";
        $joins = "
            LEFT JOIN `canvass` c ON ci.`canvass_id` = c.`id`
            LEFT JOIN `material_requisition_item` mri ON ci.`material_requisition_item_id` = mri.`id`
            LEFT JOIN `item` it ON mri.`item_id` = it.`id`
            -- LEFT JOIN `item_unit` iu ON it.`item_unit_id` = iu.`id`
            -- LEFT JOIN `item_size` isi ON it.`item_size_id` = isi.`id`
            LEFT JOIN (
                SELECT 
                    cis.`canvass_item_id`,
                    COUNT(DISTINCT cis.`id`) AS supplierCtr
                FROM `canvass_item_supplier` cis
                GROUP BY cis.`canvass_item_id`
            ) cis ON ci.`id` = cis.`canvass_item_id`
            LEFT JOIN (
                SELECT 
                    cis.`canvass_item_id`,
                    COUNT(DISTINCT cis.`id`) AS supplierSelectedCtr
                FROM `canvass_item_supplier` cis
                WHERE cis.`is_selected` = 1
                GROUP BY cis.`canvass_item_id`
            ) cis2 ON ci.`id` = cis2.`canvass_item_id`
        ";
        $sqlWhere = "WHERE ci.`canvass_id` = :canvass_id";
        $groupBy = "";
        $orderBy = "";
        $limit = "";
        $stmtParams = array(
            'canvass_id' => base64_decode($get['canvass_id'])
        );

        /*if('Super Admin' !== $userData['type']) {
            if(count($userData['branchIds'])) {
                $ors = '';
                foreach($userData['branchIds'] as $key => $branchId) {
                    $ors .= (!empty($ors) ? ' OR ' : '') . 'mr.`branch_id` = :branch_id_' . $key;
                    $stmtParams['branch_id_' . $key] = $branchId;
                }
                $sqlWhere .= " AND ($ors)";
            } else { // Don't show anything
                $sqlWhere .= " AND mr.`branch_id` < 0";
            }
        }*/

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

        /* Data Count */
        $recordsTotal = count($result_count);

        /*
         * Output
         */
        $output = array(
            "draw" => intval($get['draw']),
            "recordsTotal" => $recordsTotal,
            "recordsFiltered" => $recordsTotal,
            "data" => array()
        );

        $hasAddSupplier = $userData['type'] === 'Super Admin' || in_array('Admin Canvass Add Supplier', $userData['accesses']);
        $hasSelectSupplier = $userData['type'] === 'Super Admin' || in_array('Admin Canvass Select Supplier', $userData['accesses']);

        foreach($result as $row) {

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

            $action = '';

            if($row['status'] === 'Supplier Canvassing') {
                if($hasAddSupplier)
                    $action .= "<a href='javascript:void(0)' class='action-button-style href-canvassItemSupplier-form' data-item-desc='{$row['item_desc']}' data-action='n' data-ref-id='$id'>Add Supplier</a>";

                if($hasSelectSupplier)
                    $action .=  "<a href='javascript:void(0)' class='action-button-style href-canvassItemSupplier-select' data-ref-id='$id'>Select Supplier</a>";
            }

            $action .= "<a href='javascript:void(0)' class='action-button-style href-canvassItemSupplier-details' data-ref-id='$id'>Details</a>";
            $values = array(
                $row['item_desc'],
                number_format($row['quantity'], 0),
                number_format($row['quantity_voided'], 0),
                number_format($row['quantity_canvassed'], 0),
                $row['supplierCtr'],
                $row['supplierSelectedCtr'],
                $action
            );

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

        unset($result);

        return $output;
    }

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

        $columns = array(
            'ei.description',
            'pci.quantity',
            'pci.quantityAdded',
            'pci.quantityVoided',
            'pci.quantityCanvassed',
            'pci.quantityAdded',
            'pci.id',
            'ei.receivingUnitMeasurement',
            'ium.description'
        );
        $dtColumns = array(
            'ei.description as item_description',
            'pci.quantity',
            'pci.quantityAdded',
            'pci.quantityVoided',
            'pci.quantityCanvassed',
            'pci.quantityAdded',
            'pci.id',
            'ei.receivingUnitMeasurement',
            'ium.description as unit_of_measurement'
        );
        $dbColumns = array('pmrc.status as canvass_status');
        $asColumns = array();

        $query = $this->getEntityManager()
            ->getRepository('RxConnexionBundle:CanvassItemEntity')
            ->createQueryBuilder('pci')
            ->leftJoin('pci.itemUnitMeasurement' ,'ium')
            ->leftJoin('pci.canvass', 'pmrc')
            ->leftJoin('pci.materialRequisitionItem', 'pmri')
            ->leftJoin('pmri.item', 'ei')
            ->leftJoin('ei.itemCategory', 'eic')
            ->select(array_merge($dtColumns, $dbColumns))
            ->where('pci.canvass = :canvass_id')
            ->setParameter('canvass_id', base64_decode($get['canvass_id']));

        if($get['item_category_id'] != '' && !empty($get['item_category_id'])){
            $query = $query
                        ->andWhere('eic.id = :item_category_id')
                        ->setParameter('item_category_id',$get['item_category_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()
        );

        $hasAddSupplier = $userData['type'] === 'Super Admin' || in_array('Admin Canvass Add Supplier', $userData['accesses']);
        $hasSelectSupplier = $userData['type'] === 'Super Admin' || in_array('Admin Canvass Select Supplier', $userData['accesses']);

        foreach($result as $row) {

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

            $action = '';

            if($row['canvass_status'] === 'Supplier Canvassing' ||
                ($row['canvass_status'] === 'Pending Purchasing Manager Approval' && ($userData['type'] === 'Purchasing Manager' || $userData['type'] === 'Admin')) ||
                ($row['canvass_status'] === 'Pending Admin Approval For Purchase Order' && $userData['type'] === 'Admin')) {

                if($hasAddSupplier)
                    $action .= "<a href='javascript:void(0)' class='action-button-style href-canvassItemSupplier-form' data-action='n' data-ref-id='$id'>Add Supplier</a>";

                if($hasSelectSupplier)
                    $action .=  "<a href='javascript:void(0)' class='action-button-style href-canvassItemSupplier-select' data-ref-id='$id'>Select Supplier</a>";
            }

            $action .= "<a href='javascript:void(0)' class='action-button-style href-canvassItemSupplier-details' data-ref-id='$id'>Details</a>";
            $indicator = ($row['quantity'] + $row['quantityAdded'] - $row['quantityVoided']) == $row['quantityCanvassed'] ? 'green' : 'red';
            $values = array(

                $row['item_description'],
                number_format($row['quantity'], 2) .'/ &nbsp;' . $row['unit_of_measurement'],
                number_format($row['quantityVoided'], 2),
                number_format($row['quantityAdded'], 2),
                //number_format($row['quantityCanvassed'], 2),
                $action
            );

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

        unset($result);

        return $output;
    }
}