<?php

namespace RxConnexionBundle\Repository;

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

class MaterialRequisitionRepository extends EntityRepository
{
    public function validate($materialRequisition_form) {

        $errors = array();

        $action = $materialRequisition_form['action'];

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

            if(empty($materialRequisition_form['request_date'])) {
                $errors[] = 'Request date Description should not be blank.';
            }

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

//            if(empty($materialRequisition_form['department'])) {
//                $errors[] = 'Please select department.';
//            }
//
//            if(empty($materialRequisition_form['purpose'])) {
//                $errors[] = 'Please select purpose.';
//            }
        }

        return $errors;
    }

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

        $columns = array(
            array('mr.`material_requisition_no`', "mr.`material_requisition_no`", 'mrNo'),
            array('mr.`request_date`', "DATE_FORMAT(mr.`request_date`, '%m/%d/%Y')", 'requestDate'),
            array('b.`description`', "b.`description`", 'branchDesc'),
//            array('d.`description`', "d.`description`", 'departmentDesc'),
            array('p.`description`', "p.`description`", 'purposeDesc'),
//            array('mr.`specific_purpose`', "mr.`specific_purpose`", 'specificPurpose'),
            array('u.`first_name`', "CONCAT_WS(' ', u.`first_name`, u.`last_name`)", 'userFullname'),
//            array('mr.`status`', "mr.`status`"),
            array('mri.itemCtr', "mri.itemCtr"),
            array('mr.`id`', "mr.`id`")
        );
        $asColumns = array();

        $select = "SELECT";
        $from = "FROM `material_requisition` mr";
        $joins = "
            LEFT JOIN `health_facility` b ON mr.`health_facility_id` = b.`id`
            -- LEFT JOIN `department` d ON mr.`department_id` = d.`id`
            LEFT JOIN `account_user` u ON mr.`account_user_id` = u.`id`
            LEFT JOIN `purpose` p on mr.`purpose_id` = p.`id`
            LEFT JOIN `material_requisition_item_tmp` mri ON mr.`id` = mri.`material_requisition_id`
        ";
        $sqlWhere = "";
        $groupBy = "";
        $orderBy = "";
        $limit = "";
        $stmtParams = array();

        if('Super Admin' !== $userData['type']) {

            if(count($userData['branches'])) {
                $ors = '';
                foreach($userData['branches'] as $key => $branchId) {
                    $ors .= (!empty($ors) ? ' OR ' : '') . 'mr.`health_facility_id` = :branch_id_' . $key;
                    $stmtParams['branch_id_' . $key] = $branchId;
                }
                $sqlWhere .= (empty($sqlWhere) ? 'WHERE ' : ' AND ') . "($ors)";
            } else { // Don't show anything
                $sqlWhere .= (empty($sqlWhere) ? 'WHERE ' : ' AND ') . "mr.`health_facility_id` < 0";
            }

//            if(count($userData['departmentIds'])) {
//                $ors = '';
//                foreach($userData['departmentIds'] as $key => $departmentId) {
//                    $ors .= (!empty($ors) ? ' OR ' : '') . 'mr.`department_id` = :department_id_' . $key;
//                    $stmtParams['department_id_' . $key] = $departmentId;
//                }
//                $sqlWhere .= (empty($sqlWhere) ? 'WHERE ' : ' AND ') . "($ors)";
//            } else { // Don't show anything
//                $sqlWhere .= (empty($sqlWhere) ? 'WHERE ' : ' AND ') . "mr.`department_id` < 0";
//            }
        }

        if(isset($get['status']) && 'ALL' !== strtoupper($get['status'])) {
            if(strtoupper($get['status']) === "Active"){
                $sqlWhere .= (empty($sqlWhere) ? 'WHERE ' : ' AND ') . 'mr.`status` NOT IN (:status1, :status2)';
                $stmtParams['status1'] = "Voided";
                $stmtParams['status2'] = "Closed";
            } else {
                $sqlWhere .= (empty($sqlWhere) ? 'WHERE ' : ' AND ') . 'mr.`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') {
                    if(1 === $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 `material_requisition_item_tmp` (
                INDEX `IDX_TMP_000AAA` (`material_requisition_id`)
            ) AS (
                SELECT
                    `material_requisition_id`,
                    COUNT(DISTINCT `id`) AS itemCtr
                FROM `material_requisition_item`
                GROUP BY `material_requisition_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/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']);

        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') {
//
//                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>";
//            }

            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['mrNo'],
                $row['requestDate'],
                $row['branchDesc'],
//                $row['departmentDesc'],
                $row['purposeDesc'],
//                $row['specificPurpose'],
                $row['userFullname'],
//                $row['status'],
                $row['itemCtr'],
                $action
            );

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

        unset($result);

        return $output;
    }

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

        $columns = array(
            array('mr.`material_requisition_no`', "mr.`material_requisition_no`", 'mrNo'),
            array('mr.`request_date`', "DATE_FORMAT(mr.`request_date`, '%m/%d/%Y')", 'requestDate'),
            array('b.`description`', "b.`description`", 'branchDesc'),
            array('d.`description`', "d.`description`", 'departmentDesc'),
            array('p.`description`', "p.`description`", 'purposeDesc'),
            array('mr.`specific_purpose`', "mr.`specific_purpose`", 'specificPurpose'),
            array('u.`first_name`', "CONCAT_WS(' ', u.`first_name`, u.`last_name`)", 'userFullname'),
            array('mr.`status`', "mr.`status`"),
            array('mri.itemCtr', "mri.itemCtr"),
            array('mr.`id`', "mr.`id`")
        );
        $asColumns = array();

        $select = "SELECT";
        $from = "FROM `material_requisition` mr";
        $joins = "
            LEFT JOIN `branch` b ON mr.`branch_id` = b.`id`
            LEFT JOIN `department` d ON mr.`department_id` = d.`id`
            LEFT JOIN `user` u ON mr.`user_id` = u.`id`
            LEFT JOIN `purpose` p on mr.`purpose_id` = p.`id`
            LEFT JOIN `material_requisition_item_tmp` mri ON mr.`id` = mri.`material_requisition_id`
        ";
        $sqlWhere = "";
        $groupBy = "";
        $orderBy = "";
        $limit = "";
        $stmtParams = array();

        if('Super Admin' !== $userData['type']) {

            if(count($userData['branchIds'])) {
                $ors = '';
                foreach($userData['branchIds'] as $key => $branchId) {
                    $ors .= (!empty($ors) ? ' OR ' : '') . 'mr.`branch_id` = :branch_id_' . $key;
                    $stmtParams['branch_id_' . $key] = $branchId;
                }
                $sqlWhere .= (empty($sqlWhere) ? 'WHERE ' : ' AND ') . "($ors)";
            } else { // Don't show anything
                $sqlWhere .= (empty($sqlWhere) ? 'WHERE ' : ' AND ') . "mr.`branch_id` < 0";
            }

            if(count($userData['departmentIds'])) {
                $ors = '';
                foreach($userData['departmentIds'] as $key => $departmentId) {
                    $ors .= (!empty($ors) ? ' OR ' : '') . 'mr.`department_id` = :department_id_' . $key;
                    $stmtParams['department_id_' . $key] = $departmentId;
                }
                $sqlWhere .= (empty($sqlWhere) ? 'WHERE ' : ' AND ') . "($ors)";
            } else { // Don't show anything
                $sqlWhere .= (empty($sqlWhere) ? 'WHERE ' : ' AND ') . "mr.`department_id` < 0";
            }
        }

        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(1 === $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 `material_requisition_item_tmp` (
                INDEX `IDX_TMP_000AAA` (`material_requisition_id`)
            ) AS (
                SELECT
                    `material_requisition_id`,
                    COUNT(DISTINCT `id`) AS itemCtr
                FROM `material_requisition_item`
                GROUP BY `material_requisition_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()
        );

        foreach($result as $row) {

            $values = array(
                $row['mrNo'],
                $row['requestDate'],
                $row['branchDesc'],
                $row['departmentDesc'],
                $row['purposeDesc'],
                $row['specificPurpose'],
                $row['userFullname'],
                $row['status'],
                $row['itemCtr'],
                'DT_DATA' => array(
                    'id' => $row['id'],
                    'mrNo' => $row['mrNo'],
                    'requestDate' => $row['requestDate'],
                    'branchDesc' => $row['branchDesc'],
                    'departmentDesc' => $row['departmentDesc'],
                    'purposeDesc' => $row['purposeDesc'],
                    'specificPurpose' => $row['specificPurpose']
                )
            );

            $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;
    }




}