<?php

namespace RxConnexionBundle\Repository;

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

        $errors = array();

        $action = $transferInventory_form['action'];

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

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

//            if(empty($transferInventory_form['department']))
//                $errors[] = 'Department should not be blank.';

            if(empty($transferInventory_form['branchFrom']))
                $errors[] = 'Please select origin branch.';

            if(empty($transferInventory_form['branchTo']))
                $errors[] = 'Please select destination branch.';

            if(empty($transferInventory_form['locationFrom']))
                $errors[] = 'Please select origin location.';

            if(empty($transferInventory_form['locationTo']))
                $errors[] = 'Please select destination location.';
        }

        return $errors;
    }

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


        $DT = new \DateTime();
        $columns = array(
            array('ti.`transfer_no`', 'ti.`transfer_no`', 'transferNo'),
            array('ti.`transfer_date`', "DATE_FORMAT(ti.`transfer_date`, '%m/%d/%Y')", 'transferDate'),
            array('CONCAT_WS("", bf.`description`, CONCAT(" (", lf.`description` , ")"))', 'CONCAT_WS(" ", bf.`description`, CONCAT(" (", lf.`description` , ")"))', 'origin'),
            array('CONCAT_WS("", bt.`description`, CONCAT(" (", lt.`description` , ")"))', 'CONCAT_WS(" ", bt.`description`, CONCAT(" (", lt.`description` , ")"))', 'destination'),
            array('ti.`status`', 'ti.`status`'),
            array('tii.`itemCtr`', 'tii.`itemCtr`'),
            array('ti.`note`', 'ti.`note`'),
            array('ti.`id`', "ti.`id`"),
            array('bf.`description`', 'bf.`description`', 'branchFromDesc'),
            array('bt.`description`', 'bt.`description`', 'branchToDesc'),
//            array('sa.`id`', "IF(ti.`status` != 'Approved' AND sa.`id` IS NOT NULL, 1 , 0)", 'canApprove'),
            array('ti.`id`', 'ti.`id`'),
        );
        $asColumns = array();

        $select = "SELECT";
        $from = "FROM `transfer_inventory` ti";
        $joins = "
            LEFT JOIN `health_facility` bf ON ti.`branch_id_from` = bf.`id`
            LEFT JOIN `health_facility` bt ON ti.`branch_id_to` = bt.`id`
            LEFT JOIN `location` lf ON ti.`location_id_from` = lf.`id`
            LEFT JOIN `location` lt ON ti.`location_id_to` = lt.`id`
            LEFT JOIN `transfer_inventory_item_tmp` tii ON ti.`id` = tii.`transfer_inventory_id`
        ";
//        $joins .= " LEFT JOIN `status_approval` sa ON ti.`status` = sa.`description` AND
//                        IF(:userType = 'Super Admin', 1=1 , sa.`id` IN (
//                                SELECT sau.`status_approval_id`
//                                FROM `status_approval_user` sau
//                                WHERE sau.`user_id` = :userId
//                                AND sau.`start_date` <= :startDate
//                                AND (sau.`end_date` >= :endDate OR sau.`end_date` IS NULL)
//                                AND sa.`description` = ti.`status`
//                            )
//                        )";

//        $sqlWhere = "WHERE IF(:userType = 'Super Admin', 1=1,
//            IF(
//                (:userId IN (
//                    SELECT sau.`user_id`
//                    FROM `status_approval_user` sau
//                    LEFT JOIN `status_approval` sa ON sa.`id` = sau.`status_approval_id`
//                    WHERE UPPER(sa.`description`) IN (:status_1, :status_2)
//                    )
//                ) OR ti.`created_by` = :userName,
//                1=1,
//                1=0
//            )
//        )";

        $sqlWhere = "";
        $groupBy = "";
        $orderBy = "";
        $limit = "";
        $stmtParams = array(
//            'userType'    => $userData['type'],
//            'userName'    => $userData['username'],
//            'userId'      => $userData['id'],
//            'startDate'   => $DT->format('Y-m-d 00:00:00'),
//            'endDate'     => $DT->format('Y-m-d 23:59:59'),
//            'status_1'    => 'TRANSFER INVENTORY PENDING APPROVAL',
//            'status_2'    => 'TRANSFER INVENTORY PENDING FINAL APPROVAL',
        );


