<?php

namespace RxConnexionBundle\Repository;

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

        $errors = array();

        $action = $provider_form['action'];

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

            /*    $providerExist = $this->getEntityManager()->getRepository('RxConnexionBundle:ProviderEntity')
                    ->createQueryBuilder('ep')
                    ->where('ep.id != :id')
                    ->andWhere('ep.description = :description')
                    ->setParameters(array(
                        'id' => $provider_form['id'],
                        'description' => $provider_form['description']
                    ))
                    ->getQuery()->getResult();

                if($providerExist)
                    $errors[] = 'Description already exist.';*/

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

        return $errors;
    }

    public function ajax_list(array $get){

        $columns = array(
            array('p.`full_name`', 'p.`full_name`'),
            array('p.`address`', 'p.`address`'),
            array('p.`gender`', 'p.`gender`'),
            array('p.`birth_date`', "DATE_FORMAT(p.`birth_date`, '%m/%d/%Y')", 'birthDate'),
            array('p.`start_date`', "DATE_FORMAT(p.`start_date`, '%m/%d/%Y')", 'startDate'),
            array('p.`end_date`', "DATE_FORMAT(p.`end_date`, '%m/%d/%Y')", 'endDate'),
            array('p.`emergency_contact_name`', 'p.`emergency_contact_name`', 'emergencyContactName'),
            array('p.`emergency_contact_no`', 'p.`emergency_contact_no`', 'emergencyContactNo'),
            array('p.`gender`', 'p.`gender`'),
            array('p.`id`', "p.`id`")
        );
        $asColumns = array();

        $select = "SELECT";
        $from = "FROM `provider` p";
        $joins = "";
        $sqlWhere = "WHERE p.`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'] != 'All'){
            $sqlWhere .= (!empty($sqlWhere) ? ' AND ' : 'WHERE ') . '`is_active` = :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)
        );
    }

    public function clinicianForMultiple() {

        $sql = "
            SELECT
                p.`id`,
                p.`full_name` AS providerName
            FROM `provider` p
            WHERE p.`is_deleted`= 0 AND p.`is_active` = 1
            ORDER BY p.`full_name`
        ";

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

        $query->execute();
        $result = $query->fetchAll();

        return $result;
    }


    public function primaryProvider_autocomplete($patient_id) {

        $sql = "
            SELECT
                p.`id`,
                p.`full_name` AS providerName
            FROM `provider` p
            LEFT JOIN `patient_chart` pc ON pc.`provider_id` = p.`id`
            LEFT JOIN `chart_type` ct ON pc.`chart_type_id` = ct.`id`
            WHERE p.`is_deleted`= 0
            AND pc.`patient_id` = :patient_id
            AND ct.`description` = 'HSAT'
            AND p.`is_active` = 1
            ORDER BY pc.`chart_date` DESC
            LIMIT 1
        ";

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

        $stmtParams = array(
          'patient_id' => $patient_id
        );

        $query->execute($stmtParams);
        $result = $query->fetch();

        return $result;
    }

    public function autocomplete_suggestions($q) {

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

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

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

        $result = $query->fetchAll();

        return $result;
    }

    public function for_patient_schedule_providerAutocomplete_suggestions($q) {

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

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

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

        $result = $query->fetchAll();

        return $result;
    }

    public function schedule_provider_autocomplete_suggestions($q, $healthFacility_id) {
        $andWhere = '';
        $params = array(
            'description' => "%$q%"
        );

        if(isset($healthFacility_id) && $healthFacility_id != ''){
            $andWhere .= ' AND p.`id` IN (
                           SELECT phf.`provider_id`
                           FROM `provider_health_facility` phf
                           WHERE phf.`health_facility_id` = :healthFacility_id
                           AND phf.`is_deleted` = 0
                        )';
            $params['healthFacility_id'] = $healthFacility_id;
        }
        $sql = "
            SELECT
                p.`id`,
                p.`full_name` AS data,
                p.`full_name` AS value
            FROM `provider` p
            WHERE p.`full_name` LIKE :description
            AND p.`is_deleted` = 0
            $andWhere
            ORDER BY p.`full_name`
            LIMIT 0,20
        ";

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

        $query->execute($params);

        $result = $query->fetchAll();

        return $result;
    }

    public function scheduleCalendarViewProviders($healthFacility_id, $date) {
        $conn = $this->getEntityManager()->getConnection();
        $params = array(
            'healthFacility_id' => $healthFacility_id,
            'date' => date('Y-m-d 00:00:00', strtotime($date))
        );
        $stmtParams = array(
            'healthFacility_id' => $healthFacility_id,
            'refDate' => date('Y-m-d 00:00:00', strtotime($date))
        );
        $fields = "
            CASE pws.`type`
                WHEN 'Regular' THEN CONCAT_WS('|', pws.`type`, pws.`day_name`, CONCAT(pws.`from_hr`, ':', LPAD(pws.`from_min`, 2, 0), ' ', pws.`from_am`), CONCAT(pws.`to_hr`, ':', LPAD(pws.`to_min`, 2, 0), ' ', pws.`to_am`), hf.`id`)
                WHEN 'Irregular' THEN CONCAT_WS('|', pws.`type`, DATE_FORMAT(pws.`from_date`, '%m/%d/%Y'), DATE_FORMAT(pws.`to_date`, '%m/%d/%Y'), CONCAT(pws.`from_hr`, ':', LPAD(pws.`from_min`, 2, 0), ' ', pws.`from_am`), CONCAT(pws.`to_hr`, ':', LPAD(pws.`to_min`, 2, 0), ' ', pws.`to_am`), hf.`id`)
                ELSE CONCAT_WS('|', pws.`type`, DATE_FORMAT(pws.`from_date`, '%m/%d/%Y'), DATE_FORMAT(pws.`to_date`, '%m/%d/%Y'), CONCAT(pws.`from_hr`, ':', LPAD(pws.`from_min`, 2, 0), ' ', pws.`from_am`), CONCAT(pws.`to_hr`, ':', LPAD(pws.`to_min`, 2, 0), ' ', pws.`to_am`))
                
            END
        ";

        $stmt = $conn->prepare("
            CREATE TEMPORARY TABLE IF NOT EXISTS `provider_work_schedule_temp`
            (INDEX pwst_index_temp (`provider_id`))
             AS ( 
              SELECT
                GROUP_CONCAT($fields SEPARATOR '@') AS providerWorkSchedules,
                pws.`provider_id`
            FROM `provider_work_schedule` pws
            LEFT JOIN `health_facility` hf ON pws.`health_facility_id` = hf.`id`
            WHERE IF(pws.`type` = 'Regular',pws.`health_facility_id` = :healthFacility_id, 0=0)
            AND IF(pws.`type` != 'Regular', :refDate BETWEEN pws.`from_date` AND pws.`to_date`, 1=1)
            AND pws.`is_deleted` = 0
            GROUP BY pws.`provider_id`
            );
            
        ");
        $stmt->execute($stmtParams);
        $sql = $conn->prepare(
            "
            SELECT
                p.`id`,
                p.`full_name` AS fullName,
                pwst.`providerWorkSchedules`
            FROM `provider_health_facility` phf
            LEFT JOIN `provider` p ON phf.`provider_id` = p.`id`
            LEFT JOIN `provider_work_schedule_temp` pwst ON p.`id` = pwst.provider_id
            WHERE phf.`health_facility_id` = :healthFacility_id
            AND phf.`provider_id` IS NOT NULL
            AND phf.`health_facility_id` IS NOT NULL
            AND phf.`is_deleted` = 0
            AND p.`is_active` = 1
            AND p.`is_deleted` = 0
            AND phf.`start_date` <= :date 
            AND (phf.`end_date` IS NULL OR phf.`end_date` >= :date)
            ORDER BY p.`full_name`
        "
        );

        $sql->execute($params);

        return $sql->fetchAll();
    }



    /* ============================================================= */
    /* ================== ZAP SYS QUERY MODULE ===================== */
    /* ============================================================= */

    public function rx_schedule_calendar_view_provider($healthFacility_id, $date, $providerId) {
        $conn = $this->getEntityManager()->getConnection();
        $params = array(
            'healthFacility_id' => $healthFacility_id,
            'date' => date('Y-m-d 00:00:00', strtotime($date)),
            'provider_id' => $providerId,
        );
        $stmtParams = array(
            'healthFacility_id' => $healthFacility_id,
            'refDate' => date('Y-m-d 00:00:00', strtotime($date)),
            'provider_id' => $providerId,
        );
        $fields = "
            CASE pws.`type`
                WHEN 'Regular' THEN CONCAT_WS('|', pws.`type`, pws.`day_name`, CONCAT(pws.`from_hr`, ':', LPAD(pws.`from_min`, 2, 0), ' ', pws.`from_am`), CONCAT(pws.`to_hr`, ':', LPAD(pws.`to_min`, 2, 0), ' ', pws.`to_am`), hf.`id`)
                WHEN 'Irregular' THEN CONCAT_WS('|', pws.`type`, DATE_FORMAT(pws.`from_date`, '%m/%d/%Y'), DATE_FORMAT(pws.`to_date`, '%m/%d/%Y'), CONCAT(pws.`from_hr`, ':', LPAD(pws.`from_min`, 2, 0), ' ', pws.`from_am`), CONCAT(pws.`to_hr`, ':', LPAD(pws.`to_min`, 2, 0), ' ', pws.`to_am`), hf.`id`)
                ELSE CONCAT_WS('|', pws.`type`, DATE_FORMAT(pws.`from_date`, '%m/%d/%Y'), DATE_FORMAT(pws.`to_date`, '%m/%d/%Y'), CONCAT(pws.`from_hr`, ':', LPAD(pws.`from_min`, 2, 0), ' ', pws.`from_am`), CONCAT(pws.`to_hr`, ':', LPAD(pws.`to_min`, 2, 0), ' ', pws.`to_am`))
                
            END
        ";

        $stmt = $conn->prepare("
            CREATE TEMPORARY TABLE IF NOT EXISTS `provider_work_schedule_temp`
            (INDEX pwst_index_temp (`provider_id`))
             AS ( 
              SELECT
                GROUP_CONCAT($fields SEPARATOR '@') AS providerWorkSchedules,
                pws.`provider_id`
            FROM `provider_work_schedule` pws
            LEFT JOIN `health_facility` hf ON pws.`health_facility_id` = hf.`id`
            WHERE IF(pws.`type` = 'Regular',pws.`health_facility_id` = :healthFacility_id, 0=0)
            AND pws.`provider_id` = :provider_id
            AND IF(pws.`type` != 'Regular', :refDate BETWEEN pws.`from_date` AND pws.`to_date`, 1=1)
            AND pws.`is_deleted` = 0
            GROUP BY pws.`provider_id`
            );
            
        ");
        $stmt->execute($stmtParams);

        $sql = $conn->prepare(
            "
            SELECT
                p.`id`,
                p.`full_name` AS fullName,
                pwst.`providerWorkSchedules`
            FROM `provider_health_facility` phf
            LEFT JOIN `provider` p ON phf.`provider_id` = p.`id`
            LEFT JOIN `provider_work_schedule_temp` pwst ON p.`id` = pwst.provider_id
            WHERE phf.`health_facility_id` = :healthFacility_id
            AND phf.`provider_id` = :provider_id
            AND phf.`provider_id` IS NOT NULL
            AND phf.`health_facility_id` IS NOT NULL
            AND phf.`is_deleted` = 0
            AND p.`is_active` = 1
            AND p.`is_deleted` = 0
            AND phf.`start_date` <= :date 
            AND (phf.`end_date` IS NULL OR phf.`end_date` >= :date)
            ORDER BY p.`full_name`
        "
        );
        $sql->execute($params);

        return $sql->fetch();
    }

}
