<?php
class ScheduleEmployeeRepository extends EntityRepository {

    private $table = 'schedule_employee';
    private $options = array(
        'period_id'=>null,
        'start_period'=>null,
        'end_period'=>null,
        'scheduled_hours'=>null,
        'status'=>null
    );
    
    private $options_aux = array(
        'details'=>null
    );
    
    public function setOptions($data){
      foreach ($this->options as $option => $value){
          if(isset($data[$option])){
            $this->options[$option] = $data[$option];
          }
      }
      
      foreach ($this->options_aux as $option => $value){
          if(isset($data[$option])){
            $this->options_aux[$option] = $data[$option];
          }
      }
    }
  
    public function getOptions(){
        return $this->options;
    }
    
    public function getDataPeriod($id){
        $query = "SELECT * FROM timeclock_periods WHERE id = $id";
        $result = $this->query($query);
        
        if($result->num_rows > 0){
            return $this->resultToArray($result)[0];
        }
        
        return null;
    }

    public function _saveSchedule(array $data) {
        $periodData = $this->getDataPeriod($data['period_id']);      
        
        if($data['action'] == 'insert'){
            $array = array(
                'store_id'=>$data['store_id'],
                'period_id'=>$data['period_id'],
                'start_period'=>$periodData['date_start'],
                'end_period'=>$periodData['date_end'],
                'status'=>'1'
            );
            
            $this->save($array);
            $this->setLastInsertId($this->getInsertId());
            
        }/*Esto no se usa, porque no se actualiza desde ajax, se actualiza por POST*/
        /* 
        elseif($data['action'] == 'edit'){
            $array = array(
                'store_id'=>$data['store_id'],
                'period_id'=>$data['period_id'],
                'start_period'=>$periodData['start_date'],
                'end_period'=>$periodData['end_date'],
            );
            
            $this->startTransaction();
            
            if($this->update($data['id'],$array)){
                $this->saveDetalles($data);
            }
        }*/
        
        return true;      
    }    
    
    public function save(array $data, $table = null) {        
        return parent::save($data, $this->table);
    }
    
    public function delete($id, $table = null) {
        return parent::delete($id, $this->table);
    }

    public function update($id, $data, $table = null) {  
        $details = $this->options_aux['details'];
        
        $total_hours = 0;        
        foreach($details as $key => $config ){$total_hours += (float)$config['total_hours'];}
        $data['scheduled_hours'] = $total_hours;
        
        unset($data['status']);
        $this->startTransaction();       
        $rs = parent::update($id, $data, $this->table);
        if($rs){            
            if(is_array($details) && count($details) > 0){ 
                $this->saveDetalles($id,$details);
            }
        }
      
        $this->commit();
        return true;
    }
    
     public function saveDetalles($scheduleEmployeeId,$data){ 
        $query = "SELECT id,CONCAT(date,'_',employee_id)as `key` FROM schedule_employee_details WHERE schedule_employee_id = '$scheduleEmployeeId' ";
        $result = $this->query($query);
        
        $currentData = array();
        if($result->num_rows > 0){
            $result = $this->resultToArray($result);            
            
            foreach($result as $row){
                $currentData[$row['key']] = $row['id'];
            }         
        }
        
        foreach($data as $key => $config ){          
            $newConfig = array(
                'start_hour'=>$config['start_hour'],
                'end_hour'=>$config['end_hour'],
                'start_hour_2'=>$config['start_hour_2'],
                'end_hour_2'=>$config['end_hour_2'],
                'total_hours'=>$config['total_hours']
            );
            
            if(key_exists($key, $currentData)){
                $id = $currentData[$key];               
                parent::update($id, $newConfig, 'schedule_employee_details');
            }else{
                $key = explode('_', $key);
                $newConfig['schedule_employee_id'] = $scheduleEmployeeId;
                $newConfig['date'] = $key[0];
                $newConfig['employee_id'] = $key[1];                
                parent::save($newConfig, 'schedule_employee_details');
            }
        }
    }

    public function getById($id, $table = null,$selectAux = null) {
        return parent::getById($id, $this->table,$selectAux);
    }
    
