<?php

namespace RxConnexionBundle\Repository;

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

        $errors = array();

        $action = $patientEmail_form['action'];

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

            if(empty($patientEmail_form['emailFrom'])) {
                $errors[] = 'From should not be blank';
            }

            if(empty($patientEmail_form['email'])) {
                $errors[] = 'Email should not be blank';
            }

        }

        return $errors;
    }

    public function ajax_list(array $get){

        $columns = array(
            array('pe.`created_at`', "DATE_FORMAT(pe.`created_at`, '%m/%d/%Y %h:%i %p')", 'createdAt'),
            array('et.`description`', 'et.`description`', 'email_template_description'),
            array('pe.`id`', 'pe.`id`'),
            array("pe.`status`", "pe.`status`", 'status'),
            array('temp_pef.`attachmentFile`', 'temp_pef.`attachmentFile`', 'attachmentFile'),
            array('pe.`id`', 'pe.`id`'),
        );
        $asColumns = array(
            "DATE_FORMAT(pl.`created_at`, '%m/%d/%Y %h:%i %p')"
        );

        $select = "SELECT";
        $from = "FROM `patient_email` pe";
        $joins = " LEFT JOIN `email_template` et ON et.`id` = pe.`email_template_id`";
        $joins .= "
            LEFT JOIN (
                SELECT
                    pef.`patient_email_id`,
                    GROUP_CONCAT(CONCAT_WS('~', pef.`id`, pef.`file_desc`, pef.`parsed_file_desc`) SEPARATOR ',' ) AS attachmentFile
                FROM `patient_email_file` pef
                WHERE pef.`is_deleted` = 0
                GROUP BY pef.`patient_email_id`
            ) temp_pef ON temp_pef.`patient_email_id` = pe.`id`
        ";

        $sqlWhere = "WHERE pe.`patient_id` = :patient_id";
        $sqlWhere .= " AND pe.`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'] . "%";
            }
        }
        if($get['status']){
            if($get['status'] != 'All') {
                $sqlWhere .= (!empty($sqlWhere) ? ' AND ' : 'WHERE ') . 'pe.`status` = :status';
                $stmtParams['status'] = $get['status'];
            }
        }

        /* 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)
        );
    }
}
