<?php

namespace RxConnexionBundle\Repository;

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

        $errors = array();

        $action = $marketingStaffWorkSchedule_form['action'];

        // d = delete
        if($action !== 'd') {
            if(empty($marketingStaffWorkSchedule_form['type'])){
                $errors[] = 'Please select type.';
            }
            switch ($marketingStaffWorkSchedule_form['type']){
                case 'Regular' :
                    if(empty($marketingStaffWorkSchedule_form['health_facility'])){
                        $errors[] = 'Please select branch.';
                    }
                    if(empty($marketingStaffWorkSchedule_form['day_name'])){
                        $errors[] = 'Please select day.';
                    }
                    if(empty($marketingStaffWorkSchedule_form['from_hr']) && empty($marketingStaffWorkSchedule_form['from_min']) && empty($marketingStaffWorkSchedule_form['from_am'])){
                        $errors[] = 'Please select time.';
                    }
                    break;

                case 'Irregular' :
                    if(empty($marketingStaffWorkSchedule_form['health_facility'])){
                        $errors[] = 'Please select branch.';
                    }
                    if(empty($marketingStaffWorkSchedule_form['from_date'])){
                        $errors[] = 'Please select from date.';
                    }
                    if(empty($marketingStaffWorkSchedule_form['to_date'])){
                        $errors[] = 'Please select from date.';
                    }
                    if(empty($marketingStaffWorkSchedule_form['from_hr']) && empty($marketingStaffWorkSchedule_form['from_min']) && empty($marketingStaffWorkSchedule_form['from_am'])){
                        $errors[] = 'Please select time.';
                    }
                    break;

                case 'Out' :
                    $hasSchedule = $this->getEntityManager()->getConnection()->prepare("
                        SELECT s.`id`
                        FROM `schedule` s 
                        LEFT JOIN `schedule_status` ss ON s.`schedule_status_id` = ss.`id` 
                        WHERE s.`marketing_staff_id` = :marketingStaff_id
                        AND ss.`description` = 'Cancelled'
                        AND s.`is_deleted` = 0
                        AND s.`schedule_date` BETWEEN STR_TO_DATE(:fromDate, '%Y-%m-%d %H:%i:%s') AND STR_TO_DATE(:toDate, '%Y-%m-%d %H:%i:%s') 
                        AND (
                                STR_TO_DATE(CONCAT(s.`start_time_hour`, ':', LPAD(s.`start_time_minute`, 2,0), ' ', s.`start_time_period`), '%l:%i %p') BETWEEN STR_TO_DATE(:fromTime, '%l:%i %p') AND  STR_TO_DATE(:toTime, '%l:%i %p')
                                AND STR_TO_DATE(CONCAT(s.`end_time_hour`, ':', LPAD(s.`end_time_minute`, 2,0), ' ', s.`end_time_period`), '%l:%i %p') BETWEEN STR_TO_DATE(:fromTime, '%l:%i %p') AND  STR_TO_DATE(:toTime, '%l:%i %p')
                                
                           )
                        LIMIT 1
                    ");

                    $hasSchedule->execute(array(
                        'marketingStaff_id' => base64_decode($marketingStaffWorkSchedule_form['marketingStaff']),
                        'fromDate' => date('Y-m-d 00:00:00', strtotime($marketingStaffWorkSchedule_form['from_date'])),
                        'toDate' => date('Y-m-d 00:00:00', strtotime($marketingStaffWorkSchedule_form['to_date'])),
                        'fromTime' => $marketingStaffWorkSchedule_form['from_hr'] . ':' . sprintf('%002d',$marketingStaffWorkSchedule_form['from_min']) . ' ' . $marketingStaffWorkSchedule_form['from_am'],
                        'toTime' => $marketingStaffWorkSchedule_form['to_hr'] . ':' . sprintf('%002d',$marketingStaffWorkSchedule_form['to_min']) . ' ' . $marketingStaffWorkSchedule_form['to_am']
                    ));
                    $hasSchedule = $hasSchedule->fetchAll();
                    if(isset($hasSchedule[0])) {
                        $errors[] = 'Conflict with appointment. Please check your scheduled appointments.';
                    }
                    if(empty($marketingStaffWorkSchedule_form['from_date'])){
                        $errors[] = 'Please select from date.';
                    }
                    if(empty($marketingStaffWorkSchedule_form['to_date'])){
                        $errors[] = 'Please select from date.';
                    }
                    if(empty($marketingStaffWorkSchedule_form['from_hr']) && empty($marketingStaffWorkSchedule_form['from_min']) && empty($marketingStaffWorkSchedule_form['from_am'])){
                        $errors[] = 'Please select time.';
                    }
                    if(empty($marketingStaffWorkSchedule_form['note'])){
                        $errors[] = 'Please enter note.';
                    }

                    break;
            }
        }

        return $errors;
    }

    public function ajax_list(array $get){
            $columns = array(
                array('pws.`type`', 'pws.`type`'),
                array('hf.`description`', 'hf.`description`', 'healthFacility'),
                array('pws.`from_date`', "DATE_FORMAT(pws.`from_date`, '%m/%d/%Y')", 'fromDate'),
                array("CONCAT(pws.`from_hr`, ':', LPAD(pws.`from_min`, 2, 0), ' ', pws.`from_am`)", "CONCAT(pws.`from_hr`, ':', LPAD(pws.`from_min`, 2, 0), ' ', pws.`from_am`)", 'fromTime'),
                array('pws.`to_date`', "DATE_FORMAT(pws.`to_date`, '%m/%d/%Y')", 'toDate'),
                array("CONCAT(pws.`to_hr`, ':', LPAD(pws.`to_min`, 2, 0), ' ', pws.`to_am`)", "CONCAT(pws.`to_hr`, ':', LPAD(pws.`to_min`, 2, 0), ' ', pws.`to_am`)", 'toTime'),
                array('pws.`day_name`', 'pws.`day_name`'),
                array('pws.`note`', 'pws.`note`'),
                array('pws.`id`', 'pws.`id`')
            );
        $asColumns = array();

        $select = "SELECT";
        $from = "FROM `marketing_staff_work_schedule` pws";
        $joins = "LEFT JOIN `health_facility` hf ON pws.`health_facility_id` = hf.`id` ";
        $sqlWhere = "WHERE pws.`marketing_staff_id` = :marketingStaff_id ";
        $sqlWhere .= " AND pws.`is_deleted` = 0";
        $groupBy = "";
        $orderBy = "";
        $limit = "";
        $stmtParams = array(
            'marketingStaff_id' => base64_decode($get['marketingStaff_id'])
        );

        if(isset($get['type']) && !empty($get['type']) && !is_null($get['type'])){
            if($get['type'] === 'Regular'){
                $sqlWhere .= " AND pws.`type` = 'Regular'";
            }elseif($get['type'] === 'Irregular'){
                $sqlWhere .= " AND pws.`type` = 'Irregular'";
            }else{
                $sqlWhere .= " AND pws.`type` = 'Out'";
            }
        }
        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)
        );
    }
}
