<?php

namespace RxConnexionBundle\Repository;

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

        $errors = array();

        $action = $form['action'];

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

            $activeRhf = $this->getEntityManager()->getConnection()->prepare("
                SELECT prhf.`id`, DATE_FORMAT(`start_date`, '%m/%d/%Y')
                FROM `patient_health_facility` prhf 
                WHERE prhf.`patient_id` = :patientId
                AND (prhf.`start_date` <= :startDate AND (prhf.`end_date` > :startDate OR prhf.`end_date` IS NULL))
                AND prhf.`id` != :id 
                AND prhf.`is_deleted` = 0
                LIMIT 1
            ");
            $activeRhf->execute(array(
                'patientId' => base64_decode($form['patient']),
                'id' => $form['id'],
                'startDate' => date('Y-m-d 00:00:00', strtotime($form['start_date'])),
                'endDate' => date('Y-m-d 00:00:00', strtotime($form['end_date']))
            ));
            $activeRhf = $activeRhf->fetchAll();
            //var_dump($activeRhf, base64_decode($form['patient'])); die();
            if(isset($activeRhf[0])) {
                $errors[] = 'There is still an active branch.';
            }

            if($form['start_date']==null){
                $errors[] = 'Please enter start date';
            }

            if($form['health_facility']==null){
                $errors[] = 'Please choose branch.';
            }
        }

        return $errors;
    }

    public function ajax_list(array $get){

        $columns = array(
            array('r.`description`', 'r.`description`', 'health_facility'),
            array('r.`address`', 'r.`address`'),
            array('r.`phone_no`', 'r.`phone_no`'),
            array('r.`mobile_no`', 'r.`mobile_no`', 'fax_no'),
            array('ph.`start_date`', "DATE_FORMAT(ph.`start_date`, '%m/%d/%Y')", 'start_date'),
            array('ph.`end_date`', "DATE_FORMAT(ph.`end_date`, '%m/%d/%Y')", 'end_date'),
            array('ph.`id`', "ph.`id`")
        );
        $asColumns = array(
            "DATE_FORMAT(ph.`start_date`, '%m/%d/%Y')",
            "DATE_FORMAT(ph.`end_date`, '%m/%d/%Y')",
            'r.`description`'
        );

        $select = "SELECT";
        $from = "FROM `patient_health_facility` ph";
        $joins = "LEFT JOIN `health_facility` r ON ph.`health_facility_id` = r.`id`";
        $sqlWhere = "WHERE ph.`patient_id` = :patient_id";
        $sqlWhere .= " AND ph.`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 autocomplete_suggestions($q, $patient_id) {

        if(!is_numeric($patient_id)){
            $patient_id = base64_decode($patient_id);
        }

        $sql = "
            SELECT
                prp.`id`,
                rp.`description` AS data,
                rp.`description` AS value
            FROM `patient_health_facility` prp
            LEFT JOIN `health_facility` rp ON prp.`health_facility_id` = rp.`id`
            WHERE rp.`description` LIKE :description
            AND prp.`end_date` IS NULL
            AND prp.`patient_id` = :patient_id
            AND prp.`is_deleted` = 0
            ORDER BY rp.`description`
            LIMIT 0,20
        ";

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

        $query->execute(array(
            'description' => "%$q%",
            'patient_id' => $patient_id
        ));

        $result = $query->fetchAll();

        return $result;
    }
}