<?php

namespace RxConnexionBundle\Repository;

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

    public function patient_ajax_list(array $get){

        $fieldAffiliateName = "
            CASE anf.`affiliate_type`
                WHEN 'Referring Affiliate' THEN rhf.`description`
                WHEN 'Referring Physician' THEN rp.`full_name`
                ELSE i.`description`
            END
        ";
        $columns = array(
            array('anf.`created_at`', "DATE_FORMAT(anf.`created_at`, '%m/%d/%Y %h:%i %p')", 'createdAt'),
            array('s.`id`', "s.`id`", 'scheduleId'),
            array('anf.`affiliate_type`', "anf.`affiliate_type`", 'affiliateType'),
            array('anf.`affiliate_type`', $fieldAffiliateName, 'affiliateName'),
            array('anf.`id`', "anf.`id`"),
            array('ftb.`ctr`', "ftb.`ctr`", 'faxCtr'),
        );
        $asColumns = array();

        $select = "SELECT";
        $from = "FROM `appointment_notice_fax` anf";
        $joins = "
            LEFT JOIN `schedule` s ON anf.`schedule_id` = s.`id`
            LEFT JOIN `patient_referring_provider` prp ON anf.`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 anf.`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 anf.`patient_insurance_id` = pi.`id`
            LEFT JOIN `insurance` i ON pi.`insurance_id` = i.`id`
            LEFT JOIN (
                SELECT
                    ftb.`appointment_notice_fax_id`,
                    COUNT(DISTINCT ftb.`id`) AS ctr
                FROM `fax_tran_outbound` ftb
                LEFT JOIN `appointment_notice_fax` anf ON ftb.`appointment_notice_fax_id` = anf.`id`
                WHERE ftb.`source` = 'SN'
                AND ftb.`status` = 1
                AND ftb.`is_deleted` = 0
                AND anf.`patient_id` = :patient_id
                GROUP BY ftb.`appointment_notice_fax_id`
            ) ftb ON anf.`id` = ftb.`appointment_notice_fax_id`
        ";
        $sqlWhere = "
            WHERE anf.`patient_id` = :patient_id
            AND anf.`is_deleted` = 0
            AND s.`is_deleted` = 0
        ";
        $groupBy = "";
        $orderBy = "";
        $limit = "";
        $stmtParams = array(
            'patient_id' => base64_decode($get['patient_id'])
        );

        if(isset($get['scheduleId'])){
            $sqlWhere .= " AND anf.`schedule_id` = :scheduleId";
            $stmtParams['scheduleId'] = base64_decode($get['scheduleId']);
        }

        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 appointmentLetterPdf($patient_id, $schedule_id) {

        $sql = "
            SELECT
                p.`id` patient_id,
                a.`description` account_desc,
                s.`id`,
                p.`full_name` patient_fullName,
                p.`first_name` patient_firstName,
                p.`last_name` patient_lastName,
                p.`birth_date` patient_birthDate,
                p.`gender` patient_gender,
                DATE_FORMAT(s.`schedule_date`, '%m/%d/%Y') schedule_date,
                pr.`full_name` physician_fullName,
                pr.`phone_no` physician_phone_no,
                pr.`email` physician_email,
                rp.`full_name` referring_provider_fullName,
                rp.`phone_no` referring_provider_phoneNo,
                rp.`fax_no` referring_provider_faxNo,
                rp.`fax_no_two` referring_provider_faxNo_two,
                rp.`note` referring_provider_note,
                rhf.`company_description` company,
                rhf.`branch_description` branch,
                rhf.`description` referringAffiliate_desc,
                rhf.`fax_no` referringAffiliate_fax,
                rhf.`fax_no_two` referringAffiliate_faxTwo,
                ct.`description` encounter_type,
                s.`start_time` start_time,
                s.`end_time` end_time,
                i.`description` insurance,
                i.`fax_no` insuranceFax,
                i.`fax_no_two` insuranceFaxTwo,
                s.`fax_cover_selection` faxCoverSelection,
                s.`fax_body_selection` faxBodySelection
            FROM `schedule` s
            LEFT JOIN `patient` p ON s.`patient_id` = p.`id`
            LEFT JOIN `provider` pr ON s.`provider_id` = pr.`id`
            LEFT JOIN `chart_type` ct ON s.`chart_type_id` = ct.`id`
            LEFT JOIN `health_facility` hf ON s.`health_facility_id` = hf.`id`
            LEFT JOIN `account` a ON hf.`account_id` = a.`id`
            LEFT JOIN `patient_referring_provider` prp ON p.`id` = prp.`patient_id`
            LEFT JOIN `referring_provider` rp ON rp.`id` = prp.`referring_provider_id`
            LEFT JOIN `patient_referring_health_facility` prhf ON p.`id` = prhf.`patient_id`
            LEFT JOIN `referring_health_facility` rhf ON rhf.`id` = prhf.`referring_health_facility_id`
            LEFT JOIN `patient_insurance` pi ON p.`id` = pi.`patient_id`
            LEFT JOIN `insurance` i ON i.`id` = pi.`insurance_id`
            WHERE s.`patient_id` = $patient_id AND s.`id` = $schedule_id
            AND s.`is_deleted` = 0
        ";

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

        return $result;
    }
}
