<?php

namespace RxConnexionBundle\Repository;

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

        $errors = array();

        $action = $insurance_form['action'];
        // d = delete
        if($action !== 'd') {

            $insuranceExist = $this->getEntityManager()->getRepository('RxConnexionBundle:InsuranceEntity')
                ->createQueryBuilder('ep')
                ->where('ep.id != :id')
                ->andWhere('ep.description = :description')
                ->andWhere('ep.insuranceType = :insuranceType')
                ->andWhere('ep.isDeleted = 0')
                ->setParameters(array(
                    'id' => $insurance_form['id'],
                    'description' => $insurance_form['description'],
                    'insuranceType' => $insurance_form['insurance_type']
                ))
                ->getQuery()->getResult();

            if($insuranceExist)
                $errors[] = 'Description already exist.';

            if(empty($insurance_form['description']))
                $errors[] = 'Description should not be blank.';
        }

        return $errors;
    }

    public function ajax_list(array $get){

        $columns = array(
            array('it.`description`', 'it.`description`', 'insuranceType_desc'),
            array('c.`code`', 'c.`code`'),
            array('c.`description`', 'c.`description`'),
            array('c.`id`', "c.`id`")
        );
        $asColumns = array();

        $select = "SELECT";
        $from = "FROM `insurance` c";
        $joins = "LEFT JOIN `insurance_type` it ON c.`insurance_type_id` = it.`id`";
        $sqlWhere = "WHERE c.`is_deleted` = 0";
        $groupBy = "";
        $orderBy = "";
        $limit = "";
        $stmtParams = array();

        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 reportInsurance($params) {
        $sqlWhere = "";
        $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 ") . "pins.`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['patient_id']) && !empty($params['patient_id']) && 'NULL' !== strtoupper($params['patient_id'])){
            $sqlWhere .= (empty($sqlWhere) ? "WHERE " : " AND ") . "pins.`patient_id` = :patient_id";
            $stmtParams['patient_id'] = $params['patient_id'];
        }

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



        $sql = "
                SELECT 
                    pins.`patient_id` patientId,
                    intyp.`description` AS insurance_type,
                    pins.`insurance_no` AS insurance_no,
                    ins.`description` AS insurance_desc,
                    DATE_FORMAT(pins.`start_date`, '%m/%d/%Y') stateDate,
                    DATE_FORMAT(pins.expire_date, '%m/%d/%Y') expireDate,
                    pat.`full_name` AS full_name
                FROM `patient_insurance` pins
                LEFT JOIN `insurance` ins ON pins.`insurance_id` = ins.`id`
                LEFT JOIN `insurance_type` intyp ON ins.`insurance_type_id` = intyp.`id`
                LEFT JOIN `patient` pat ON pins.`patient_id` = pat.`id` 
                $sqlWhere
                AND pins.`is_deleted` = 0 AND pat.`is_deleted` = 0
        ";

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

        $query->execute($stmtParams);

        $result = $query->fetchAll();

        return $result;
    }

    public function autocomplete_suggestions($q) {

        $sql = "
            SELECT
                p.`id`,
                p.`fax_no`,
                CONCAT_WS(' - ', p.`description`, it.`description`) AS data,
                CONCAT_WS(' - ', p.`description`, it.`description`) AS value
            FROM `insurance` p
            LEFT JOIN insurance_type it ON p.`insurance_type_id` = it.`id`
            WHERE CONCAT_WS(' - ', p.`description`, it.`description`) LIKE :description
            AND p.`is_deleted` = 0
            ORDER BY data
            LIMIT 0,20
        ";

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

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

        $result = $query->fetchAll();

        return $result;
    }
}
