<?php

namespace RxConnexionBundle\Repository;

/**
 * PatientInsuranceRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class PatientReferringProviderRepository 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_referring_provider` 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();
//            if(isset($activeRhf[0])) {
//                $errors[] = 'There is still an active referring physician.';
//            }
            if($form['referring_provider']==null){
                $errors[] = 'Please choose referring physician.';
            }
            if($form['start_date']==null){
                $errors[] = 'Please enter start date';
            }
        }


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

            $insuranceExist = $this->getEntityManager()->getRepository('RxConnexionBundle:PatientReferringProviderEntity')
                ->createQueryBuilder('ph')
                ->where('ph.id != :id')
                ->andWhere('ph.patient = :patient')
                ->andWhere('ph.referringProvider = :referringProvider')
                ->andWhere('ph.isDeleted = 0')
                ->setParameters(array(
                    'id' => $form['id'],
                    'patient' => base64_decode($form['patient']),
                    'referringProvider' => $form['referring_provider']
                ))
                ->getQuery()->getResult();

            if($insuranceExist)
                $errors[] = 'Referring Provider already exists to the patient.';
        }

        return $errors;
    }

    public function ajax_list(array $get){

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

        $select = "SELECT";
        $from = "FROM `patient_referring_provider` pr";
        $joins = "LEFT JOIN `referring_provider` r ON pr.`referring_provider_id` = r.`id`";
        $sqlWhere = "WHERE pr.`patient_id` = :patient_id";
        $sqlWhere .= " AND pr.`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 patientReferringProviderNote($patient) {

        $sql = "
            SELECT
                prp.`id`,
                prp.`note`
            FROM `patient_referring_provider` prp
            LEFT JOIN `referring_provider` rp ON prp.`referring_provider_id` = rp.`id`
            WHERE prp.`is_deleted` = 0
            AND prp.`end_date` IS NULL
            AND prp.`patient_id` = :patient_id
            AND prp.`is_deleted` = 0
            ORDER BY prp.`start_date` DESC
            LIMIT 1
            ";

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

        $query->execute(array(
            'patient_id' => $patient
        ));

        $result = $query->fetch();

        return $result;
    }

    public function autocomplete_suggestions($q, $patient_id) {

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

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

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

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

        $result = $query->fetchAll();

        return $result;
    }
}
