<?php

namespace RxConnexionBundle\Repository;

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

class CanvassRepository extends EntityRepository
{

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

        $columns = array(
            'pmr.materialRequisitionNo',
            'pmr.referenceNo',
            'pmr.title',
            'pmr.requestDate',
            'eb.description',
            'eu.firstName',
//            'pc.status',
            'pci.quantityAdded',
            'pc.id'
        );
        $dtColumns = array(
            'pmr.materialRequisitionNo as materialRequisition_materialRequisitionNo',
            'pmr.referenceNo as materialRequisition_referenceNo',
            'pmr.title as materialRequisition_title',
            'pmr.requestDate as materialRequisition_requestDate',
            'eb.description as branch_description',
            "CONCAT(eu.firstName, ' ', eu.lastName) as user_fullName",
            'pc.status',
            'pci.quantityAdded as quantityAdded',
            'pc.id'
        );
        $dbColumns = array('COUNT(pci.id) as canvassItems_count');
        $asColumns = array();

        $query = $this->getEntityManager()
            ->getRepository('RxConnexionBundle:CanvassEntity')
            ->createQueryBuilder('pc')
            ->leftJoin('pc.materialRequisition', 'pmr')
            ->leftJoin('pmr.healthFacility', 'eb')
            ->leftJoin('pmr.accountUser', 'eu')
            ->leftJoin('pc.canvassItems', 'pci')
            ->select(array_merge($dtColumns, $dbColumns))
//            ->where('pmr.branch IN (:user_branchIds)')
//            ->where('pc.status IN (:canvassStatusDescriptions)')
            ->setParameters(array(
//                'user_branchIds' => $userData['branchIds'],
//                'canvassStatusDescriptions' => $userData['canvassStatusDescriptions']
            ))
            ->groupBy('pc.id');

//        if(isSet($get['status']) && $get['status'] !== 'all') {
//
//            $query->andWhere('pc.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 ' : '') . '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/canvass/view';

        $hasCanvassViewAccess = $userData['type'] === 'Super Admin' || in_array('Admin Canvass', $userData['accesses']);

        $dateTimeToStringTransformer = new DateTimeToStringTransformer();

        foreach($result as $row) {

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

            $action = $hasCanvassViewAccess ? "<a class='action-button-style' href='$viewUrl/$id'>View</a>" : '';

            $values = array(
                sprintf('%012d', $row['id']),
                $row['materialRequisition_materialRequisitionNo'],
                $row['materialRequisition_referenceNo'],
                $row['materialRequisition_title'],
                date('m/d/Y', strtotime($dateTimeToStringTransformer->transform($row['materialRequisition_requestDate']))),
                $row['branch_description'],
                $row['user_fullName'],
//                $row['status'],
                $row['canvassItems_count'],
                $row['quantityAdded'],
                $action
            );

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

        unset($result);

        return $output;
    }

    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 c.`id`) AS ctr,
                c.`status`
            FROM `canvass` c
            LEFT JOIN `material_requisition` mr ON c.`material_requisition_id` = mr.`id`
            WHERE c.`status` IN ('Supplier Canvassing', 'Pending Purchasing Manager Approval For PO', 'Pending Admin Approval For PO')
            $andWhere
            GROUP BY c.`status`
        ");
        $query->execute($stmtParams);

        return $query->fetchAll();
    }

    public function countForApprovalByUser($userData, $status, $canvass_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($canvass_id)) {
            $andWhere = 'AND c.`id` = :canvass_id';
            $stmtParams['canvass_id'] = $canvass_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 ') . '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 c.`id`) as ctr
                FROM `canvass` c
                LEFT JOIN `material_requisition`mr ON c.`material_requisition_id` = mr.`id`
                LEFT JOIN `canvass_status` cs ON c.`id` = cs.`canvass_id` AND cs.`status` = :status AND cs.`batch_no` = c.`approval_batch_no` AND cs.`user_id` = :user_id
                LEFT JOIN (
                    SELECT
                      sa.`description`,
                      sau.`id`,
                      sau.`user_id`,
                      sau.`branch_id`,
                      sau.`department_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 c.`status` = sau.`description` AND :user_id = sau.`user_id` AND (mr.`branch_id` = sau.`branch_id` OR sau.`branch_id` IS NULL) AND (mr.`department_id` = sau.`department_id` OR sau.`department_id` IS NULL)
                WHERE c.`status` = :status
                AND cs.`id` IS NULL
                $andWhere
            ");
        $query->execute($stmtParams);
        $query = $query->fetchAll();

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