    public function getScheduleList(){
        $query = "SELECT *,"
                . "DATE_FORMAT(start_period,'%m/%d/%Y')as formated_start_period,"
                . "DATE_FORMAT(end_period,'%m/%d/%Y')as formated_end_period,"
                . "fxGetStatusName(status,'ScheduleEmployee')as status_name,"
                . "fxGetStoreName(store_id)as store_name "
                . "FROM $this->table ";
        $result = $this->query($query);
        
        if($result->num_rows > 0){
            return $this->resultToArray($result);
        }   
    }
    
    public function getListPeriods(){
        $query = "SELECT *,"
                . "DATE_FORMAT(date_start,'%m/%d/%Y')as date_start, "
                . "DATE_FORMAT(date_end,'%m/%d/%Y')as date_end "
                . "FROM timeclock_periods ";
        
        $result = $this->query($query);
        
         if($result->num_rows > 0){
            $array = array();
            while($row = $result->fetch_object()){
                $array[$row->id] = $row->date_start.' al '.$row->date_end; 
            }            
            return $array;
        }
        
        return null;
    }   
    
    
    public function getScheduleDetailsByScheduleId($id){
        $scheduleData = $this->getById($id);
        $userRepo = new UserRepository();
        $userList = $userRepo->getListUsers(array('store'=>$scheduleData['store_id'],'status'=>'1'));
        $daysOfPeriod = array();
        
        /*Obtener arreglo con fechas de los dias del periodo de este horario*/       
        $startPeriod = new DateTime($scheduleData['start_period']);
        $endPeriod = new DateTime($scheduleData['end_period']);
        
        if($startPeriod != $endPeriod){            
            $daysOfPeriod[$startPeriod->format('Y-m-d')] = $startPeriod->format('l, d M Y');
            
            while ($startPeriod < $endPeriod){
                $startPeriod->add(new DateInterval('P1D'));
                $daysOfPeriod[$startPeriod->format('Y-m-d')] = $startPeriod->format('l, d M Y');
            }
        }
              
        $query = "SELECT * FROM schedule_employee_details WHERE schedule_employee_id = '$id' ";
        $result = $this->query($query);
        
        $details = array();
        if($result->num_rows > 0){
            $result = $this->resultToArray($result);            
            
            foreach($result as $row){
                $details[$row['date']][$row['employee_id']] = array(
                    'start_hour'=>$row['start_hour'],
                    'end_hour'=>$row['end_hour'],
                    'start_hour_2'=>$row['start_hour_2'],
                    'end_hour_2'=>$row['end_hour_2'],
                    'total_hours'=>$row['total_hours'],
                );
            }           
        }
        
        return array(
            'days_of_period'=>$daysOfPeriod,
            'user_list'=>$userList,
            'details'=>$details
        );      
    }
    
    public function existScheduloForThisPeriod($data){
        $query = "SELECT id FROM $this->table WHERE store_id = '{$data['store_id']}' AND period_id = '{$data['period_id']}'";
        $result = $this->query($query);
        
        if($result->num_rows > 0){
            $result = $this->resultToArray($result)[0];
            return $result['id'];
        }
        
        return null;
    }
    
    public function getListPeriodsForScheduleEmployee(){
        $year = date('Y');
        $month = date('m');
        $lastMonth = $month - 1;
        $nextMonth = $month + 1;
        
        if((float)$month == 1){$lastMonth = 12;}        
        if((float)$month == 12){$nextMonth = 1;}       
        
        $query = "SELECT *,"
                . "DATE_FORMAT(date_start,'%m/%d/%Y')as date_start, "
                . "DATE_FORMAT(date_end,'%m/%d/%Y')as date_end "
                . "FROM timeclock_periods "
                . "WHERE YEAR(date_start) = '$year' AND MONTH(date_start) BETWEEN {$lastMonth} AND {$nextMonth} ";
        
        $result = $this->query($query);
        
         if($result->num_rows > 0){
            $array = array();
            while($row = $result->fetch_object()){
                $array[$row->id] = 'Periodo #'.$row->id.' - De '.$row->date_start.' al '.$row->date_end; 
            }            
            return $array;
        }
        
        return null;
    }
}