<?php

namespace RxConnexionBundle\Repository;

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

        $errors = array();

        $action = $salesAgent_form['action'];

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

            $salesAgentExist = $this->getEntityManager()->getRepository('RxConnexionBundle:SalesAgentEntity')
                ->createQueryBuilder('ep')
                ->where('ep.id != :id')
                ->andWhere('ep.firstName = :firstName')
                ->andWhere('ep.lastName = :lastName')
                ->andWhere('ep.isDeleted = 0')
                ->setParameters(array(
                    'id' => $salesAgent_form['id'],
                    'firstName' => $salesAgent_form['first_name'],
                    'lastName' => $salesAgent_form['last_name']
                ))
                ->getQuery()->getResult();

            if($salesAgentExist)
                $errors[] = 'Sales agent already exist.';
        }

        return $errors;
    }

    public function ajax_list(array $get){

        $columns = array(
            array('c.`full_name`', 'c.`full_name`'),
            array('c.`rate`', 'c.`rate`'),
            array('c.`id`', "c.`id`")
        );
        $asColumns = array();

        $select = "SELECT";
        $from = "FROM `sales_agent` c";
        $joins = "";
        $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'] . "%";
            }
        }
        if($get['status']){
            if($get['status'] == 'not_active') {
                $status = 0;
            } else {
                $status = 1;
            }
            $sqlWhere .= (!empty($sqlWhere) ? ' AND ' : 'WHERE ') . 'c.`is_active` = :status';
            $stmtParams['status'] = $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)
        );
    }

    //REPORT MARKETING
    public function reportMarketing($params) {
        $sqlWhere = "WHERE (pat.`is_deleted` = 0 OR pat.`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 ") . "pat.`referral_date` 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 (!is_null($params['receive_date_from']) && $params['receive_date_from'] !== 'NULL' && $params['receive_date_from'] !== 'all' && !empty($params['receive_date_from']) && !is_null($params['receive_date_to']) && $params['receive_date_to'] !== 'null' && $params['receive_date_to'] !== 'all' && !empty($params['receive_date_to'])) {
            $sqlWhere .= (empty($sqlWhere) ? "WHERE " : " AND ") . "pat.`receive_date` BETWEEN :receive_date_from AND :receive_date_to";
            $stmtParams['receive_date_from'] = date('Y-m-d 00:00:00', strtotime(str_replace('-',  '/', $params['receive_date_from'])));
            $stmtParams['receive_date_to'] = date('Y-m-d 23:59:59', strtotime(str_replace('-', '/', $params['receive_date_to'])));
        }

        if(isset($params['company']) && !empty($params['company']) && 'NULL' !== strtoupper($params['company'])){
            $companies = explode(',' , $params['company']);
            if(count($companies) > 0){
                $co_ors = '';
                foreach($companies as $key => $companyId){
                    $co_ors .= (empty($co_ors) ? '' : ' OR ') . "hf.`company_id` = :company_id_$key";
                    $stmtParams["company_id_$key"] = $companyId;
                }
                $sqlWhere .= " AND ($co_ors) ";
            }
        }

        if(isset($params['branch']) && !empty($params['branch']) && 'NULL' !== strtoupper($params['branch'])){
            $branches = explode(',' , $params['branch']);
            if(count($branches) > 0){
                $hf_ors = '';
                foreach($branches as $key => $branchId){
                    $hf_ors .= (empty($hf_ors) ? '' : ' OR ') . "temp_hf.`healthFacilityId` = :healthFacility_id_$key";
                    $stmtParams["healthFacility_id_$key"] = $branchId;
                }
                $sqlWhere .= " AND ($hf_ors) ";
            }
        }

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

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

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

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

        if($params['company'] == 'null' && $params['branch'] == 'null') {
            if (!is_null($params['userData']) && !empty($params['userData'])) {
                if ($params['userData']['type'] != 'Super Admin') {
                    if (count($params['userData']['company']['companyBranches']) > 0) {
                        $hf_ors = '';
                        foreach ($params['userData']['company']['companyBranches'] as $key => $branchId) {
                            $hf_ors .= (empty($hf_ors) ? '' : ' OR ') . "temp_hf.`healthFacilityId` = $branchId";
                        }
                        $sqlWhere .= (empty($andWhere) ? " AND " : "") . " ($hf_ors) ";
                    } else {
                        $sqlWhere .= (empty($andWhere) ? " AND " : "") . " (1 != 1) ";
                    }
                }
            }
        }

        $sql = "SELECT
                    DATE_FORMAT(pat.`referral_date`, '%m/%d/%Y') AS referral_date,
                    DATE_FORMAT(pat.`receive_date`, '%m/%d/%Y') receive_date,
                    pat.`id` AS patientId,
                    pl.`id` AS patient_letter_id,
                    pat.`full_name` AS patient,
                    temp_ps.`patientServices`,
                    co.`description` AS companyDesc,
                    hf.`description` AS branch,
                    rhf.`description` AS referring_affiliate,
                    ct.`description` AS chartTypeDesc,
                    cs.`description` AS chartStatusDesc,
                    pl.`letter_type` AS letterType,
                    pls.`description` AS letterStatus,
                    rp.`full_name` AS referring_physician,
                    sa.`full_name` AS sales_agent,
                    sarhf.`sales_agent_id`,
                    pb.`id` AS billingId,
                    IF(pb.`invoice_no` IS NOT NULL, pb.`invoice_no`, pb.`prev_sys_invoice_no`) AS invoice_no,
                    DATE_FORMAT(pb.`billing_date`, '%m/%d/%Y') AS billingDate,
                    IF(pb.`id` IS NOT NULL, IF(sa.`rate` IS NOT NULL, sa.`rate`, 0.00), 0.00) AS rate
                FROM `patient` pat
                LEFT JOIN (
                    SELECT
                        ps.`patient_id`,
                        GROUP_CONCAT(CONCAT_WS('|', ps.`id`, ser.`description`) SEPARATOR ',' ) AS patientServices
                    FROM `patient_service` ps
                    LEFT JOIN `service` ser ON ps.`service_id` = ser.`id`
                    WHERE ps.`is_deleted` = 0
                    GROUP BY ps.`patient_id`
                ) temp_ps ON temp_ps.`patient_id` = pat.`id`
                LEFT JOIN (SELECT
                              phf.`patient_id` AS patientId,
                              phf.`health_facility_id` AS healthFacilityId
                           FROM `patient_health_facility` phf
                           LEFT JOIN `health_facility` hf ON phf.`health_facility_id` = hf.`id`
                           WHERE phf.`end_date` IS NULL
                           ORDER BY phf.`created_at` DESC
                ) temp_hf ON temp_hf.`patientId` = pat.`id`
                LEFT JOIN `health_facility` hf ON temp_hf.`healthFacilityId` = hf.`id`
                LEFT JOIN `company` co ON hf.`company_id` = co.`id`
                LEFT JOIN `patient_chart` pc ON pc.`id` = (
                  SELECT pc1.`id`
                  FROM `patient_chart` pc1
                  WHERE pc1.`is_deleted` = 0
                  AND pc1.`patient_id` = pat.`id`
                  ORDER BY pc1.`chart_date` DESC
                  LIMIT 1
                )
                LEFT JOIN `chart_type` ct ON ct.`id` = pc.`chart_type_id`
                LEFT JOIN `chart_status` cs ON cs.`id` = pc.`chart_status_id`
                LEFT JOIN `patient_letter` pl ON pl.`id` = (
                  SELECT pl1.`id`
                  FROM `patient_letter` pl1
                  WHERE pl1.`is_deleted` = 0
                  AND pl1.`patient_id` = pat.`id`
                  ORDER BY pl1.`created_at` DESC
                  LIMIT 1
                )
                LEFT JOIN `patient_letter_status` pls ON pls.`id` = pl.`patient_letter_status_id`
                LEFT JOIN `patient_referring_health_facility` prhf ON prhf.`id` = (
                          SELECT
                              prhf1.`id`
                          FROM `patient_referring_health_facility` prhf1
                          WHERE pat.`id` = prhf1.`patient_id`
                          AND (prhf1.`is_deleted` = 0 AND prhf1.`is_deleted` IS NOT NULL)
                          AND prhf1.`end_date` IS NULL
                          ORDER BY prhf1.`created_at` DESC
                          LIMIT 1
                )
                LEFT JOIN `referring_health_facility` rhf ON rhf.`id` = prhf.`referring_health_facility_id`
                LEFT JOIN `patient_referring_provider` prp ON prp.`id` = (
                           SELECT
                              prp1.`id`
                           FROM `patient_referring_provider` prp1
                           WHERE prp1.`patient_id` = pat.`id`
                           AND (prp1.`is_deleted` = 0 AND prp1.`is_deleted` IS NOT NULL)
                           AND prp1.`end_date` IS NULL
                           ORDER BY prp1.`created_at` DESC
                           LIMIT 1
                )
                LEFT JOIN `referring_provider` rp ON rp.`id` = prp.`referring_provider_id`
                LEFT JOIN `patient_billing` pb ON pb.`id` = (
                        SELECT pb1.`id`
                        FROM `patient_billing` pb1
                        WHERE pb1.`patient_id` = pat.`id` 
                        AND (pb1.`is_deleted` = 0 OR pb1.`is_deleted` IS NOT NULL)
                        ORDER BY pb1.`billing_date` ASC
                        LIMIT 1
                )
                LEFT JOIN `sales_agent_referring_health_facility` sarhf ON sarhf.`id` = (
                            SELECT 
                              sarhf1.`id`
                            FROM `sales_agent_referring_health_facility` sarhf1
                            LEFT JOIN `referring_health_facility` rhf1 ON rhf1.`id` = sarhf1.`referring_health_facility_id`
                            WHERE prhf.`referring_health_facility_id` = rhf1.`id`
                            AND (sarhf1.`is_deleted` = 0 OR sarhf1.`is_deleted` IS NOT NULL)
                            LIMIT 1
                )	
                LEFT JOIN `sales_agent` sa ON sarhf.sales_agent_id = sa.`id`
                $sqlWhere
                AND pat.`is_duplicate` = 0
                AND (pat.`is_not_count_as_referral` = 0 OR pat.`is_not_count_as_referral` IS NULL)
                AND pat.`id` IS NOT NULL
                AND hf.`description` IS NOT NULL
                AND hf.`description` NOT IN('DemoLocation', 'test', 'Demo_Test')
                AND pat.`id` IS NOT NULL
                ORDER BY pat.`id` ASC
                ";

        $sqlSoldCount = "SELECT
                            sa.`full_name` AS sales_agent,
                            SUM(IF(pb.`id` IS NOT NULL, IF(sa.`rate` IS NOT NULL, sa.`rate`, 0.00), 0.00)) AS rate
                        FROM `patient` pat
                        LEFT JOIN (SELECT
                                      phf.`patient_id` AS patientId,
                                      phf.`health_facility_id` AS healthFacilityId
                                   FROM `patient_health_facility` phf
                                   LEFT JOIN `health_facility` hf ON phf.`health_facility_id` = hf.`id`
                                   WHERE phf.`end_date` IS NULL
                                   ORDER BY phf.`created_at` DESC
                        ) temp_hf ON temp_hf.`patientId` = pat.`id`
                        LEFT JOIN `health_facility` hf ON temp_hf.`healthFacilityId` = hf.`id`
                        LEFT JOIN `company` co ON hf.`company_id` = co.`id`
                        LEFT JOIN `patient_referring_health_facility` prhf ON prhf.`id` = (
                          SELECT
                              prhf1.`id`
                          FROM `patient_referring_health_facility` prhf1
                          WHERE pat.`id` = prhf1.`patient_id`
                          AND (prhf1.`is_deleted` = 0 AND prhf1.`is_deleted` IS NOT NULL)
                          AND prhf1.`end_date` IS NULL
                          ORDER BY prhf1.`created_at` DESC
                          LIMIT 1
                        )
                        LEFT JOIN `referring_health_facility` rhf ON rhf.`id` = prhf.`referring_health_facility_id`
                        LEFT JOIN `patient_referring_provider` prp ON prp.`id` = (
                                   SELECT
                                      prp1.`id`
                                   FROM `patient_referring_provider` prp1
                                   WHERE prp1.`patient_id` = pat.`id`
                                   AND (prp1.`is_deleted` = 0 AND prp1.`is_deleted` IS NOT NULL)
                                   AND prp1.`end_date` IS NULL
                                   ORDER BY prp1.`created_at` DESC
                                   LIMIT 1
                        )
                        LEFT JOIN `referring_provider` rp ON rp.`id` = prp.`referring_provider_id`
                        LEFT JOIN `patient_billing` pb ON pb.`id` = (
                                SELECT pb1.`id`
                                FROM `patient_billing` pb1
                                WHERE pb1.`patient_id` = pat.`id` 
                                AND (pb1.`is_deleted` = 0 OR pb1.`is_deleted` IS NOT NULL)
                                ORDER BY pb1.`billing_date` ASC
                                LIMIT 1
                        )
                        LEFT JOIN `sales_agent_referring_health_facility` sarhf ON sarhf.`id` = (
                                    SELECT 
                                      sarhf1.`id`
                                    FROM `sales_agent_referring_health_facility` sarhf1
                                    LEFT JOIN `referring_health_facility` rhf1 ON rhf1.`id` = sarhf1.`referring_health_facility_id`
                                    WHERE prhf.`referring_health_facility_id` = rhf1.`id`
                                    AND (sarhf1.`is_deleted` = 0 OR sarhf1.`is_deleted` IS NOT NULL)
                                    LIMIT 1
                        )	
                        LEFT JOIN `sales_agent` sa ON sarhf.sales_agent_id = sa.`id`	  
                        $sqlWhere
                        AND pat.`is_duplicate` = 0
                        AND (pat.`is_not_count_as_referral` = 0 OR pat.`is_not_count_as_referral` IS NULL)
                        AND pat.`id` IS NOT NULL
                        AND hf.`description` IS NOT NULL
                        AND hf.`description` NOT IN('DemoLocation', 'test', 'Demo_Test')
                        AND pat.`id` IS NOT NULL
                        AND (pb.`is_deleted` IS NOT NULL OR pb.`is_deleted` = 0)
                        AND sa.`full_name` IS NOT NULL
                        GROUP BY sarhf.`sales_agent_id`
        ";

        $query_marketing = $this->getEntityManager()->getConnection()->prepare($sql);
        $query_soldCount = $this->getEntityManager()->getConnection()->prepare($sqlSoldCount);

        $query_marketing->execute($stmtParams);
        $query_soldCount->execute($stmtParams);

        $result['marketing'] = $query_marketing->fetchAll();
        $result['soldCount'] = $query_soldCount->fetchAll();

        return $result;
    }



    public function autocomplete_suggestions($q) {

        $sql = "
            SELECT
                sa.`id`,
                sa.`first_name`,
                sa.`middle_name`,
                sa.`last_name`,
                sa.`full_name` AS data,
                sa.`full_name` AS value
            FROM `sales_agent` sa
            WHERE sa.`full_name` LIKE :full_name
            AND sa.`is_deleted` = 0
            ORDER BY sa.`full_name`
            LIMIT 0,20
        ";

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

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

        $result = $query->fetchAll();

        return $result;
    }
}
