<?php

namespace RxConnexionBundle\Repository;

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

        $errors = array();

        $action = $patientInsurance_form['action'];
        if($action !== 'd') {
                /*$activeRhf = $this->getEntityManager()->getConnection()->prepare("
                SELECT `id`
                FROM `patient_insurance` prhf 
                WHERE prhf.`end_date` IS NULL
                AND prhf.`patient_id` = :patientId
                AND prhf.`id` != :id 
                LIMIT 1
            ");
                $activeRhf->execute(array(
                    'patientId' => base64_decode($patientInsurance_form['patient']),
                    'id' => $patientInsurance_form['id']
                ));
                $activeRhf = $activeRhf->fetchAll();
                if(isset($activeRhf[0]) && $patientInsurance_form['end_date'] === '') {
                    $errors[] = 'There is still an active insurance.';
                }*/
            if($patientInsurance_form['insurance'] == null){
                $errors[] = 'Please choose insurance';
            }
        }

        /*if($patientInsurance_form['insurance_no']==null){
            $errors[] = 'Please enter insurance no.';
        }
        if($patientInsurance_form['start_date']==null){
            $errors[] = 'Please enter start date';
        }*/


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

            $insuranceExist = $this->getEntityManager()->getRepository('RxConnexionBundle:PatientInsuranceEntity')
                ->createQueryBuilder('d')
                ->where('d.id != :id')
                ->andWhere('d.patient = :patient')
                ->andWhere('d.insurance = :insurance')
                ->andWhere('d.isDeleted = 0')
                ->setParameters(array(
                    'id' => $patientInsurance_form['id'],
                    'patient' => base64_decode($patientInsurance_form['patient']),
                    'insurance' => $patientInsurance_form['insurance']
                ))
                ->getQuery()->getResult();

