<?php

namespace RxConnexionBundle\Repository;

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

        $errors = array();

        $action = $referringHealthFacility_form['action'];

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

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

            /*if(empty($referring_health_facilityChart_form['description']))
                $errors[] = 'Description should not be blank.';*/
            if(empty($referringHealthFacility_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_health_facility_id`', 'pc.`referring_health_facility_id`'),
        );
        $asColumns = array();

        $select = "SELECT";
        $from = "FROM `referring_health_facility_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_health_facility_id` = :referring_health_facility_id";
        $sqlWhere .= " AND (pc.`is_deleted` = 0 OR pc.`is_deleted` IS NULL)";
        $groupBy = "";
        $orderBy = "";
        $limit = "";
        $stmtParams = array(
            'referring_health_facility_id' => base64_decode($get['referring_health_facility_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 getReferringHealthFacilityLatestChart($referringHealthFacilityId, $chartId) {
        $conn = $this->getEntityManager()->getConnection();
        $stmtParams = array(
            'referringHealthFacilityId' => $referringHealthFacilityId,
            '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_health_facility_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_health_facility_id` = :referringHealthFacilityId
            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_health_facility_id'])) {
            $andWhere .= ' AND pc.`referring_health_facility_id` = :pt_id';
            $stmtParams['pt_id'] = $get['referring_health_facility_id'];
        }

        if(isset($get['referring_health_facility_ids']) && !empty($get['referring_health_facility_ids'])) {
            $referring_health_facilityIds = explode('|',$get['referring_health_facility_ids']);
            if(count($referring_health_facilityIds)){
                $ors = "";
                foreach ($referring_health_facilityIds as $key => $referring_health_facilityId) {
                    $ors .= (empty($ors) ? '' : ' OR ').'pc.`referring_health_facility_id` = :pt_id'.$key;
                    $stmtParams['pt_id'.$key] = $referring_health_facilityId;
                }
                $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_health_facility_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();
    }
}
