<?php

namespace RxConnexionBundle\Repository;

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

        $errors = array();

        $action = $patient_service_form['action'];

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

            $activePs = $this->getEntityManager()->getConnection()->prepare("
                SELECT
                  ps.`id`,
                  ps.`service_id`,
                  DATE_FORMAT(`start_date`, '%m/%d/%Y') AS start_date,
                  DATE_FORMAT(`start_date`, '%m/%d/%Y') AS end_date
                FROM `patient_service` ps
                WHERE ps.`patient_id` = :patientId
                AND ps.`id` != :id
                AND ps.`is_deleted` = 0
                LIMIT 1
            ");
            $activePs->execute(array(
                'patientId' => base64_decode($patient_service_form['patient']),
                'id' => $patient_service_form['id'],
            ));

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

            if(empty($patient_service_form['service_desc']))
                $errors[] = 'Service should not be blank.';
        }

        return $errors;
    }

    public function ajax_list(array $get){

        $columns = array(
            array('s.`description`', 's.`description`', 'service_desc'),
            array('hf.`description`', 'hf.`description`', 'health_facility_desc'),
            array('sp.`full_name`', 'sp.`full_name`', 'specialist_full_name'),
            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')",
        );

        $select = "SELECT";
        $from = "FROM `patient_service` ps";
        $joins = "LEFT JOIN `patient` p ON ps.`patient_id` = p.`id`";
        $joins .= " LEFT JOIN `service` s ON ps.`service_id` = s.`id`";
        $joins .= " LEFT JOIN `health_facility` hf ON ps.`health_facility_id` = hf.`id`";
        $joins .= " LEFT JOIN `specialist` sp ON ps.`specialist_id` = sp.`id`";
        $sqlWhere = "WHERE (ps.`is_deleted` = 0 OR ps.`is_deleted` IS NULL)";
        $sqlWhere .= " AND ps.`patient_id` = :patient_id";
        $sqlWhere .= " AND ps.`patient_service_type` = 'Specialist'";
        $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 patient_service_other_ajax_list(array $get){

        $columns = array(
            array('s.`description`', 's.`description`', 'service_desc'),
            array('hf.`description`', 'hf.`description`', 'health_facility_desc'),
            array('sp.`full_name`', 'sp.`full_name`', 'specialist_full_name'),
            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')",
        );

        $select = "SELECT";
        $from = "FROM `patient_service` ps";
        $joins = "LEFT JOIN `patient` p ON ps.`patient_id` = p.`id`";
        $joins .= " LEFT JOIN `service` s ON ps.`service_id` = s.`id`";
        $joins .= " LEFT JOIN `health_facility` hf ON ps.`health_facility_id` = hf.`id`";
        $joins .= " LEFT JOIN `specialist` sp ON ps.`specialist_id` = sp.`id`";
        $sqlWhere = "WHERE (ps.`is_deleted` = 0 OR ps.`is_deleted` IS NULL)";
        $sqlWhere .= " AND ps.`patient_id` = :patient_id";
        $sqlWhere .= " AND (ps.`patient_service_type` = 'Others' OR ps.`patient_service_type` IS NULL OR ps.`patient_service_type` = '')";
        $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)
        );
    }
}