//            if($insuranceExist)
//                $errors[] = 'Insurance already exists to the patient.';


            /*$overlapSql = "SELECT * FROM `patient_insurance` pi  WHERE pi.is_deleted != 1 AND  pi.`patient_id` = :patient AND  pi.`id` != :id ";
            $overlapParams = array(
                'id' => ($patientInsurance_form['id']),
                'patient' => base64_decode($patientInsurance_form['patient']),
                'startdate' => date('Y-m-d 00:00:00', strtotime($patientInsurance_form['start_date'])),
            );

            if($patientInsurance_form['end_date'] == ''){
                $overlapSql .= " AND (
                                (pi.`start_date` <= :startdate AND :startdate < pi.`end_date`) OR
                                (:startdate >= pi.`start_date` AND pi.`end_date` IS NULL)
                              )";
            } else {
                $overlapSql .= " AND (
                      (pi.`start_date` <= :startdate AND :startdate < pi.`end_date`) OR
                      (:startdate >= pi.`start_date` && pi.`end_date` IS NULL) OR
                      (:enddate > pi.`start_date` && :enddate <= pi.`end_date`) OR
                      (:enddate > pi.`start_date` && pi.`end_date` IS NULL)
                  )";
                $overlapParams['enddate'] = date('Y-m-d 00:00:00', strtotime($patientInsurance_form['end_date']));
            }


            $overlapQuery = $this->getEntityManager()->getConnection()->prepare($overlapSql);
            $overlapQuery->execute($overlapParams);
            $overlapCount = $overlapQuery->fetchAll();
            if(count($overlapCount) > 0){
                $errors[] = 'Start date or End date should not overlap other Insurance';
            }*/

        }

        return $errors;
    }

    public function ajax_list(array $get){

        $columns = array(
            array('i.`description`', 'i.`description`', 'insurance_desc'),
            array('pi.`insurance_no`', 'pi.`insurance_no`'),
            array('pi.`plan_contact_no`', 'pi.`plan_contact_no`'),
            array('i.`fax_no`', 'i.`fax_no`'),
            array('i.`phone_no`', 'i.`phone_no`'),
            array('i.`mobile_no`', 'i.`mobile_no`'),
            array("DATE_FORMAT(pi.`expire_date`, '%Y/%m')", "DATE_FORMAT(pi.`expire_date`, '%Y/%m')", 'expire_date'),
            array("DATE_FORMAT(pi.`start_date`, '%m/%d/%Y')", "DATE_FORMAT(pi.`start_date`, '%m/%d/%Y')", 'start_date'),
            array("DATE_FORMAT(pi.`end_date`, '%m/%d/%Y')", "DATE_FORMAT(pi.`end_date`, '%m/%d/%Y')", 'end_date'),
            array('pi.`id`', "pi.`id`")
        );
        $asColumns = array(
        );

        $select = "SELECT";
        $from = "FROM `patient_insurance` pi";
        $joins = "LEFT JOIN `insurance` i ON pi.`insurance_id` = i.`id`";
        $sqlWhere = "WHERE pi.`patient_id` = :patient_id";
        $sqlWhere .= " AND pi.`is_deleted` = 0";
        $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 insuranceCoverage($params) {
        $sqlWhere = "WHERE p.`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 ") . "pb.`billing_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.`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['branchAddress']) && !empty($params['branchAddress']) && 'NULL' !== strtoupper($params['branchAddress'])){
            $branches = explode(',' , $params['branchAddress']);
            if(count($branches) > 0){
                $hf_ors = '';
                foreach($branches as $key => $branchId){
                    $hf_ors .= (empty($hf_ors) ? '' : ' OR ') . "pb.`health_facility_for_address_id` = :healthFacilityAddress_id_$key";
                    $stmtParams["healthFacilityAddress_id_$key"] = $branchId;
                }
                $sqlWhere .= " AND ($hf_ors) ";
            }
        }

        //USER ACCESS ON BRANCH
        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_for_address_id` = $branchId";
                        }
                        $sqlWhere .= (empty($andWhere) ? " AND " : "") . " ($hf_ors) ";
                    } else {
                        $sqlWhere .= (empty($andWhere) ? " AND " : "") . " (1 != 1) ";
                    }
                }
            }
        }

        $sql = "SELECT 
                    p.`id` AS patientId,
                    p.`full_name` AS patientName,
                    co.`description` AS companyDesc,
                    hf1.`description` AS branch,
                    hf2.`description` AS branchAddress,
                    i.`description` AS insuranceDesc,
                    it.`description` AS itemDesc,
                    pbb.`frequency` AS frequency,
                    pbb.`benefit_period` AS benefitPeriod,
                    pbb.`amount_covered` AS amtCovered,
                    pbb.`invoice_amount` AS amt
                FROM `patient_billing` pb
                LEFT JOIN `patient` p ON pb.`patient_id` = p.`id`
                LEFT JOIN `patient_health_facility` phf ON phf.`id` = (
                    SELECT phf2.`id`
                    FROM `patient_health_facility` phf2
                    WHERE phf2.`patient_id` = p.`id`
                    AND phf2.`start_date` IS NOT NULL
                    AND phf2.`end_date` IS NULL
                    ORDER BY phf2.`start_date` DESC
                    LIMIT 1
                )
                LEFT JOIN `health_facility` hf ON phf.`health_facility_id` = hf.`id`
                LEFT JOIN `health_facility` hf1 ON pb.`health_facility_id` = hf1.`id`
                LEFT JOIN `health_facility` hf2 ON pb.`health_facility_for_address_id` = hf2.`id`
                LEFT JOIN `company` co ON hf2.`company_id` = co.`id`
                LEFT JOIN `patient_insurance` pins ON pins.`id` = (
                    SELECT pins1.`id` 
                    FROM `patient_insurance` pins1
                    WHERE pins1.`is_deleted` = 0
                    AND pins1.`patient_id` = pb.`patient_id`
                    AND pins1.`start_date` IS NOT NULL
                    AND pins1.`end_date` IS NULL
                    LIMIT 1
                ) 
                LEFT JOIN `insurance` i ON i.`id` = pins.`insurance_id`
                LEFT JOIN `patient_billing_breakdown` pbb ON pbb.`id` = (
					 	SELECT pbb1.`id`
					 	FROM `patient_billing_breakdown` pbb1
					 	WHERE pbb1.`is_deleted` = 0
					 	AND pbb1.`patient_billing_id` = pb.`id`
					 	LIMIT 1
					 )
                LEFT JOIN `item` it ON pbb.`item_id` = it.`id`
                $sqlWhere
                AND pb.`billing_status` != 'Void'
                AND pb.`payer_type` = 'Insurance'
                AND hf.`description` NOT IN('DemoLocation', 'test', 'Demo_Test')
                AND hf1.`description` NOT IN('DemoLocation', 'test', 'Demo_Test')
                AND hf2.`description` NOT IN('DemoLocation', 'test', 'Demo_Test')
                AND (pbb.`price_covered` != '' OR pbb.`price_covered` != 0.00)
                AND (pbb.`amount_covered` != '' OR pbb.`amount_covered` != 0.00)
                AND p.`is_duplicate` = 0
                AND p.`is_test_patient` = 0";

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

        $query->execute($stmtParams);
        $result = $query->fetchAll();

        return $result;
    }

    public function autocomplete_suggestions($q) {

        if(is_numeric($q['patient_id'])) {
            $patient_id = $q['patient_id'];
        } else {
            $patient_id = base64_decode($q['patient_id']);
        }

        $andWhere = '';
        $stmtParams = array(
            'description' => "%{$q['query']}%",
            'patient_id' => $patient_id
        );

        if(isset($q['refDate'])) {
            $andWhere .= ' 
                AND prp.`start_date` <= :refDate
                AND (prp.`end_date` IS NULL OR prp.`end_date` >= :refDate)
            ';
            $stmtParams['refDate'] = date('Y-m-d 00:00:00', strtotime($q['refDate']));
        }

        $sql = "
            SELECT
                prp.`id`,
                CONCAT_WS(' - ', prp.`insurance_no` ,rp.`description`) AS data,
                CONCAT_WS(' - ', prp.`insurance_no` ,rp.`description`) AS value
            FROM `patient_insurance` prp
            LEFT JOIN `insurance` rp ON prp.`insurance_id` = rp.`id`
            WHERE rp.`description` LIKE :description
            AND prp.`end_date` IS NULL
            AND prp.`patient_id` = :patient_id
            AND prp.`is_deleted` = 0
            $andWhere
            ORDER BY rp.`description`
            LIMIT 0,20
        ";

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

        $query->execute($stmtParams);

        $result = $query->fetchAll();

        return $result;
    }
}
