<?php

namespace RxConnexionBundle\Repository;

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

class ConvertInventoryRepository extends EntityRepository
{
    public function validate($convertInventory_form) {

        $errors = array();

        $action = $convertInventory_form['action'];

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

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

            if(empty($convertInventory_form['healthFacility']))
                $errors[] = 'Please select branch.';
        }

        return $errors;
    }

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

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

        $query = $this->getEntityManager()
            ->getRepository('RxConnexionBundle:ConvertInventoryEntity')
            ->createQueryBuilder('iui')
            ->leftJoin('iui.healthFacility', 'eb')
            ->select(array_merge($dtColumns, $dbColumns));

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

            $query->andWhere('iui.status = :status')
                ->setParameter('status', $get['status']);
        }

        if('Super Admin' !== $userData['type']) {
            if (isset($userData['branches']) && count($userData['branches'])) {
                $ors = '';
                foreach ($userData['branches'] as $key => $branchId) {
                    $ors .= (!empty($ors) ? ' OR ' : '') . 'iui.healthFacility = :branch_id_' . $key;
                    $query->setParameter("branch_id_$key", $branchId);
                }
                $query->andWhere("($ors)");
            } else { // Don't show anything
                $query->andWhere("iui.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'];
        $formUrl = $url . '/admin/convert_inventory/form';
        $convertInventoryItemUrl = $url . '/admin/convert_inventory/item/index';

        $hasUpdate = $userData['type'] === 'Super Admin' || in_array('Admin Convert Inventory Update', $userData['accesses']);
        $hasConvertInventoryItemAccess = $userData['type'] === 'Super Admin' || in_array('Admin Convert 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($hasConvertInventoryItemAccess)
                $action .= "<a class='action-button-style' href='$convertInventoryItemUrl/$id'>Details</a>";

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

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

        unset($result);

        return $output;
    }

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

        $andWhere = '';
        $stmtParams = array(
            'user_id' => $userData['id'],
            'status' => $status,
            'startDate' => date('Y-m-d 00:00:00'),
            'endDate' => date('Y-m-d 23:59:59')
        );

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

        if($userData['type'] !== 'Super Admin') {
            $andWhere .= ' AND sau.`id` IS NOT NULL';
            if(count($userData['branchIds'])) {
                $ors = '';
                foreach($userData['branchIds'] as $key => $branchId) {
                    $ors .= (empty($ors) ? '' : ' OR ') . 'ci.`branch_id` = :branchId' . $key;
                    $stmtParams['branchId' . $key] = $branchId;
                }
                if(!empty($ors)) {
                    $andWhere .= ' AND (' . $ors . ')';
                }
            } else {
                $andWhere .= ' AND ci.`branch_id` < 0';
            }
        }

        $query = $this->getEntityManager()->getConnection()->prepare("
                SELECT COUNT(DISTINCT ci.`id`) as ctr
                FROM `convert_inventory` ci
                LEFT JOIN `convert_inventory_status` cis ON ci.`id` = cis.`convert_inventory_id` AND cis.`status` = :status AND cis.`batch_no` = ci.`approval_batch_no` AND cis.`user_id` = :user_id
                LEFT JOIN (
                    SELECT
                      sa.`description`,
                      sau.`id`,
                      sau.`user_id`,
                      sau.`branch_id`
                    FROM `status_approval_user` sau
                    LEFT JOIN `status_approval` sa ON sau.`status_approval_id` = sa.`id`
                    WHERE sau.`start_date` <= :startDate
                    AND (sau.`end_date` IS NULL OR sau.`end_date` >= :endDate)
                ) sau ON CONCAT('Convert Inventory ', ci.`status`) = sau.`description` AND :user_id = sau.`user_id` AND (ci.`branch_id` = sau.`branch_id` OR sau.`branch_id` IS NULL)
                WHERE ci.`status` = :status
                AND cis.`id` IS NULL
                $andWhere
            ");
        $query->execute($stmtParams);
        $query = $query->fetchAll();

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

    public function autoCompleteSuggestions($q, $userData) {

        $stmtParams = array(
            'description' => "%$q%"
        );
        $andWhere = '';
        if(isset($userData['branchIds']) && count($userData['branchIds'])) {
            $ors = '';
            foreach($userData['branchIds'] as $key => $branchId) {
                $ors .= (empty($ors) ? '' : ' OR ') . 'ci.`branch_id` = :branchId' . $key;
                $stmtParams['branchId'.$key] = $branchId;
            }
            if(!empty($ors))
                $andWhere .= ' AND (' . $ors . ')';
        }

        $sql = "
            SELECT
                ci.`id`,
                LPAD(ci.`id`, 12, 0) AS data,
                LPAD(ci.`id`, 12, 0) AS value
            FROM `convert_inventory` ci
            WHERE LPAD(ci.`id`, 12, 0) LIKE :description
            $andWhere
            ORDER BY ci.`id` DESC
            LIMIT 0,20
        ";

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

        $query->execute($stmtParams);

        $result = $query->fetchAll();

        return $result;
    }
}