<?php

namespace RxConnexionBundle\Repository;

/**
 * ChartTypeMethodRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class PatientLetterRepository extends \Doctrine\ORM\EntityRepository
{

    public function validate($patientLetter_form) {

        $errors = array();

        $action = $patientLetter_form['action'];

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

//            if(empty($patientLetter_form['letter_type'])) {
//                $errors[] = 'Letter Type should not be blank.';
//            }

            if(empty($patientLetter_form['affiliate_type'])) {
                $errors[] = 'Affiliate should not be blank';
            }

            if($patientLetter_form['affiliate_type']=='Insurance'){
                if(empty($patientLetter_form['patient_insurance_desc'])){
                    $errors[] = 'Insurance should not be blank';
                }
            }

            if($patientLetter_form['affiliate_type']=='Referring Health Facility'){
                if(empty($patientLetter_form['patient_referring_health_facility_desc'])){
                    $errors[] = 'Referring Health Facility should not be blank';
                }
            }

            if($patientLetter_form['affiliate_type']=='Referring Provider'){
                if(empty($patientLetter_form['patient_referring_provider_desc'])){
                    $errors[] = 'Referring Provider should not be blank';
                }
            }
        }

        return $errors;
    }

    public function ajax_list(array $get){

        $columns = array(
            array('pl.`created_at`', "DATE_FORMAT(pl.`created_at`, '%m/%d/%Y %h:%i %p')", 'createdAt'),
            array('pl.`letter_type`', 'pl.`letter_type`'),
            array('pl.`id`', 'pl.`id`'),
            array('IF(pl.`patient_referring_provider_id` IS NOT NULL , rp.`full_name` , 
                    IF(pl.`patient_referring_health_facility_id` IS NOT NULL ,  rhf.`description` , 
                        i.`description`) )', 'IF(pl.`patient_referring_provider_id` IS NOT NULL , rp.`full_name` , 
                                                 IF(pl.`patient_referring_health_facility_id` IS NOT NULL ,  
                                                    rhf.`description` , i.`description`) )', 'recipient'),
            array("pls.`description`", "pls.`description`", 'status'),
            array("IF(pl.`page` IS NOT NULL AND pl.`page` != 2,pl.`page`, 2 + IF(pl.`photo_desc` IS NOT NULL, 1,0) + IF(pl.`photo_desc_2` IS NOT NULL, 1, 0))", "IF(pl.`page` IS NOT NULL AND pl.`page` != 2,pl.`page`, 2 + IF(pl.`photo_desc` IS NOT NULL, 1,0) + IF(pl.`photo_desc_2` IS NOT NULL, 1, 0))", 'pages'),
            array('CONCAT(rp.`full_name`," (",rp.`fax_no`,")")', 'CONCAT(rp.`full_name`," (",rp.`fax_no`,")")', 'rpDescription'),
            array('CONCAT(rhf.`description`," (",rhf.`fax_no`,")")', 'CONCAT(rhf.`description`," (",rhf.`fax_no`,")")', 'rhfDescription'),
            array('CONCAT(i.`description`," (",i.`fax_no`,")")', 'CONCAT(i.`description`," (",i.`fax_no`,")")', 'iDescription'),
            array("pl.`photo_desc`", "pl.`photo_desc`"),
            array("pl.`photo_desc_2`", "pl.`photo_desc_2`"),
            array('temp_plf.`attachmentFile`', 'temp_plf.`attachmentFile`', 'attachmentFile'),
            array('ftb.`ctr`', 'ftb.`ctr`', 'faxCtr'),
            array('pl.`patient_referring_provider_id`', 'pl.`patient_referring_provider_id`'),
            array('pl.`id`', 'pl.`id`'),
        );
        $asColumns = array(
            "DATE_FORMAT(pl.`created_at`, '%m/%d/%Y %h:%i %p')"
        );

        $select = "SELECT";
        $from = "FROM `patient_letter` pl";
        $joins = "LEFT JOIN `patient_referring_provider` prp ON pl.`patient_referring_provider_id` = prp.`id`";
        $joins .= "LEFT JOIN `referring_provider` rp ON prp.`referring_provider_id` = rp.`id`";
        $joins .= "LEFT JOIN `patient_referring_health_facility` prhf ON pl.`patient_referring_health_facility_id` = prhf.`id` ";
        $joins .= "LEFT JOIN `referring_health_facility` rhf ON prhf.`referring_health_facility_id` = rhf.`id` ";
        $joins .= "LEFT JOIN `patient_insurance` pi ON pl.`patient_insurance_id` = pi.`id`";
        $joins .= "LEFT JOIN `insurance` i ON pi.`insurance_id` = i.`id`";
        $joins .= "LEFT JOIN `patient_letter_status` pls ON pl.`patient_letter_status_id` = pls.`id`";
        $joins .= "
            LEFT JOIN (
                SELECT
                    ftb.`patient_letter_id`,
                    COUNT(DISTINCT ftb.`id`) AS ctr
                FROM `fax_tran_outbound` ftb
                LEFT JOIN `patient_letter` pl ON ftb.`patient_letter_id` = pl.`id`
                WHERE ftb.`source` = 'PL'
                AND ftb.`status` = 1
                AND pl.`patient_id` = :patient_id
                GROUP BY ftb.`patient_letter_id`
            ) ftb ON pl.`id` = ftb.`patient_letter_id`
        ";
        $joins .= "
            LEFT JOIN (
                SELECT
                    plf.`patient_letter_id`,
                    GROUP_CONCAT(CONCAT_WS('~', plf.`id`, plf.`file_desc`, plf.`parsed_file_desc`) SEPARATOR ',' ) AS attachmentFile
                FROM `patient_letter_file` plf
                WHERE plf.`is_deleted` = 0
                GROUP BY plf.`patient_letter_id`
            ) temp_plf ON temp_plf.`patient_letter_id` = pl.`id`
        ";

        $sqlWhere = "WHERE pl.`patient_id` = :patient_id";
        $sqlWhere .= " AND pl.`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'] . "%";
            }
        }
        if($get['letter_status']){
            if($get['letter_status'] != 'All') {
                $sqlWhere .= (!empty($sqlWhere) ? ' AND ' : 'WHERE ') . 'pl.`patient_letter_status_id` = :letter_status';
                $stmtParams['letter_status'] = $get['letter_status'];
            }
        }

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

    //DASHBOARD
    public function dashboardPatientLettersNotSent($params, $userData) {
        $conn = $this->getEntityManager()->getConnection();
        $andWhere = '';
        $stmtParams = array();
        if(isset($params['branch']) && $params['branch'] != 'All'){
            $ors = "";
            foreach ($params['branch'] as $key => $branch) {
                $ors .= (empty($ors) ? '' : ' OR ').'p.`health_facility_id` = :hf_id'.$key;
                $stmtParams['hf_id'.$key] = $branch;
            }
            $andWhere .= " AND ($ors)";
        }

        if($userData['username'] != 'superadmin') {
            if(isset($userData['username']) && $userData != '') {
                $andWhere .= ' AND au.`username` = :username';
                $stmtParams['username'] = $userData['username'];
            }
        }

        $sql = $conn->prepare(
            "
            SELECT
              pl.`letter_type` AS letterType,
              rp.`full_name` AS referringProvider,
              rhf.`description` AS referringHealthFacility,
              i.`description` AS patientInsurance,
              pls.`description` AS status,
              p.`full_name` AS patient,
              p.`id` AS ptId
            FROM `patient_letter` pl
            LEFT JOIN `patient` p ON pl.`patient_id` = p.`id`
            LEFT JOIN `patient_letter_status` pls ON pl.`patient_letter_status_id` = pls.`id`
            LEFT JOIN `patient_referring_provider` prp ON pl.`patient_referring_provider_id` = prp.`id`
            LEFT JOIN `referring_provider` rp ON prp.`referring_provider_id` = rp.`id`
            LEFT JOIN `patient_referring_health_facility` prhf ON pl.`patient_referring_health_facility_id` = prhf.`id`
            LEFT JOIN `referring_health_facility` rhf ON prhf.`referring_health_facility_id` = rhf.`id`
            LEFT JOIN `patient_insurance` pi ON pl.`patient_insurance_id` = pi.`id`
            LEFT JOIN `insurance` i ON pi.`insurance_id` = i.`id`
            LEFT JOIN `account_user` au ON pl.`account_user_id` = au.`id`
            WHERE pl.`is_deleted` = 0
            AND pls.`description` != 'Sent'
            $andWhere
        "
        );

        $sql->execute($stmtParams);

        return $sql->fetchAll();
    }

    public function reportLetterTracker($params) {
        $sqlWhere = "WHERE (p.`is_deleted` = 0 OR p.`is_deleted` IS NOT NULL)";
        $stmtParams = array();

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

        if(isset($params['clinician']) && !empty($params['clinician']) && 'NULL' !== strtoupper($params['clinician'])){
            $clinicians = explode(',' , $params['clinician']);
            if(count($clinicians) > 0){
                $co_ors = '';
                foreach($clinicians as $key => $clinicianId){
                    $co_ors .= (empty($co_ors) ? '' : ' OR ') . "pc.`provider_id` = :provider_id_$key";
                    $stmtParams["provider_id_$key"] = $clinicianId;
                }
                $sqlWhere .= " AND ($co_ors) ";
            }
        }

        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['letterType']) && !empty($params['letterType']) && 'NULL' !== strtoupper($params['letterType'])) {
            $sqlWhere .= (empty($sqlWhere) ? "WHERE " : " AND ") . "pl.`letter_type` = :letterType";
            $stmtParams['letterType'] = $params['letterType'];
        }

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

        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 
                    pl.`id` AS patient_letter_id,
                    p.`id` AS patientId,
                    p.`full_name` AS patientName,
                    rp.`full_name` AS referringPhysician,
                    pr.`full_name` AS hsatInProvider,
                    pl.`letter_type` AS letterType,
                    pls.`description` AS letterStatus,
                    DATE_FORMAT(pl.`created_at`, '%m/%d/%Y') AS requestDate,
                    DATE_FORMAT(pl.`updated_at`, '%m/%d/%Y') AS startedAndCompletedDate,
                    DATE_FORMAT(pl_review.`updated_at`, '%m/%d/%Y') AS reviewAt,
                    au_review.`full_name` AS reviewBy,
                    DATE_FORMAT(pl_sent.`updated_at`, '%m/%d/%Y') AS sentAt,
                    au_sent.`full_name` AS sentBy,
                    pl.`photo_desc` AS photoDesc,
                    pl.`parsed_photo_desc` AS parsedPhotoDesc,
                    au_created.`full_name` AS createdBy,
                    au_assign.`full_name` AS assignTo,
                    pf.`id` AS patientFileId,
                    pf.`description` AS faxConfirmationDesc
                FROM `patient_letter` pl
                LEFT JOIN `patient_letter_status` pls ON pl.`patient_letter_status_id` = pls.`id`
                LEFT JOIN `patient` p ON pl.`patient_id` = p.`id`
                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_referring_provider` prp ON prp.`id` = (
                    SELECT prp1.`id`
                    FROM `patient_referring_provider` prp1
                    WHERE (prp1.`is_deleted` = 0 OR prp1.`is_deleted` IS NOT NULL)
                    AND prp1.`patient_id` = p.`id`
                    AND prp1.`end_date` IS NULL
                    ORDER BY prp1.`start_date` DESC
                    LIMIT 1
                )
                LEFT JOIN `referring_provider` rp ON prp.`referring_provider_id` = rp.`id`
                LEFT JOIN `patient_chart` pc ON pc.`id` = (
                    SELECT pc1.`id`
                    FROM `patient_chart` pc1 
                    LEFT JOIN `chart_type` ct ON pc1.`chart_type_id` = ct.`id` 
                    WHERE (pc1.`is_deleted` = 0 OR pc1.`is_deleted` IS NOT NULL)
                    AND pc1.`patient_id` = p.`id`
                    AND ct.`description` = 'HSAT Results Interpretation'
                    ORDER BY pc1.`chart_date` DESC
                    LIMIT 1
                )
                LEFT JOIN `provider` pr ON pc.`provider_id` = pr.`id`
                LEFT JOIN `patient_letter` pl_review ON pl_review.`id` = (
                    SELECT pl1.`id`
                    FROM `patient_letter` pl1
                    LEFT JOIN `patient_letter_status` pls1 ON pl1.`patient_letter_status_id` = pls1.`id`
                    WHERE (pl1.`is_deleted` = 0 OR pl1.`is_deleted` IS NOT NULL)
                    AND pl1.`id` = pl.`id`
                    AND pls1.`description` = 'Review'
                    LIMIT 1
                )
                LEFT JOIN `patient_letter` pl_sent ON pl_sent.`id` = (
                    SELECT pl2.`id`
                    FROM `patient_letter` pl2
                    LEFT JOIN `patient_letter_status` pls2 ON pl2.`patient_letter_status_id` = pls2.`id`
                    WHERE (pl2.`is_deleted` = 0 OR pl2.`is_deleted` IS NOT NULL)
                    AND pl2.`id` = pl.`id`
                    AND pls2.`description` = 'Sent'
                    LIMIT 1
                )
                LEFT JOIN `account_user` au_review ON pl_review.`updated_by` = au_review.`username`
                LEFT JOIN `account_user` au_sent ON pl_sent.`updated_by` = au_sent.`username`
                LEFT JOIN `account_user` au_created ON pl.`created_by` = au_created.`username`
                LEFT JOIN `account_user` au_assign ON pl.`account_user_id` = au_assign.`id`
                LEFT JOIN `patient_file` pf ON pf.`id` = (
                  SELECT pf1.`id`
                  FROM `patient_file` pf1
                  LEFT JOIN `file_type` ft ON pf1.`file_type_id` = ft.`id`
                  WHERE pf1.`is_deleted` = 0
                  AND pf1.`patient_id` = pl.`patient_id`
                  AND ft.`description` = 'Fax Confirmation'
                  LIMIT 1
                )
                $sqlWhere
                AND p.`is_test_patient` = 0
                AND hf.`description` NOT IN('DemoLocation', 'test', 'Demo_Test')
                GROUP BY pl.`patient_id`
                ORDER BY pl.`created_at` DESC
        ";

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

        $result = $query->fetchAll();

        return $result;
    }

    public function reportLetter($params) {
        $sqlWhere = "WHERE (pl.`is_deleted` = 0 OR pl.`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 ") . "pl.`created_at` 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['account_user']) && !empty($params['account_user']) && 'NULL' !== strtoupper($params['account_user'])) {
            $sqlWhere .= (empty($sqlWhere) ? "WHERE " : " AND ") . "pl.`account_user_id` = :account_user";
            $stmtParams['account_user'] = $params['account_user'];
        }

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

        $sql = "
                SELECT 
                    p.`id` AS patientId,
                    p.`full_name` AS patientName,
                    pl.`letter_type` AS letterType,
                    au.`full_name` AS assignedTo,
                    pls.`description` AS letterStatus,
                    au2.`full_name` AS createdBy,
                    DATE_FORMAT(pl.`created_at`, '%m/%d/%Y') AS createdAt,
                    ftb.`ctr` AS faxCount
                FROM `patient_letter` pl
                LEFT JOIN `patient` p ON pl.`patient_id` = p.`id`
                LEFT JOIN `account_user` au2 ON au2.`username` = pl.`created_by`
                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 (
                    SELECT
                        ftb.`patient_letter_id`,
                        COUNT(DISTINCT ftb.`id`) AS ctr
                    FROM `fax_tran_outbound` ftb
                    WHERE ftb.`source` = 'PL'
                    AND ftb.`status` = 1
                    GROUP BY ftb.`patient_letter_id`
                ) ftb ON pl.`id` = ftb.`patient_letter_id`
                LEFT JOIN `health_facility` hf ON temp_hf.`healthFacilityId` = hf.`id`
                LEFT JOIN `patient_letter_status` pls ON pl.`patient_letter_status_id` = pls.`id`
                LEFT JOIN `company` co ON hf.`company_id` = co.`id`
                LEFT JOIN `account_user` au ON pl.`account_user_id` = au.`id`
                $sqlWhere
        ";

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

        $result = $query->fetchAll();

        return $result;
    }

    public function patientLetterCreatedBy($id) {
        $stmtParams = array();

        $sql = "
                SELECT 
                    au.`full_name` AS createdBy
                FROM `patient_letter` pl
                LEFT JOIN `patient` p ON pl.`patient_id` = p.`id`
                LEFT JOIN `account_user` au ON pl.`created_by` = au.`username`
                WHERE (pl.`is_deleted` = 0 OR pl.`is_deleted` IS NOT NULL)
                AND pl.`id` = :patientLetterId
        ";

        $stmtParams['patientLetterId'] = $id;
        $query = $this->getEntityManager()->getConnection()->prepare($sql);
        $query->execute($stmtParams);

        $result = $query->fetch();

        return $result;
    }
}
