<?php

namespace RxConnexionBundle\Repository;

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

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

        $errors = array();

        $action = $purchaseOrderBreakdown_form['action'];

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

            if(empty($purchaseOrderBreakdown_form['purchase_order_no']))
                $errors[] = 'PO number should not be blank.';

            if(empty($purchaseOrderBreakdown_form['payment_method']))
                $errors[] = 'Please select payment method.';

            $quantity = 0;
            $purchaseOrderItems_form = $request->get('purchaseOrderItems');
            $purchaseOrder = $this->getEntityManager()->getRepository('RxConnexionBundle:PurchaseOrderEntity')->find($purchaseOrderBreakdown_form['purchaseOrder_id']);

            foreach($purchaseOrderItems_form as $purchaseOrderItem_form) {
                $quantity += str_replace(',', '', $purchaseOrderItem_form['quantity']);

                foreach($purchaseOrder->getPurchaseOrderItems() as $purchaseOrderItem) {
                    if($purchaseOrderItem->getId() === $purchaseOrderItem_form['id'] && (($purchaseOrderItem->getQuantityWithPo() - $purchaseOrderItem_form['purchaseOrderBreakdownItem_quantity']) + str_replace(',', '', $purchaseOrderItem_form['quantity'])) > ($purchaseOrderItem->getQuantity() + $purchaseOrderItem->getQuantityAdded()))
                        $errors[] = 'Item ' . $purchaseOrderItem->getMaterialRequisitionItem()->getItem()->getDescription() . ' already met its required quantity.';
                }
            }

            if($quantity === 0) {
                $errors[] = 'Atleast one(1) item with quantity is required.';
            }
        }

        return $errors;
    }

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

        $columns = array(
            array('pob.`po_no`', "pob.`po_no`", 'poNo'),
            array('pob.`po_date`', "DATE_FORMAT(pob.`po_date`, '%m/%d/%Y')", 'poDate'),
            array('pob.`status`', "pob.`status`"),
            //array('pob.`payment_method`', "pob.`payment_method`", 'payMethod'),
            array('pobi.itemCtr', "pobi.itemCtr"),
            array('pob.`id`', "pob.`id`")
        );
        $asColumns = array();

        $select = "SELECT";
        $from = "FROM `purchase_order_breakdown` pob";
        $joins = "
            LEFT JOIN `purchase_order_breakdown_item_tmp` pobi ON pob.`id` = pobi.`purchase_order_breakdown_id`
        ";
        $sqlWhere = "WHERE pob.`purchase_order_id` = :purchaseOrder_id";
        $groupBy = "";
        $orderBy = "";
        $limit = "";
        $stmtParams = array('purchaseOrder_id' => base64_decode($get['purchaseOrder_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') {
                    if(3 === $key) {
                        $aLikes[] = "DATE_FORMAT(mr.`request_date`, '%m/%d/%Y') LIKE :searchValue";
                    } else {
                        $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'];
        }

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

        $q = $conn->prepare("
            CREATE TEMPORARY TABLE IF NOT EXISTS `purchase_order_breakdown_item_tmp` (
                INDEX `IDX_TMP_000AAA` (`purchase_order_breakdown_id`)
            ) AS (
                SELECT
                    `purchase_order_breakdown_id`,
                    COUNT(DISTINCT `id`) AS itemCtr
                FROM `purchase_order_breakdown_item`
                GROUP BY `purchase_order_breakdown_id`
            )
        ");
        $q->execute();

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

        $url = $get['url'];
        $viewUrl = $url . '/admin/material_requisition/purchase_order/breakdown/item/delivery/view';
        $printUrl = $url . '/admin/material_requisition/purchase_order/breakdown/print';

        // $hasUpdate = $userData['type'] === 'Super Admin' || in_array('Admin Purchase Order Update', $userData['accesses']);
        // $hasSend = $userData['type'] === 'Super Admin' || in_array('Admin Purchase Order Send', $userData['accesses']);
        $hasPrint = $userData['type'] === 'Super Admin' || in_array('Admin Purchase Order Print', $userData['accesses']);
        $hasView = $userData['type'] === 'Super Admin' || in_array('Admin Purchase Order Receive', $userData['accesses']);

        foreach($result as $row) {

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

            $action = '';

            /*if($row['status'] === 'New') {

                if($hasUpdate) {
                    $action .= "<a href='javascript:void(0)' class='action-button-style href-purchaseOrderBreakdown-form' data-action='u' data-id='$id'>Update</a>";
                }
                if($hasSend) {
                    $action .= "<a href='javascript:void(0)' class='action-button-style href-purchaseOrderBreakdown-send' data-id='$id'>Send</a>";
                }
                // if($hasPrint) {
                //     $action .= "<a href='javascript:alert(\"Coming Soon...\")' class='action-button-style'>Print P.O.</a>";
                // }
            }*/

            if($hasPrint) {
                $action .= "<a href='$printUrl/$id' class='action-button-style'>Print P.O.</a>";
            }

            if(($row['status'] === 'Sent' || $row['status'] === 'Received') && $hasView)
                $action .= "<a class='action-button-style' href='$viewUrl/$id'>Receive Order</a>";

            $action .= "<a href='javascript:void(0)' class='action-button-style href-purchaseOrderBreakdown-details' data-id='$id'>Details</a>";

            $values = array(
                $row['poNo'],
                $row['poDate'],
                $row['status'],
                //$row['payMethod'],
                number_format($row['itemCtr'], 0),
                $action
            );

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

        unset($result);

        return $output;
    }

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

        $columns = array(
            'ppob.poNo',
            'ppo.batchNo',
            'pmr.materialRequisitionNo',
            'es.description',
            'pmr.requestDate',
            'eb.description',
            'eu.firstName',
            'ppob.id',
            'ppobi.quantityAdded',
//            'pi.id as purchaseInvoiceId'
        );
        $dtColumns = array(
            'ppob.poNo',
            'ppo.batchNo as purchaseOrder_batchNo',
            'pmr.materialRequisitionNo as materialRequisition_materialRequisitionNo',
            'es.description as supplier_description',
            'pmr.requestDate as materialRequisition_requestDate',
            'eb.description as branch_description',
            "CONCAT(eu.firstName, ' ', eu.lastName) as user_fullName",
            'ppob.id',
            'ppobi.quantityAdded as quantityAdded',
//            'pi.id as purchaseInvoiceId'
        );
        $dbColumns = array('COUNT(ppobi.id) as purchaseOrderBreakdownItems_count');
        $asColumns = array();

        $query = $this->getEntityManager()
            ->getRepository('RxConnexionBundle:PurchaseOrderBreakdownEntity')
            ->createQueryBuilder('ppob')
            ->leftJoin('ppob.purchaseOrderBreakdownItems', 'ppobi')
//            ->leftJoin('ppob.purchaseInvoice', 'pi')
            ->leftJoin('ppob.purchaseOrder', 'ppo')
            ->leftJoin('ppo.supplier', 'es')
            ->leftJoin('ppo.materialRequisition', 'pmr')
            ->leftJoin('pmr.healthFacility', 'eb')
            ->leftJoin('pmr.accountUser', 'eu')
            ->select(array_merge($dtColumns, $dbColumns))
            ->groupBy('ppob.id');

        if(isSet($get['status']) && $get['status'] !== 'all') {
            if($get['status'] == 'Active') {
                $query->andWhere('ppob.status IN (:status1, :status2)')
                    ->setParameters([
                        'status1' => 'New',
                        'status2' => 'Sent',
                    ]);
            } elseif($get['status'] == 'Closed') {
                $query->andWhere('ppob.status IN (:status1, :status2, :status3)')
                    ->setParameters([
                        'status1' => 'Received',
                        'status2' => 'Voided',
                        'status3' => 'Cancelled',
                    ]);
            }
        }
	    if('Super Admin' !== $userData['type']) {
		    if (isset($userData['branches']) && count($userData['branches'])) {
			    $ors = '';
			    foreach ($userData['branches'] as $key => $branchId) {
				    $ors .= (!empty($ors) ? ' OR ' : '') . 'pmr.healthFacility = :branch_id_' . $key;
				    $query->setParameter("branch_id_$key", $branchId);
			    }
			    $query->andWhere("($ors)");
		    } else { // Don't show anything
			    $query->andWhere("pmr.healthFacility < 0");
		    }

	    }

        /*
         * 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'];
        $viewUrl = $url . '/admin/material_requisition/purchase_order/breakdown/item/delivery/view';
        $printPurchaseOrderUrl = $url . '/admin/material_requisition/purchase_order/breakdown/print';
        $printPurchaseInvoiceUrl = $url . '/admin/material_requisition/purchase_invoice/print';
        $hasView = $userData['type'] === 'Super Admin' || in_array('Admin Purchase Order Receive', $userData['accesses']);
        $hasPurchaseOrderPrint = $userData['type'] === 'Super Admin' || in_array('Admin Purchase Order Print', $userData['accesses']);
        $hasPurchaseInvoicePrint = $userData['type'] === 'Super Admin' || in_array('Admin Purchase Invoice Print', $userData['accesses']);
        $dateTimeToStringTransformer = new DateTimeToStringTransformer();

        foreach($result as $row) {

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

            $action = '';

            if($hasView)
                $action .= "<a class='action-button-style' href='$viewUrl/$id' >View</a>";
            /*      if($hasPurchaseOrderPrint)
                      $action .= "<a class='action-button-style' href='$printPurchaseOrderUrl/$id' >Print PO</a>";
                  if($hasPurchaseInvoicePrint)
                      $action .= "<a class='action-button-style' href='$printPurchaseInvoiceUrl/$purchaseInvoiceId' >Print RR</a>";*/

            $values = array(
                $row['poNo'],
//                $row['purchaseOrder_batchNo'],
                $row['materialRequisition_materialRequisitionNo'],
                $row['supplier_description'],
                date('m/d/Y', strtotime($dateTimeToStringTransformer->transform($row['materialRequisition_requestDate']))),
                $row['branch_description'],
                $row['user_fullName'],
                number_format($row['purchaseOrderBreakdownItems_count'], 2),
                number_format($row['quantityAdded'], 2),
                $action
            );

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

        unset($result);

        return $output;
    }

    public function getNextPurchaseOrderNo() {

        $sql = "
            SELECT
                ppob.`purchase_order_no`
            FROM `purchase_order_breakdown` ppob
            ORDER BY ppob.`purchase_order_no` DESC
            LIMIT 1
        ";

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

        $result = $query->fetch();

        return $result ? $result['purchase_order_no'] + 1 : 1;
    }

    public function dashboardData($userData) {

        $andWhere = '';
        $stmtParams = array();

        if($userData['type'] !== 'Super Admin') {
            if(count($userData['branchIds'])) {
                $ors = '';
                foreach($userData['branchIds'] as $key => $branchId) {
                    $ors .= (empty($ors) ? '' : ' OR ') . 'mr.`branch_id` = :branchId' . $key;
                    $stmtParams['branchId' . $key] = $branchId;
                }
                if(!empty($ors)) {
                    $andWhere .= ' AND (' . $ors . ')';
                }
            } else {
                $andWhere .= ' AND mr.`branch_id` < 0';
            }
            if(count($userData['departmentIds'])) {
                $ors = '';
                foreach($userData['departmentIds'] as $key => $departmentId) {
                    $ors .= (empty($ors) ? '' : ' OR ') . 'mr.`department_id` = :departmentId' . $key;
                    $stmtParams['departmentId' . $key] = $departmentId;
                }
                if(!empty($ors)) {
                    $andWhere .= ' AND (' . $ors . ')';
                }
            } else {
                $andWhere .= ' AND mr.`department_id` < 0';
            }
        }

        $query = $this->getEntityManager()->getConnection()->prepare("
            SELECT
                COUNT(DISTINCT pob.`id`) AS ctr,
                pob.`status`
            FROM `purchase_order_breakdown` pob
            LEFT JOIN `purchase_order` po ON pob.`purchase_order_id` = po.`id`
            LEFT JOIN `material_requisition` mr ON po.`material_requisition_id` = mr.`id`
            WHERE pob.`status` = 'Sent'
            $andWhere
            GROUP BY pob.`status`
        ");
        $query->execute($stmtParams);

        return $query->fetchAll();
    }
}
