<?php

namespace RxConnexionBundle\Repository;

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

        $errors = array();

        $action = $diagnosis_form['action'];

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

            $diagnosisExist = $this->getEntityManager()->getRepository('RxConnexionBundle:DiagnosisEntity')
                ->createQueryBuilder('d')
                ->where('d.id != :id')
                ->andWhere('d.description = :description')
                ->andWhere('d.diagnosisType = :diagnosisType')
                ->andWhere('d.isDeleted = 0')
                ->setParameters(array(
                    'id' => $diagnosis_form['id'],
                    'description' => $diagnosis_form['description'],
                    'diagnosisType' => $diagnosis_form['diagnosis_type']
                ))
                ->getQuery()->getResult();

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

            if(empty($diagnosis_form['description']))
                $errors[] = 'Description should not be blank.';
        }

        return $errors;
    }

    public function ajax_list(array $get){

        $columns = array(
            array('dt.`description`', 'dt.`description`', 'diagnosis_type_desc'),
            array('d.`code`', 'd.`code`'),
            array('d.`description`', 'd.`description`'),
            array('d.`id`', "d.`id`")
        );
        $asColumns = array();

        $select = "SELECT";
        $from = "FROM `diagnosis` d";
        $joins = "LEFT JOIN `diagnosis_type` dt ON d.`diagnosis_type_id` = dt.`id`";
        $sqlWhere = "WHERE d.`is_deleted` = 0";
        $groupBy = "";
        $orderBy = "";
        $limit = "";
        $stmtParams = array();

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

    //REPORT DIAGNOSIS
    public function reportDiagnosis($params) {

        $sqlWhere = "WHERE (p.`is_deleted` = 0 OR p.is_deleted IS NOT NULL)";
        $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 ") . "p.`referral_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 ') . "hf.`id` = :healthFacility_id_$key";
                    $stmtParams["healthFacility_id_$key"] = $branchId;
                }
                $sqlWhere .= " AND ($hf_ors) ";
            }
        }

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

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

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

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

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

        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 ') . "hf.`id` = $branchId";
                        }
                        $sqlWhere .= (empty($andWhere) ? " AND " : "") . " ($hf_ors) ";
                    } else {
                        $sqlWhere .= (empty($andWhere) ? " AND " : "") . " (1 != 1) ";
                    }
                }
            }
        }

        $sql = "
                SELECT 
                      p.`id` AS patientId,
                      DATE_FORMAT(p.`referral_date`, '%m/%d/%Y') AS referralDate,
                      DATE_FORMAT(p.`receive_date`, '%m/%d/%Y') AS receivedDate ,
                      p.`full_name` AS patientName,
                      co.`description` AS companyDesc,
                      hf.`description` AS branchDesc,
                      ct.`description` AS chartType,
                      rhf.`description` AS referringAffiliateDesc,
                      d.`description` AS diagnosisDesc,
                      sp.`full_name` AS specialistName
                FROM `patient` p
                LEFT JOIN (SELECT
                          phf.`patient_id` AS patientId,
                          phf.`health_facility_id` AS healthFacilityId
                       FROM `patient_health_facility` phf
                       LEFT JOIN `health_facility` hf ON phf.`health_facility_id` = hf.`id`
                       WHERE phf.`end_date` IS NULL
                       ORDER BY phf.`created_at` DESC
                ) temp_hf ON temp_hf.`patientId` = p.`id`
                LEFT JOIN `health_facility` hf ON temp_hf.`healthFacilityId` = hf.`id`
                LEFT JOIN `company` co ON hf.`company_id` = co.`id`
                LEFT JOIN `patient_chart` pc ON pc.`id` = (
                    SELECT pc1.`id`
                    FROM `patient_chart` pc1
                    WHERE (pc1.`is_deleted` = 0 OR pc1.`is_deleted` IS NOT NULL)
                    AND pc1.`patient_id` = p.`id`
                    ORDER BY pc1.`chart_date` DESC
                    LIMIT 1
                )
                LEFT JOIN `patient_diagnosis` pd ON pd.`id` = (
					SELECT pd1.`id`
					FROM `patient_diagnosis` pd1
					WHERE (pd1.`is_deleted` = 0 OR pd1.`is_deleted` IS NOT NULL)
					AND pd1.`patient_id` = p.`id`
					AND pd1.`end_date` IS NULL
					ORDER BY pd1.`start_date` DESC
					LIMIT 1
				)
				LEFT JOIN `patient_specialist` ps ON ps.`id` = (
					SELECT ps1.`id`
					FROM `patient_specialist` ps1
					WHERE (ps1.`is_deleted` = 0 OR ps1.`is_deleted` IS NOT NULL)
					AND ps1.`patient_id` = p.`id`
					AND ps1.`end_date` IS NULL
					ORDER BY ps1.`start_date` DESC
					LIMIT 1
				)
				LEFT JOIN `patient_referring_health_facility` prhf ON prhf.`id` = (
					SELECT prhf1.`id`
					FROM `patient_referring_health_facility` prhf1
					WHERE (prhf1.`is_deleted` = 0 OR prhf1.`is_deleted` IS NOT NULL)
					AND prhf1.`patient_id` = p.`id`
					AND prhf1.`end_date` IS NULL
					ORDER BY prhf1.`start_date` DESC
					LIMIT 1
				)
				LEFT JOIN `chart_type` ct ON pc.`chart_type_id` = ct.`id`
				LEFT JOIN `diagnosis` d ON pd.`diagnosis_id` = d.`id`
				LEFT JOIN `specialist` sp ON ps.`specialist_id` = sp.`id`
				LEFT JOIN `referring_health_facility` rhf ON prhf.`referring_health_facility_id` = rhf.`id`
                $sqlWhere
        ";

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

        $result = $query->fetchAll();

        return $result;
    }

    public function autocomplete_suggestions($q) {

        $sql = "
            SELECT
                d.`id`,
                d.`description` AS data,
                d.`description` AS value
            FROM `diagnosis` d
            WHERE d.`description` LIKE :description
            AND d.`is_deleted` = 0
            ORDER BY d.`description`
            LIMIT 0,20
        ";

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

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

        $result = $query->fetchAll();

        return $result;
    }
}
