<?php

namespace RxConnexionBundle\Repository;

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

class MaterialRequisitionNoteRepository extends EntityRepository
{
    public function validate($materialRequisitionNote_form) {

        $errors = array();

        $action = $materialRequisitionNote_form['action'];

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

        }

        return $errors;
    }

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

        $columns = array(
            'pmr.materialRequisitionNo',
            'pmr.referenceNo',
            'pmr.title',
            'pmr.requestDate',
            'eb.description',
            'd.description',
            'eu.firstName',
            'pmr.status',
            'pmri.quantityAdded',
            'pmr.id'
        );
        $dtColumns = array(
            'pmr.materialRequisitionNo',
            'pmr.referenceNo',
            'pmr.title',
            'pmr.requestDate',
            'eb.description as branch_description',
            'd.description as department_description',
            "CONCAT(eu.firstName, ' ', eu.lastName) as user_fullName",
            'pmr.status',
            'SUM(pmri.quantityAdded) as quantityAdded',
            'pmr.id'
        );
        $dbColumns = array();
        $asColumns = array();

        $query = $this->getEntityManager()
            ->getRepository('RxConnexionBundle:MaterialRequisitionEntity')
            ->createQueryBuilder('pmr')
            ->leftJoin('pmr.branch', 'eb')
            ->leftJoin('pmr.department', 'd')
            ->leftJoin('pmr.user', 'eu')
            ->leftJoin('RxConnexionBundle:MaterialRequisitionItemEntity','pmri' ,'WITH' ,'pmr.id=pmri.materialRequisition')
            ->select(array_merge($dtColumns, $dbColumns))
            ->where('pmr.branch IN (:user_branchIds)')
            ->andWhere('pmr.department IN (:user_departmentIds)')
            ->andWhere('pmr.status IN (:materialRequisitionStatusDescriptions)')
            ->setParameters(array(
                'user_branchIds' => $userData['branchIds'],
                'user_departmentIds' => $userData['departmentIds'],
                'materialRequisitionStatusDescriptions' => $userData['materialRequisitionStatusDescriptions']
            ))
            ->groupBy('pmr.id');

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

            $query->andWhere('pmr.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/material_requisition/form';
        $viewUrl = $url . 'admin/material_requisition/view';
        $materialRequisitionItemUrl = $url . 'admin/material_requisition/item/index';

        $hasUpdate = $userData['type'] === 'Super Admin' || in_array('Admin Material Requisition Update', $userData['accesses']);
        $hasMaterialRequisitionItemAccess = $userData['type'] === 'Super Admin' || in_array('Admin Material Requisition Item', $userData['accesses']);
        $hasMaterialRequisitionViewAccess = $userData['type'] === 'Super Admin' || in_array('Admin Material Requisition', $userData['accesses']);

        $dateTimeToStringTransformer = new DateTimeToStringTransformer();

        foreach($result as $row) {

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

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

            if($row['status'] === 'New' ||
                ($row['status'] === 'Pending Branch Manager Approval' && ($userData['type'] === 'Branch Manager' || $userData['type'] === 'Admin')) ||
                ($row['status'] === 'Pending Admin Approval' && $userData['type'] === 'Admin')) {

                if($hasUpdate)
                    $action .= "<a class='action-button-style' href='$formUrl/u/$id'>Update</a>";
                if($hasMaterialRequisitionItemAccess)
                    $action .= "<a class='action-button-style' href='$materialRequisitionItemUrl/$id'>Items</a>";
            }

            $values = array(
                $row['materialRequisitionNo'],
                $row['referenceNo'],
                $row['title'],
                date('m/d/Y', strtotime($dateTimeToStringTransformer->transform($row['requestDate']))),
                $row['branch_description'],
                $row['department_description'],
                $row['user_fullName'],
                $row['status'],
                $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 mr.`id`) AS ctr,
                mr.`status`
            FROM `material_requisition` mr
            WHERE mr.`status` IN ('New', 'Pending Purchasing Manager Approval', 'Pending Admin Approval', 'Active')
            $andWhere
            GROUP BY mr.`status`
        ");
        $query->execute($stmtParams);

        return $query->fetchAll();
    }

    public function countForApprovalByUser($userData, $status, $mr_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($mr_id)) {
            $andWhere = 'AND mr.`id` = :mr_id';
            $stmtParams['mr_id'] = $mr_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 mr.`id`) as ctr
                FROM `material_requisition` mr
                LEFT JOIN `material_requisition_status` mrs ON mr.`id` = mrs.`material_requisition_id` AND mrs.`status` = :status AND mrs.`batch_no` = mr.`approval_batch_no` AND mrs.`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 mr.`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 mr.`status` = :status
                AND mrs.`id` IS NULL
                $andWhere
            ");
        $query->execute($stmtParams);
        $query = $query->fetchAll();

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




}