<?php

namespace RxConnexionBundle\Repository;

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

        $errors = array();

        $action = $marketingStaff_form['action'];

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

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

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

            /*if(empty($marketingStaff_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 `marketing_staff` 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 marketingStaffName
            FROM `marketing_staff` 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 primaryMarketingStaff_autocomplete($patient_id) {

        $sql = "
            SELECT
                p.`id`,
                p.`full_name` AS marketingStaffName
            FROM `marketing_staff` p
            LEFT JOIN `patient_chart` pc ON pc.`marketing_staff_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 `marketing_staff` 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_marketing_staffAutocomplete_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 `marketing_staff` 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_marketing_staff_autocomplete_suggestions($q, $healthFacility_id) {
        $andWhere = '';
        $params = array(
            'description' => "%$q%"
        );

        if(isset($healthFacility_id) && $healthFacility_id != ''){
            $andWhere .= ' AND p.`id` IN (
                           SELECT phf.`marketing_staff_id`
                           FROM `marketing_staff_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 `marketing_staff` 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 scheduleCalendarViewMarketingStaffs($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 `marketing_staff_work_schedule_temp`
            (INDEX pwst_index_temp (`marketing_staff_id`))
             AS ( 
              SELECT
                GROUP_CONCAT($fields SEPARATOR '@') AS marketingStaffWorkSchedules,
                pws.`marketing_staff_id`
            FROM `marketing_staff_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.`marketing_staff_id`
            );
            
        ");
        $stmt->execute($stmtParams);
        $sql = $conn->prepare(
            "
            SELECT
                p.`id`,
                p.`full_name` AS fullName,
                pwst.`marketingStaffWorkSchedules`
            FROM `marketing_staff_health_facility` phf
            LEFT JOIN `marketing_staff` p ON phf.`marketing_staff_id` = p.`id`
            LEFT JOIN `marketing_staff_work_schedule_temp` pwst ON p.`id` = pwst.`marketing_staff_id`
            WHERE phf.`health_facility_id` = :healthFacility_id
            AND phf.`marketing_staff_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_marketingStaff($healthFacility_id, $date, $marketingStaffId) {
        $conn = $this->getEntityManager()->getConnection();
        $params = array(
            'healthFacility_id' => $healthFacility_id,
            'date' => date('Y-m-d 00:00:00', strtotime($date)),
            'marketingStaff_id' => $marketingStaffId,
        );
        $stmtParams = array(
            'healthFacility_id' => $healthFacility_id,
            'refDate' => date('Y-m-d 00:00:00', strtotime($date)),
            'marketingStaff_id' => $marketingStaffId,
        );
        $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 `marketing_staff_work_schedule_temp`
            (INDEX pwst_index_temp (`marketing_staff_id`))
             AS ( 
              SELECT
                GROUP_CONCAT($fields SEPARATOR '@') AS marketingStaffWorkSchedules,
                pws.`marketing_staff_id`
            FROM `marketing_staff_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.`marketing_staff_id` = :marketingStaff_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.`marketing_staff_id`
            );
            
        ");
        $stmt->execute($stmtParams);

        $sql = $conn->prepare(
            "
            SELECT
                p.`id`,
                p.`full_name` AS fullName,
                pwst.`marketingStaffWorkSchedules`
            FROM `marketing_staff_health_facility` phf
            LEFT JOIN `marketing_staff` p ON phf.`marketing_staff_id` = p.`id`
            LEFT JOIN `marketing_staff_work_schedule_temp` pwst ON p.`id` = pwst.marketing_staff_id
            WHERE phf.`health_facility_id` = :healthFacility_id
            AND phf.`marketing_staff_id` = :marketingStaff_id
            AND phf.`marketing_staff_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();
    }

}
