<?php

namespace RxConnexionBundle\Repository;

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

        $errors = array();

        $action = $referringProvider_form['action'];

        // d = delete
        if($action !== 'd') {
            /*    $patientChartExist = $this->getEntityManager()->getRepository('RxConnexionBundle:ProviderEntity')
                    ->createQueryBuilder('ep')
                    ->where('ep.id != :id')
                    ->andWhere('ep.description = :description')
                    ->setParameters(array(
                        'id' => $referring_providerChart_form['id'],
                        'description' => $referring_providerChart_form['description']
                    ))
                    ->getQuery()->getResult();

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

            /*if(empty($referring_providerChart_form['description']))
                $errors[] = 'Description should not be blank.';*/
            if(empty($referringProvider_form['chart_status'])){
                $errors[] = 'Please select status';
            }
        }

        return $errors;
    }

    public function ajax_list(array $get){

        $columns = array(
            array('hf.`description`', 'hf.`description`', 'health_facility_desc'),
            array('pc.`id`', "pc.`id`"),
            array('ct.`description`', 'ct.`description`', 'chart_type_desc'),
            array('pc.`chart_date`', "DATE_FORMAT(pc.`chart_date`, '%m/%d/%Y')", 'chart_date'),
            array('pr.`full_name`', 'pr.`full_name`', 'marketingStaff_fullName'),
            array('cs.`description`', 'cs.`description`', 'chart_status_desc'),
            array('pc.`referring_provider_id`', 'pc.`referring_provider_id`'),
        );
        $asColumns = array();

        $select = "SELECT";
        $from = "FROM `referring_provider_chart` pc";
        $joins = "LEFT JOIN `health_facility` hf ON pc.`health_facility_id` = hf.`id`";
        $joins .= " LEFT JOIN `marketing_staff` pr ON pc.`marketing_staff_id` = pr.`id`";
        $joins .= " LEFT JOIN `chart_status` cs ON pc.`chart_status_id` = cs.`id`";
        $joins .= " LEFT JOIN `chart_type` ct ON pc.`chart_type_id` = ct.`id`";
        $sqlWhere = "WHERE pc.`referring_provider_id` = :referring_provider_id";
        $sqlWhere .= " AND (pc.`is_deleted` = 0 OR pc.`is_deleted` IS NULL)";
        $groupBy = "";
        $orderBy = "";
        $limit = "";
        $stmtParams = array(
            'referring_provider_id' => base64_decode($get['referring_provider_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 getReferringProviderLatestChart($referringProviderId, $chartId) {
        $conn = $this->getEntityManager()->getConnection();
        $stmtParams = array(
            'referringProviderId' => $referringProviderId,
            'chartId' => $chartId
        );
        $sql = $conn->prepare(
            "
           SELECT
                pc.`id` AS patientChartId,
                cs.`description` AS chartStatus,
                ct.`description` AS chartType,
                DATE_FORMAT(pc.`chart_date`, '%m/%d/%Y') AS chartDate,
                hf.`description` AS healthFacility,
                p.`full_name` AS marketingStaff
            FROM `referring_provider_chart` pc
            LEFT JOIN `chart_type` ct ON pc.`chart_type_id` = ct.`id` 
            LEFT JOIN `chart_status` cs ON pc.`chart_status_id` = cs.`id` 
            LEFT JOIN `health_facility` hf ON pc.`health_facility_id` = hf.`id` 
            LEFT JOIN `marketing_staff` p ON pc.`marketing_staff_id` = p.`id`
            LEFT JOIN `marketing_staff_schedule` s ON pc.`marketing_staff_schedule_id` = s.`id`
            WHERE pc.`referring_provider_id` = :referringProviderId
            AND pc.`id` != :chartId
            AND pc.`is_deleted` = 0
            ORDER BY pc.`id` DESC, pc.`chart_date` DESC
            
        "

        );

        $sql->execute($stmtParams);
        $result = $sql->fetchAll();
        if(isset($result[0])){
            return $result[0];
        }


    }

    public function autocompleteSuggestions($get) {

        $andWhere = '';
        $stmtParams = array('q' => '%' . $get['query'] . '%');

        if(isset($get['referring_provider_id'])) {
            $andWhere .= ' AND pc.`referring_provider_id` = :pt_id';
            $stmtParams['pt_id'] = $get['referring_provider_id'];
        }

        if(isset($get['referring_provider_ids']) && !empty($get['referring_provider_ids'])) {
            $referring_providerIds = explode('|',$get['referring_provider_ids']);
            if(count($referring_providerIds)){
                $ors = "";
                foreach ($referring_providerIds as $key => $referring_providerId) {
                    $ors .= (empty($ors) ? '' : ' OR ').'pc.`referring_provider_id` = :pt_id'.$key;
                    $stmtParams['pt_id'.$key] = $referring_providerId;
                }
                $andWhere .= " AND ($ors)";
            }
        }

        $field = "CONCAT_WS(' - ', pc.`id`, DATE_FORMAT(pc.`chart_date`, '%m/%d/%Y'), ct.`description`)";
        $query = $this->getEntityManager()->getConnection()->prepare("
            SELECT
                pc.`id`,
                $field AS data,
                $field AS value,
                pc.`chart_type_id` AS chartType_id
            FROM `referring_provider_chart` pc
            LEFT JOIN `chart_type` ct ON pc.`chart_type_id` = ct.`id`
            WHERE $field LIKE :q
            AND pc.`is_deleted` = 0
            AND ct.`has_billing` = 1
            $andWhere
            ORDER BY $field DESC
            LIMIT 0,10
        ");
        $query->execute($stmtParams);

        return $query->fetchAll();
    }
}
