<?php

namespace RxConnexionBundle\Repository;

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

        $errors = array();

//        $action = $form['action'];
//
//        // d = delete
//        if($action !== 'd') {
//
//            $activeRhf = $this->getEntityManager()->getConnection()->prepare("
//                SELECT `id`
//                FROM `patient_health_facility` prhf
//                WHERE prhf.`end_date` IS NULL
//                AND prhf.`patient_id` = :patientId
//                AND prhf.`id` != :id
//                LIMIT 1
//            ");
//            $activeRhf->execute(array(
//                'patientId' => base64_decode($form['patient']),
//                'id' => $form['id']
//            ));
//            $activeRhf = $activeRhf->fetchAll();
//            if(isset($activeRhf[0]) && $form['end_date'] === '') {
//                $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('s.`full_name`', 's.`full_name`', 'full_name'),
            array('s.`address`', 's.`address`'),
            array('s.`phone_no`', 's.`phone_no`'),
            array('s.`mobile_no`', 's.`mobile_no`'),
            array('ps.`start_date`', "DATE_FORMAT(ps.`start_date`, '%m/%d/%Y')", 'start_date'),
            array('ps.`end_date`', "DATE_FORMAT(ps.`end_date`, '%m/%d/%Y')", 'end_date'),
            array('ps.`id`', "ps.`id`")
        );
        $asColumns = array(
            "DATE_FORMAT(ps.`start_date`, '%m/%d/%Y')",
            "DATE_FORMAT(ps.`end_date`, '%m/%d/%Y')",
            's.`full_name`'
        );

        $select = "SELECT";
        $from = "FROM `patient_specialist` ps";
        $joins = "LEFT JOIN `specialist` s ON ps.`specialist_id` = s.`id`
        ";
        $sqlWhere = "WHERE ps.`patient_id` = :patient_id";
        $sqlWhere .= " AND ps.`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;
//    }
}
