<?php

namespace RxConnexionBundle\Repository;

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

        $errors = array();

        $action = $patientBillingRefund_form['action'];

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

//            $cityExist = $this->getEntityManager()->getRepository('RxConnexionBundle:PatientBillingRefundEntity')
//                ->createQueryBuilder('ep')
//                ->where('ep.id != :id')
//                ->andWhere('ep.description = :description')
//                ->andWhere('ep.province = :province_id')
//                ->andWhere('ep.isDeleted = 0')
//                ->setParameters(array(
//                    'id' => $city_form['id'],
//                    'description' => $city_form['description'],
//                    'province_id' => $city_form['province']
//                ))
//                ->getQuery()->getResult();

//            if($cityExist)
//                $errors[] = 'Description already exist.';

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

            if(empty($patientBillingRefund_form['amount']))
                $errors[] = 'Amount should not be blank.';

            if(empty($patientBillingRefund_form['note']))
                $errors[] = 'Note should not be blank.';
        }

        return $errors;
    }

    public function ajax_list(array $get){

        $columns = array(
            array('pb.`invoice_no`', 'pb.`invoice_no`', 'invoiceNo'),
            array('DATE_FORMAT(pbr.`refund_date`, "%m/%d/%Y")', 'DATE_FORMAT(pbr.`refund_date`, "%m/%d/%Y")', 'refundDate'),
            array('pbr.`amount`', 'pbr.`amount`'),
            array("CONCAT('[ ' , DATE_FORMAT(pbr.`created_at`, '%m/%d/%Y %h:%i %p'), ' - ', pbr.`created_by`, ' ] : ', pbr.`note`)", "CONCAT('[ ' , DATE_FORMAT(pbr.`created_at`, '%m/%d/%Y %h:%i %p'), ' - ', pbr.`created_by`, ' ] : ', pbr.`note`)", 'note'),
            array('pbr.`id`', "pbr.`id`")
        );
        $asColumns = array();

        $select = "SELECT";
        $from = "FROM `patient_billing_refund` pbr";
        $joins = "LEFT JOIN `patient_billing` pb ON pbr.`patient_billing_id` = pb.`id`";
        $sqlWhere = "WHERE pbr.`is_deleted` = 0";
        $sqlWhere .= " AND pbr.`patient_id` = :patient_id";
        $groupBy = "";
        $orderBy = "";
        $limit = "";
        $stmtParams = array(
            'patient_id' => base64_decode($get['patient_id'])
        );

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

        $sql = "$select $from $joins $sqlWhere $groupBy $orderBy";
        $query = $this->getEntityManager()->getConnection()->prepare($sql);
        $query->execute($stmtParams);
        $result_count = $query->fetchAll();

        $sql = "$select $from $joins $sqlWhere $groupBy $orderBy $limit";
        $query = $this->getEntityManager()->getConnection()->prepare($sql);
        $query->execute($stmtParams);
        $result = $query->fetchAll();

        return array(
            'results' => $result,
            'total' => count($result_count)
        );
    }

    public function reportRefund($params) {
        $sqlWhere = "WHERE pbr.`is_deleted` = 0";
        $stmtParams = array();

        if (!is_null($params['date_from']) && $params['date_from'] !== 'null' && $params['date_from'] !== 'all' && !empty($params['date_from']) && !is_null($params['date_to']) && $params['date_to'] !== 'null' && $params['date_to'] !== 'all' && !empty($params['date_to'])) {
            $sqlWhere .= (empty($sqlWhere) ? "WHERE " : " AND ") . "pbr.`refund_date` BETWEEN :date_from AND :date_to";
            $stmtParams['date_from'] = date('Y-m-d 00:00:00', strtotime(str_replace('-',  '/', $params['date_from'])));
            $stmtParams['date_to'] = date('Y-m-d 23:59:59', strtotime(str_replace('-', '/', $params['date_to'])));
        }

        if(isset($params['company']) && !empty($params['company']) && 'NULL' !== strtoupper($params['company'])){
            $companies = explode(',' , $params['company']);
            if(count($companies) > 0){
                $co_ors = '';
                foreach($companies as $key => $companyId){
                    $co_ors .= (empty($co_ors) ? '' : ' OR ') . "hf_pb.`company_id` = :company_id_$key";
                    $stmtParams["company_id_$key"] = $companyId;
                }
                $sqlWhere .= " AND ($co_ors) ";
            }
        }

        if(isset($params['branch']) && !empty($params['branch']) && 'NULL' !== strtoupper($params['branch'])){
            $branches = explode(',' , $params['branch']);
            if(count($branches) > 0){
                $hf_ors = '';
                foreach($branches as $key => $branchId){
                    $hf_ors .= (empty($hf_ors) ? '' : ' OR ') . "pb.`health_facility_id` = :healthFacility_id_$key";
                    $stmtParams["healthFacility_id_$key"] = $branchId;
                }
                $sqlWhere .= " AND ($hf_ors) ";
            }
        }

        if(isset($params['patient']) && !empty($params['patient']) && 'NULL' !== strtoupper($params['patient'])) {
            $sqlWhere .= (empty($sqlWhere) ? "WHERE " : " AND ") . "pb.`patient_id` = :patient";
            $stmtParams['patient'] = $params['patient'];
        }

        if(isset($params['status']) && !empty($params['status']) && 'NULL' !== strtoupper($params['status'])) {
            $sqlWhere .= (empty($sqlWhere) ? "WHERE " : " AND ") . "pb.`billing_status` = :status";
            $stmtParams['status'] = $params['status'];
        }

        if($params['company'] == 'null' && $params['branch'] == 'null') {
            if(!is_null($params['userData']) && !empty($params['userData'])) {
                if ($params['userData']['type'] != 'Super Admin') {
                    if (count($params['userData']['company']['companyBranches']) > 0) {
                        $hf_ors = '';
                        foreach ($params['userData']['company']['companyBranches'] as $key => $branchId) {
                            $hf_ors .= (empty($hf_ors) ? '' : ' OR ') . "pb.`health_facility_id` = $branchId";
                        }
                        $sqlWhere .= (empty($andWhere) ? " AND " : "") . " ($hf_ors) ";
                    } else {
                        $sqlWhere .= (empty($andWhere) ? " AND " : "") . " (1 != 1) ";
                    }
                }
            }
        }

        $sql = "SELECT 
                    pb.`invoice_no` AS invoiceNo, 
                    DATE_FORMAT(pbr.`refund_date`, '%m/%d/%Y') AS refundDate,
                    pb.`patient_id` AS patientId,
                    p.`full_name` AS patientName,
                    hf_pb.`description` AS healthFacility,
                    hf_add.`description` AS healthFacilityAddress,
                    pb.`amount_due` AS amountDue,
                    pb.`amount_paid` AS amountPaid,
                    pb.`amount_balance` AS amountBalance,
                    pb.`amount_refunded` AS amountRefund,
                    CONCAT('[ ' , DATE_FORMAT(pbr.`created_at`, '%m/%d/%Y %h:%i %p'), ' - ', pbr.`created_by`, ' ] : ', pbr.`note`) AS note
                FROM `patient_billing_refund` pbr
                LEFT JOIN `patient_billing` pb ON pbr.`patient_billing_id` = pb.`id`
                LEFT JOIN `health_facility` hf_pb ON pb.`health_facility_id` = hf_pb.`id` 
                LEFT JOIN `company` co ON hf_pb.`company_id` = co.`id`
                LEFT JOIN `health_facility` hf_add ON pb.`health_facility_for_address_id` = hf_add.`id` 
                LEFT JOIN `patient` p ON pb.`patient_id` = p.`id`
                $sqlWhere
                AND hf_pb.`description` NOT IN('DemoLocation', 'test', 'Demo_Test')
                AND hf_add.`description` NOT IN('DemoLocation', 'test', 'Demo_Test')
                AND pb.`amount_due` != 0
                AND p.`is_test_patient` != 1
                ORDER BY pb.`billing_date` DESC
                ";

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

        $result = $query->fetchAll();

        return $result;
    }

    public function autocomplete_suggestions($q)
    {
        $sql = "
            SELECT
                pb.`id`,
                CONCAT_WS(' - ', pb.`invoice_no`, DATE_FORMAT(pbr.`refund_date`, '%Y/%m/%d'), pbr.`amount`) AS data,
                CONCAT_WS(' - ', pb.`invoice_no`, DATE_FORMAT(pbr.`refund_date`, '%Y/%m/%d'), pbr.`amount`) AS value,
                pb.`billing_status` AS billingStatus,
                pbr.`amount` AS amountDue
            FROM `patient_billing_refund` pbr
            LEFT JOIN `patient_billing` pb ON pbr.`patient_billing_id` = pb.`id`
            WHERE pb.`invoice_no` LIKE :description
            AND pb.`is_deleted` = 0
            AND (pb.`invoice_no` IS NOT NULL OR pb.`invoice_no` != '')
            ORDER BY pb.`invoice_no`
            LIMIT 0,20
        ";

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

        $query->execute(array(
            'description' => "%$q%"
        ));

        $result = $query->fetchAll();

        return $result;
    }
}
