<?php

namespace RxConnexionBundle\Repository;

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

        $errors = array();

        $action = $medication_form['action'];

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

            $medicationExist = $this->getEntityManager()->getRepository('RxConnexionBundle:MedicationEntity')
                ->createQueryBuilder('m')
                ->where('m.id != :id')
                ->andWhere('m.description = :description')
                ->andWhere('m.isDeleted = 0')
                ->setParameters(array(
                    'id' => $medication_form['id'],
                    'description' => $medication_form['description']
                ))
                ->getQuery()->getResult();

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

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

        return $errors;
    }

    public function ajax_list(array $get){

        $columns = array(
            array('mt.`description`','mt.`description`', 'medicationType_desc'),
            array('m.`code`', 'm.`code`'),
            array('m.`description`', 'm.`description`'),
            array('m.`id`', "m.`id`")
        );
        $asColumns = array();

        $select = "SELECT";
        $from = "FROM `medication` m";
        $joins = "LEFT JOIN `medication_type` mt ON m.`medication_type_id` = mt.`id`";
        $sqlWhere = "WHERE m.`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)
        );
    }

    public function reportMedication($params) {

        $sqlWhere = "WHERE pdm.`is_deleted` = 0";
        $stmtParams = array();

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

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

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


        $sql = "
            SELECT     	
                pdm.`patient_diagnosis_id`,
                temp_patient_diagnosis.`patientId`,
                temp_patient_diagnosis.`full_name` patientName,
                temp_patient_diagnosis.`diagnosis`,
                medtype.`description` AS medication_type,
                med.`description` AS medication
            FROM `patient_diagnosis_medication` pdm
            LEFT JOIN `medication` med ON med.`id` = pdm.`medication_id`
            LEFT JOIN `medication_type` medtype ON med.`medication_type_id` = medtype.`id`
            LEFT JOIN (SELECT
			 	 pd.`id` patientDiagnosisId,
			 	 pat.`id` patientId,
			 	 pat.`full_name`,
			 	 dia.`description` diagnosis
			  FROM `patient_diagnosis` pd
			  LEFT JOIN `patient` pat ON pd.`patient_id` = pat.`id`
			  LEFT JOIN `diagnosis` dia ON pd.`diagnosis_id` = dia.`id`
			) temp_patient_diagnosis ON temp_patient_diagnosis.`patientDiagnosisId` = pdm.`patient_diagnosis_id`
            $sqlWhere
        ";

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

        $query->execute($stmtParams);

        $result = $query->fetchAll();

        return $result;
    }

    public function autocomplete_suggestions($q) {

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

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

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

        $result = $query->fetchAll();

        return $result;
    }
}