//        if('Super Admin' !== $userData['type']) {
//            if(count($userData['branchIds'])) {
//                $branchOrs = '';
//                $orsTo = '';
//                foreach($userData['branchIds'] as $key => $branchId) {
//                    $branchOrs .= (!empty($branchOrs) ? ' OR ' : '') . 'ti.`branch_id_from` = :branch_id_from_' . $key;
//                    $orsTo .= (!empty($orsTo) ? ' OR ' : '') . 'ti.`branch_id_to` = :branch_id_to_' . $key;
//                    $stmtParams['branch_id_from_' . $key] = $branchId;
//                    $stmtParams['branch_id_to_' . $key] = $branchId;
//                }
//                $sqlWhere .= (empty($sqlWhere) ? 'WHERE ' : ' AND ') . "(($branchOrs) OR ($orsTo))";
//            } else { // Don't show anything
//                $sqlWhere .= (empty($sqlWhere) ? 'WHERE ' : ' AND ') . "ti.`branch_id_from` < 0";
//            }
//        }

        if(isSet($get['status']) && $get['status'] !== 'all') {
            $sqlWhere .= (empty($sqlWhere) ? 'WHERE ' : ' AND ') . 'ti.status = :status';
            $stmtParams['status'] =  $get['status'];
        }

        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'];
        }

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

        $q = $conn->prepare("
            CREATE TEMPORARY TABLE IF NOT EXISTS `transfer_inventory_item_tmp` (
                INDEX `IDX_TMP_000AAA` (`transfer_inventory_id`)
            ) AS (
                SELECT
                    tii.`transfer_inventory_id`,
                    COUNT(DISTINCT tii.`id`) AS itemCtr
                FROM `transfer_inventory_item` tii
                GROUP BY tii.`transfer_inventory_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'];
        $formUrl = $url . '/admin/transfer_inventory/form';
        $transferInventoryItemUrl = $url . '/admin/transfer_inventory/item/index';

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

        foreach($result as $row) {

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

            $action = '';

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

            if($hasTransferInventoryItemAccess)
                $action .= "<a class='action-button-style' href='$transferInventoryItemUrl/$id'>Details</a>";

            $values = array(
                $row['transferNo'],
                $row['transferDate'],
                $row['origin'],
                $row['destination'],
                $row['status'],
                number_format($row['itemCtr'], 0),
                $row['note'],
                $action
            );

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

        unset($result);

        return $output;
    }

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

        $columns = array(
            'iui.id',
            'iui.transferDate',
            'eb.description',
            'ebt.description',
            'iui.status',
            'iui.note',
            'iui.id'
        );
        $dtColumns = array(
            'iui.id',
            'iui.transferDate',
            'eb.description as branchFrom_description',
            'ebt.description as branchTo_description',
            'iui.status',
            'iui.note',
            'iui.id'
        );
        $dbColumns = array();
        $asColumns = array();

        $query = $this->getEntityManager()
            ->getRepository('ZapconBundle:TransferInventoryEntity')
            ->createQueryBuilder('iui')
            ->leftJoin('iui.branchFrom', 'eb')
            ->leftJoin('iui.branchTo', 'ebt')
            ->select(array_merge($dtColumns, $dbColumns))
            ->where('(iui.branchFrom IN (:user_branchIds) OR iui.branchTo IN (:user_branchIds))')
            ->setParameter('user_branchIds', $userData['branchIds']);

        if(isSet($get['status']) && $get['status'] !== 'all') {

            $query->andWhere('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/transfer_inventory/form';
        $transferInventoryItemUrl = $url . 'admin/transfer_inventory/item/index';

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

        $dateTimeToStringTransformer = new DateTimeToStringTransformer();

        foreach($result as $row) {

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

            $action = '';

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

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

            $values = array(
                sprintf('%006d', $row['id']),
                date('m/d/Y', strtotime($dateTimeToStringTransformer->transform($row['transferDate']))),
                $row['branchFrom_description'],
                $row['branchTo_description'],
                $row['status'],
                number_format($row['itemCtr'], 0),
                $row['note'],
                $action
            );

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

        unset($result);

        return $output;
    }

    public function countForApprovalByUser($userData, $status, $ti_id=null) {

        $andWhere = '';
        $stmtParams = array(
            'user_id' => $userData['id'],
            'status' => $status
        );

        if(!is_null($ti_id)) {
            $andWhere = 'AND ti.`id` = :ti_id';
            $stmtParams['ti_id'] = $ti_id;
        }

        if($userData['type'] !== 'Super Admin' && $status != TransferInventoryEntity::STATUS_NEW) {
            /*if(count($userData['branchIds'])) {
                $ors = '';
                foreach($userData['branchIds'] as $key => $branchId) {
                    $ors .= (empty($ors) ? '' : ' OR ') . 'ti.`branch_id_to` = :branchId' . $key;
                    $stmtParams['branchId' . $key] = $branchId;
                }
                if(!empty($ors)) {
                    $andWhere .= ' AND (' . $ors . ')';
                }
            } else {
                $andWhere .= ' AND ti.`branch_id_to` < 0';
            }*/
            if(count($userData['departmentIds'])) {
                $ors = '';
                foreach($userData['departmentIds'] as $key => $departmentIds) {
                    $ors .= (empty($ors) ? '' : ' OR ') . 'ti.`department_id` = :departmentId' . $key;
                    $stmtParams['departmentId' . $key] = $departmentIds;
                }
                if(!empty($ors)) {
                    $andWhere .= ' AND (' . $ors . ')';
                }
            } else {
                $andWhere .= ' AND ti.`department_id` < 0';
            }
            /*$andWhere .= "
                AND ti.`branch_id_to` IN (
                    SELECT sau.`branch_id`
                    FROM `status_approval_user` sau
                    LEFT JOIN `status_approval` sa ON sau.`status_approval_id` = sa.`id`
                    WHERE sau.`user_id` = :user_id
                    AND sau.`start_date` <= :startDate
                    AND (sau.`end_date` >= :endDate OR sau.`end_date` IS NULL)
                    AND sa.`description` = CONCAT('Transfer Inventory ', :status)
                )
            ";*/
            $andWhere .= "
                AND ti.`department_id` IN (
                    SELECT sau.`department_id`
                    FROM `status_approval_user` sau
                    LEFT JOIN `status_approval` sa ON sau.`status_approval_id` = sa.`id`
                    WHERE sau.`user_id` = :user_id
                    AND sau.`start_date` <= :startDate
                    AND (sau.`end_date` >= :endDate OR sau.`end_date` IS NULL)
                    AND sa.`description` = CONCAT('Transfer Inventory ', :status)
                )
            ";
            $stmtParams['startDate'] = date('Y-m-d 00:00:00');
            $stmtParams['endDate'] = date('Y-m-d 23:59:59');
        }

        $query = $this->getEntityManager()->getConnection()->prepare("
                SELECT COUNT(DISTINCT ti.`id`) as ctr
                FROM `transfer_inventory` ti
                LEFT JOIN `transfer_inventory_status` tis ON ti.`id` = tis.`transfer_inventory_id` AND tis.`status` = :status AND tis.`batch_no` = ti.`approval_batch_no` AND tis.`user_id` = :user_id
                WHERE ti.`status` = :status
                AND tis.`id` IS NULL
                $andWhere
            ");
        $query->execute($stmtParams);
        $query = $query->fetchAll();

        return isset($query[0]) ? $query[0]['ctr'] : 0;
    }
}
