<?php

namespace RxConnexionBundle\Repository;

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


        $errors = array();

        $action = $patientFile_form['action'];

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

            /*    $providerExist = $this->getEntityManager()->getRepository('RxConnexionBundle:ProviderEntity')
                    ->createQueryBuilder('ep')
                    ->where('ep.id != :id')
                    ->andWhere('ep.description = :description')
                    ->setParameters(array(
                        'id' => $patientFile_form['id'],
                        'description' => $patientFile_form['description']
                    ))
                    ->getQuery()->getResult();

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

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

        return $errors;
    }
    public function ajax_list(array $get){

        $columns = array(
            array('pf.`created_at`', "DATE_FORMAT(pf.`created_at`, '%m/%d/%Y %h:%i:%s')", 'date'),
            array('pf.`created_by`', 'pf.`created_by`', 'user'),
            array('ft.`description`', 'ft.`description`', 'fileType_desc'),
            array('pf.`description`', 'pf.`description`'),
            array('pf.`note`', 'pf.`note`'),
            array('pf.`faxing_option_id`', 'TO_BASE64(pf.`faxing_option_id`)', 'faxingOptionIdEncoded'),
            array('pf.`id`', 'pf.`id`')
        );
        $asColumns = array();

        $select = "SELECT";
        $from = "FROM `patient_file` pf";
        $joins = " LEFT JOIN `file_type` ft ON pf.`file_type_id` = ft.`id`";
        $joins .= " LEFT JOIN `faxing_option` fo ON pf.`faxing_option_id` = fo.`id`";
        $sqlWhere = "WHERE pf.`patient_id` = :patient_id";
        $sqlWhere .= " AND pf.`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 reportFile($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 (!is_null($params['receive_date_from']) && $params['receive_date_from'] !== 'NULL' && $params['receive_date_from'] !== 'all' && !empty($params['receive_date_from']) && !is_null($params['receive_date_to']) && $params['receive_date_to'] !== 'null' && $params['receive_date_to'] !== 'all' && !empty($params['receive_date_to'])) {
            $sqlWhere .= (empty($sqlWhere) ? "WHERE " : " AND ") . "p.`receive_date` BETWEEN :receive_date_from AND :receive_date_to";
            $stmtParams['receive_date_from'] = date('Y-m-d 00:00:00', strtotime(str_replace('-',  '/', $params['receive_date_from'])));
            $stmtParams['receive_date_to'] = date('Y-m-d 23:59:59', strtotime(str_replace('-', '/', $params['receive_date_to'])));
        }

        if (!is_null($params['upload_date_from']) && $params['upload_date_from'] !== 'NULL' && $params['upload_date_from'] !== 'all' && !empty($params['upload_date_from']) && !is_null($params['upload_date_to']) && $params['upload_date_to'] !== 'null' && $params['upload_date_to'] !== 'all' && !empty($params['upload_date_to'])) {
            $sqlWhere .= (empty($sqlWhere) ? "WHERE " : " AND ") . "pf.`created_at` BETWEEN :upload_date_from AND :upload_date_to";
            $stmtParams['upload_date_from'] = date('Y-m-d 00:00:00', strtotime(str_replace('-',  '/', $params['upload_date_from'])));
            $stmtParams['upload_date_to'] = date('Y-m-d 23:59:59', strtotime(str_replace('-', '/', $params['upload_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 ') . "ft.`health_facility_id` = :healthFacility_id_$key";
                    $stmtParams["healthFacility_id_$key"] = $branchId;
                }
                $sqlWhere .= " AND ($hf_ors) ";
            }
        }

        if(isset($params['file_type']) && !empty($params['file_type']) && 'NULL' !== strtoupper($params['file_type'])){
            $fileTypes = explode(',' , $params['file_type']);
            if(count($fileTypes) > 0){
                $hf_ors = '';
                foreach($fileTypes as $key => $fileTypeId){
                    $hf_ors .= (empty($hf_ors) ? '' : ' OR ') . "pf.`file_type_id` = :fileType_id_$key";
                    $stmtParams["fileType_id_$key"] = $fileTypeId;
                }
                $sqlWhere .= " AND ($hf_ors) ";
            }
        }

        $sql = "SELECT 	
                    pf.`id` AS patientFileId,
                    p.`id` AS patientId,
                    p.`full_name` AS patientName,
                    hf.`description` AS healthFacilityDesc,
                    au.`full_name` AS createdBy,
                    DATE_FORMAT(p.`referral_date` ,'%m/%d/%Y') AS referralDate,
                    DATE_FORMAT(p.`receive_date` ,'%m/%d/%Y') AS receiveDate,
                    DATE_FORMAT(pf.`created_at` ,'%m/%d/%Y %h:%i %p') AS createdAt,
                    pf.`description` AS fileName,
                    ft.`description` AS fileTypeDesc,
                    pf.`note`
                FROM `patient_file` pf
                LEFT JOIN `patient` p ON p.`id` = pf.`patient_id`
                LEFT JOIN `account_user` au ON au.`username` = pf.`created_by`
                LEFT JOIN `file_type` ft ON ft.`id` = pf.`file_type_id`
                LEFT JOIN `patient_health_facility` phf ON phf.`id` = (
                    SELECT
                        phf1.`id`
                    FROM `patient_health_facility` phf1
                    WHERE phf1.`end_date` IS NULL
                    AND phf1.`patient_id` = p.`id`
                    AND phf1.`start_date` <= :now
                    AND (phf1.`end_date` IS NULL OR phf1.`end_date` >= :now)
                    ORDER BY phf1.`created_at` DESC
                    LIMIT 1
                )
                LEFT JOIN `health_facility` hf ON phf.`health_facility_id` = hf.`id`
                $sqlWhere
                AND p.`is_duplicate` = 0
                AND (p.`is_not_count_as_referral` = 0 OR p.`is_not_count_as_referral` IS NULL)
                AND p.`id` IS NOT NULL
                AND hf.`description` IS NOT NULL
                AND hf.`description` NOT IN('DemoLocation', 'test', 'Demo_Test')
                ORDER BY pf.`created_at` DESC
                ";

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

        $stmtParams['now'] = date('Y-m-d');
        $query->execute($stmtParams);

        $result = $query->fetchAll();

        return $result;
    }
}
