<?php

namespace RxConnexionBundle\Repository;

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

        $errors = array();

        $action = $faxingOption_form['action'];

        // d = delete
        if($action !== 'd') {
            if(empty($faxingOption_form['faxNo'])){
                $errors[] = 'Fax No. should not be empty';
            }

//            if(empty($faxingOption_form['patient'])){
//                $errors[] = 'Patient should not be empty';
//            }
//            if(empty($faxTran_form['fax_status'])){
//                $errors[] = 'Status should not be empty';
//            }
        }

        return $errors;
    }

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

        $columns = array(
            array('op.`created_at`', "DATE_FORMAT(op.`created_at`, '%m/%d/%Y %h:%i %p')", 'createdAt'),
            array("op.`fax_no`", "op.`fax_no`", 'faxNo'),
            array(
                "
                (
                     CASE 
                        WHEN op.`insurance_id` IS NOT NULL THEN i.`description`
                        WHEN op.`referring_provider_id` IS NOT NULL THEN rp.`full_name`
                        ELSE rhf.`description`
                     END
                )
                ",
                "
                (
                     CASE 
                        WHEN op.`insurance_id` IS NOT NULL THEN i.`description`
                        WHEN op.`referring_provider_id` IS NOT NULL THEN rp.`full_name`
                        ELSE rhf.`description`
                     END
                )
                ",
                'faxTo'),
            array("p.`full_name`", "p.`full_name`", 'patientName'),
            array('temp_fof.`attachmentFile`', 'temp_fof.`attachmentFile`', 'attachmentFile'),
            array('foo.`description`', "foo.`description`", 'faxConfirmation'),
            array("op.`status`", "op.`status`", 'status'),
            array("fob.`ctr`", "fob.`ctr`", 'faxCtr'),
            array("foo.`created_at`", "foo.`created_at`", 'faxConfirmationSent'),
            array('foo.`id`', 'foo.`id`', 'faxConfirmationId'),
            array('op.`id`', 'op.`id`'),
        );
        $asColumns = array(
            "DATE_FORMAT(op.`created_at`, '%m/%d/%Y %h:%i %p')"
        );

        $select = "SELECT";
        $from = "FROM `faxing_option` op";
        $joins = "LEFT JOIN `patient` p ON op.`patient_id` = p.`id`";
        $joins .= "
            LEFT JOIN (
                SELECT
                    fob.`faxing_option_id`,
                    COUNT(DISTINCT fob.`id`) AS ctr
                FROM `faxing_option_outbound` fob
                LEFT JOIN `faxing_option` fo ON fob.`faxing_option_id` = fo.`id`
                WHERE fob.`source` = 'FO'
                AND fob.`status` = 1
                GROUP BY fob.`faxing_option_id`
            ) fob ON op.`id` = fob.`faxing_option_id`";
        $joins .= "LEFT JOIN `insurance` i ON op.`insurance_id` = i.`id`";
        $joins .= "LEFT JOIN `referring_provider` rp ON op.`referring_provider_id` = rp.`id`";
        $joins .= "LEFT JOIN `referring_health_facility` rhf ON op.`referring_health_facility_id` = rhf.`id`";
        $joins .= "
            LEFT JOIN (
                SELECT
                    fof.`faxing_option_id`,
                    GROUP_CONCAT(CONCAT_WS('~', fof.`id`, fof.`file_desc`, fof.`parsed_file_desc`) SEPARATOR ',' ) AS attachmentFile
                FROM `faxing_option_file` fof
                WHERE fof.`is_deleted` = 0
                GROUP BY fof.`faxing_option_id`
            ) temp_fof ON temp_fof.`faxing_option_id` = op.`id`
        ";
        $joins .= "LEFT JOIN `faxing_option_confirmation` foo ON foo.`id` = (
            SELECT foo1.`id`
            FROM `faxing_option_confirmation` foo1
            WHERE foo1.`faxing_option_id` = op.`id`
            ORDER BY foo1.`created_at` DESC
            LIMIT 1
        )";

        $sqlWhere = " WHERE op.`is_deleted` = 0";

        $stmtParams = array();
        if(!is_null($userData) && !empty($userData)){
            if($userData['type'] != 'Super Admin'){
                if(count($userData['company']['ids']) > 0){
                    $hf_ors = '';
                    foreach($userData['company']['ids'] as $key => $companyId){
                        $hf_ors .= (empty($hf_ors) ? '' : ' OR ') . "op.`company_id` = :company_id_$key";
                        $stmtParams["company_id_$key"] = $companyId;
                    }
                    $sqlWhere .= (empty($sqlWhere) ? "WHERE " : " AND ") . " ($hf_ors) ";
                } else {
                    $sqlWhere .= (empty($sqlWhere) ? "WHERE " : " AND ") . " (1 != 1) ";
                }
            }
        }

        $sqlWhere .= " OR op.`company_id` IS NULL";

        $groupBy = "";
        $orderBy = "";
        $limit = "";

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

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