<?php

namespace RxConnexionBundle\Repository;

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

        $errors = array();

        $action = $form['action'];

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

            if(empty($form['reminder_type'])){
                $errors[] = 'Category is a required field. ';
            }

            if(empty($form['assigned_to_account_user'])){
                if(empty($form['assigned_to_user_group'])){
                    $errors[] = 'Either a User or a User Group should be assigned. ';
                }
            }

            if(empty($form['start_date'])){
                $errors[] = 'Start Date is a required field. ';
            }

            if(empty($form['note'])){
                $errors[] = 'Note is a required field. ';
            }
        }

        return $errors;
    }

    public function patient_reminder_validate($patientReminder_form) {

        $errors = array();

        $action = $patientReminder_form['action'];

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

            if(empty($patientReminder_form['reminderType'])){
                $errors[] = 'Category is a required field. ';
            }

//            if(empty($form['assigned_to_account_user'])){
//                if(empty($form['assigned_to_user_group'])){
//                    $errors[] = 'Either a User or a User Group should be assigned. ';
//                }
//            }

            if(empty($patientReminder_form['start_date'])){
                $errors[] = 'Start Date is a required field. ';
            }

            if(empty($patientReminder_form['note'])){
                $errors[] = 'Note is a required field. ';
            }
        }

        return $errors;
    }

    public function ajax_list(array $get, $userData=null){

        $columns = array(
            array('rt.`description`', "rt.`description`", 'reminderType_description'),
            array('CONCAT_WS(", ",assigned_au.`full_name`, ug.`description`)', 'CONCAT_WS(", ",assigned_au.`full_name`, ug.`description`)', 'assigned_to'),
            array("DATE_FORMAT(aur.`start_date`, '%m/%d/%Y')", "DATE_FORMAT(aur.`start_date`, '%m/%d/%Y')", 'startDate'),
            array('created_au.`full_name`', "created_au.`full_name`", 'createdBy'),
            array('aur.`status`', "aur.`status`"),
            array('aur.`note`', "aur.`note`"),
            array('aur.`id`', "aur.`id`"),
        );
        $asColumns = array();

        $select = "SELECT";
        $from = "FROM `account_user_reminder` aur";
        $joins = "LEFT JOIN `reminder_type` rt ON aur.`reminder_type_id` = rt.`id`";
        $joins .= "LEFT JOIN `account_user` assigned_au ON aur.`assigned_to_account_user_id` = assigned_au.`id`";
        $joins .= "LEFT JOIN `account_user` created_au ON aur.`account_user_id` = created_au.`id`";
        $joins .= "LEFT JOIN `user_group` ug ON aur.`assigned_to_user_group_id` = ug.`id`";
        $sqlWhere = "WHERE (aur.`account_user_id` = :user_id
                     OR aur.`assigned_to_account_user_id` = :user_id
                     OR aur.`assigned_to_user_group_id` IN (
                      SELECT ugau.`user_group_id`
                      FROM `user_group_account_user` ugau
                      WHERE ugau.`account_user_id` = :user_id
                     )
                  )";
        $groupBy = "";
        $orderBy = "";
        $limit = "";
        $stmtParams = array(
            'user_id' => $userData['id']
        );
        /*if($get['healthFacility_id'] != 'All'){
            $sqlWhere .= (empty($sqlWhere) ? "WHERE " : " AND ") . " phf.`health_facility_id` = :healthFacility_id";
            $stmtParams['healthFacility_id'] = $get['healthFacility_id'];
        } else{ # if all
            if(!is_null($userData) && !empty($userData)){
                if($userData['type'] != 'Super Admin'){
                    if(count($userData['company']['companyBranches']) > 0){
                        $hf_ors = '';
                        foreach($userData['company']['companyBranches'] as $key => $branchId){
                            $hf_ors .= (empty($hf_ors) ? '' : ' OR ') . "phf.`health_facility_id` = :healthFacility_id_$key";
                            $stmtParams["healthFacility_id_$key"] = $branchId;
                        }
                        $sqlWhere .= (empty($sqlWhere) ? "WHERE " : " AND ") . " ($hf_ors) ";
                    } else {
                        $sqlWhere .= (empty($sqlWhere) ? "WHERE " : " AND ") . " (1 != 1) ";
                    }
                }
            }
        }*/
        /*if($get['is_active'] != 'All'){
            $sqlWhere .= (empty($sqlWhere) ? "WHERE " : " AND ") . " p.`is_active` = :is_active";
            $stmtParams['is_active'] = $get['is_active'];
        }*/

        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['reminderType'] != 'All'){
            $sqlWhere .= " AND aur.`reminder_type_id` = :reminderType";
            $stmtParams['reminderType'] = $get['reminderType'];
        }

        if($get['month'] != "all"){
            $yearMonth = explode("|",$get['month']);
            $year = $yearMonth[0];
            $month = $yearMonth[1];
            $sqlWhere .= (!empty($sqlWhere) ? ' AND ' : 'WHERE ') . ' YEAR(aur.`created_at`) = :year AND MONTH(aur.`created_at`) = :month ';
            $stmtParams['year'] = $year;
            $stmtParams['month'] = $month;
        }

        if($get['status'] != 'All'){
            $sqlWhere .= " AND aur.`status` = :status";
            $stmtParams['status'] = $get['status'];
        }

        if($get['assignedTo'] != ''){
            $sqlWhere .= " AND aur.`account_user_id` = :assignedTo";
            $stmtParams['assignedTo'] = $get['assignedTo'];
        }

        /* Set Limit and Length */
        if(isset( $get['start'] ) && $get['length'] != '-1'){
            $limit = 'LIMIT ' . (int)$get['start'] . ',' . (int)$get['length'];
        }

        //$stmtParams['now'] = date('Y-m-d 00:00:00');

        $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_reminder_ajax_list(array $get, $userData=null){

        $patient_id = base64_decode($get['patient_id']);

        $columns = array(
            array('rt.`description`', "rt.`description`", 'reminderType_description'),
            array('CONCAT_WS(", ",assigned_au.`full_name`, ug.`description`)', 'CONCAT_WS(", ",assigned_au.`full_name`, ug.`description`)', 'assigned_to'),
            array("DATE_FORMAT(aur.`start_date`, '%m/%d/%Y')", "DATE_FORMAT(aur.`start_date`, '%m/%d/%Y')", 'startDate'),
            array("DATE_FORMAT(aur.`end_date`, '%m/%d/%Y')", "DATE_FORMAT(aur.`end_date`, '%m/%d/%Y')", 'endDate'),
            array('created_au.`full_name`', "created_au.`full_name`", 'createdBy'),
            array('aur.`status`', "aur.`status`"),
            array("CONCAT('[ ' , DATE_FORMAT(aur.`created_at`, '%m/%d/%Y %h:%i %p'), ' - ', aur.`created_by`, ' ] : ', aur.`note`)","CONCAT('[ ' , DATE_FORMAT(aur.`created_at`, '%m/%d/%Y %h:%i %p'), ' - ', aur.`created_by`, ' ] : ', aur.`note`)", "note"),
            array('aur.`id`', "aur.`id`"),
        );
        $asColumns = array();

        $select = "SELECT";
        $from = "FROM `account_user_reminder` aur";
        $joins = "LEFT JOIN `reminder_type` rt ON aur.`reminder_type_id` = rt.`id`";
        $joins .= "LEFT JOIN `account_user` assigned_au ON aur.`assigned_to_account_user_id` = assigned_au.`id`";
        $joins .= "LEFT JOIN `account_user` created_au ON aur.`account_user_id` = created_au.`id`";
        $joins .= "LEFT JOIN `user_group` ug ON aur.`assigned_to_user_group_id` = ug.`id`";
        $joins .= "LEFT JOIN `account_user_reminder_ref_patient` aurp ON aurp.`account_user_reminder_id` = aur.`id`";
        $sqlWhere = "WHERE aurp.`patient_id` = :patient_id";
        $groupBy = "";
        $orderBy = "";
        $limit = "";
        $stmtParams = array(
            'patient_id' => $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 findAssignedToUserGroup($userGroup){
        return $this->getEntityManager()->getRepository('RxConnexionBundle:AccountUserReminderEntity')
            ->createQueryBuilder('a')
            ->where('a.assignedToUserGroup IN(:userGroup)')
            ->andWhere('a.isDeleted IN(:isDeleted)')
            ->andWhere('a.status IN(:status)')
            ->setParameters(array(
                'userGroup' => array_values($userGroup),
                'isDeleted' => false,
                'status' => 'Pending',
            ))
            ->getQuery()->getResult();
    }

    public function findForUser($userData){
        $stmtParams = array(
            'user_id' => $userData['id'],
            'now' => date('Y-m-d 00:00:00')
        );

        $sql = "SELECT
              rt.`description` as reminderType_description,
              aur.`note`,
              aur.`id`,
              DATE_FORMAT(aur.`created_at`, '%m/%d/%Y') as createdAt,
              DATE_FORMAT(aur.`start_date`, '%m/%d/%Y') as startDate
            FROM `account_user_reminder` aur
            LEFT JOIN `reminder_type` rt ON aur.`reminder_type_id` = rt.`id`
            WHERE (aur.`account_user_id` = :user_id
                     OR aur.`assigned_to_account_user_id` = :user_id
                     OR aur.`assigned_to_user_group_id` IN (
                      SELECT ugau.`user_group_id`
                      FROM `user_group_account_user` ugau
                      WHERE ugau.`account_user_id` = :user_id
                     )
                  )
            AND aur.`status` != 'Completed'
            AND aur.`start_date` <= :now
            ORDER BY aur.`id`  DESC ";
        $query = $this->getEntityManager()->getConnection()->prepare($sql);
        $query->execute($stmtParams);
        $result = $query->fetchAll();

        return $result;
    }

    public function clinician_dashboardFindForUser($provider_id){
        $stmtParams = array(
            'user_id' => $provider_id,
            'now' => date('Y-m-d 00:00:00')
        );

        $sql = "SELECT
              rt.`description` as reminderType_description,
              aur.`note`,
              aur.`id`,
              DATE_FORMAT(aur.`created_at`, '%m/%d/%Y') as createdAt,
              DATE_FORMAT(aur.`start_date`, '%m/%d/%Y') as startDate
            FROM `account_user_reminder` aur
            LEFT JOIN `reminder_type` rt ON aur.`reminder_type_id` = rt.`id`
            LEFT JOIN `account_user` au ON aur.`account_user_id` = au.`id`
            LEFT JOIN `account_user` au_assigned ON aur.`assigned_to_account_user_id` = au_assigned.`id`
            WHERE (au.`provider_id` = :user_id
                     OR au_assigned.`provider_id` = :user_id
                     OR aur.`assigned_to_user_group_id` IN (
                      SELECT ugau.`user_group_id`
                      FROM `user_group_account_user` ugau
                      LEFT JOIN `account_user` au1 ON ugau.`account_user_id` = au1.`id`
                      WHERE au1.`provider_id` = :user_id
                     )
                  )
            AND aur.`status` != 'Completed'
            AND aur.`start_date` <= :now
            ORDER BY aur.`id`  DESC ";
        $query = $this->getEntityManager()->getConnection()->prepare($sql);
        $query->execute($stmtParams);
        $result = $query->fetchAll();

        return $result;
    }

    public function reportReminder($params) {

        $sqlWhere = "WHERE (aur.`is_deleted` = 0 OR aur.`is_deleted` IS NOT NULL)";
        $stmtParams = array();

        if (!is_null($params['date_from']) && $params['date_from'] !== 'null' && $params['date_from'] !== 'all' && !empty($params['date_from']) && !is_null($params['date_to']) && $params['date_to'] !== 'null' && $params['date_to'] !== 'all' && !empty($params['date_to'])) {
            $sqlWhere .= (empty($sqlWhere) ? "WHERE " : " AND ") . "aur.`created_at` BETWEEN :date_from AND :date_to";
            $stmtParams['date_from'] = date('Y-m-d 00:00:00', strtotime(str_replace('-',  '/', $params['date_from'])));
            $stmtParams['date_to'] = date('Y-m-d 23:59:59', strtotime(str_replace('-', '/', $params['date_to'])));
        }

        if(isset($params['reminderType']) && !empty($params['reminderType']) && 'NULL' !== strtoupper($params['reminderType'])){
            $reminderTypes = explode(',' , $params['reminderType']);
            if(count($reminderTypes) > 0){
                $rt_ors = '';
                foreach($reminderTypes as $key => $reminderTypeId){
                    $rt_ors .= (empty($rt_ors) ? '' : ' OR ') . "aur.`reminder_type_id` = :reminder_type_id_$key";
                    $stmtParams["reminder_type_id_$key"] = $reminderTypeId;
                }
                $sqlWhere .= " AND ($rt_ors) ";
            }
        }

        if(isset($params['userGroup']) && !empty($params['userGroup']) && 'NULL' !== strtoupper($params['userGroup'])){
            $userGroups = explode(',' , $params['userGroup']);
            if(count($userGroups) > 0){
                $ug_ors = '';
                foreach($userGroups as $key => $userGroupId){
                    $ug_ors .= (empty($ug_ors) ? '' : ' OR ') . "aur.`assigned_to_user_group_id` = :assigned_to_user_group_$key";
                    $stmtParams["assigned_to_user_group_id_$key"] = $userGroupId;
                }
                $sqlWhere .= " AND ($ug_ors) ";
            }
        }

        if(isset($params['status']) && !empty($params['status']) && 'NULL' !== strtoupper($params['status'])) {
            $sqlWhere .= (empty($sqlWhere) ? "WHERE " : " AND ") . "aur.`status` = :status";
            $stmtParams['status'] = $params['status'];
        }

        if(isset($params['account_user']) && !empty($params['account_user']) && 'NULL' !== strtoupper($params['account_user'])) {
            $sqlWhere .= (empty($sqlWhere) ? "WHERE " : " AND ") . "aur.`account_user_id` = :account_user";
            $stmtParams['account_user'] = $params['account_user'];
        }

        $sql = "SELECT 
                    aur.`id`,
                    rt.`description` AS reminderType,
                    aur.`status` AS reminderStatus,
                    p.`full_name` AS patientName,
                    au.`full_name` AS accountUserName,
                    ug.`description` AS userGroup,
                    aur.`start_date`,
                    aur.`end_date`,
                    aur.`note`
                FROM `account_user_reminder` aur
                LEFT JOIN `reminder_type` rt ON aur.`reminder_type_id` = rt.`id`
                LEFT JOIN `account_user_reminder_ref_patient` aurrp ON aur.`id` = aurrp.`account_user_reminder_id`
                LEFT JOIN `account_user` au ON aur.`account_user_id` = au.`id`
                LEFT JOIN `user_group` ug ON aur.`assigned_to_user_group_id` = ug.`id`
                LEFT JOIN `patient` p ON p.`id` = (
                    SELECT p1.`id` 
                    FROM `patient` p1
                    WHERE (p.`is_deleted` = 0 OR p.`is_deleted` IS NOT NULL) 
                    AND p1.`id` = aurrp.`patient_id`
                    LIMIT 1
                )
                $sqlWhere
                ";

        $query = $this->getEntityManager()->getConnection()->prepare($sql);
        $query->execute($stmtParams);
        $result = $query->fetchAll();

        return $result;
    }

}
