<?php 
require 'include/ECM/EcmNotifications/WebsocketClient.php';

class EcmNotification extends WebsocketClient{
    
    public $db;
    public $ask;
    public $res;
    public $return_list;
    public $return_position;
    public $user_id;
    public $date_now;
    public $email;
    public $first_name;
    public $last_name;
    public $message_content;
    public $site_url;
    public $phoneNumber;
    public $dataBase;
    public $params_sms;
    private $smsLogin='SAAS';
    private $smsPw='b9cbf79b64be7ad146587d1804daa2eb';
    
    function __construct($user_id) {
        global $sugar_config;
        require_once('modules/EcmSysInfos/EcmSysInfo.php');
        $EcmSysInfo = new EcmSysInfo();
        $this->dataBase=$EcmSysInfo->getDatabaseName();
        $this->assignVariables($user_id);

        if($sugar_config['ruby_notification']==true && $sugar_config['ruby_server_ip']!='' && $sugar_config['ruby_server_port']!=''){
            parent::__construct($sugar_config['ruby_server_ip'],$sugar_config['ruby_server_port']);
        }
    }
    
    function setSmsText($text){
        $this->params_sms['message']=$text;
    }
    function setSmsNumber($number){
        $this->params_sms['to']=$number;
    }
    function assignVariables($user_id){
        global $sugar_config;
        $this->db=$GLOBALS['superGlobalDb'];
        $this->user_id=$user_id;
        $this->site_url=$sugar_config['site_url'];
        if($this->dataBase=='preDb_60b08fe051546309b61d2714d4a0438d'){
        	      $this->params_sms = array(
                'username' => $this->smsLogin,
                'password' => $this->smsPw,
        	      		'encoding'=>'utf-8',
                'to' => '',
                'from' => 'MAT INSTAL',
                'eco' => 0,
                'message' => "",
        	      		
        );
        } else {
        	$this->params_sms = array(
        			'username' => $this->smsLogin,
        			'password' => $this->smsPw,
        			'encoding'=>'utf-8',
        			'to' => '',
        			'from' => 'SMSAPI',
        			'eco' => 0,
        			'message' => "",
        	);
        }
  
    }
    
    /** Ustawia status przypomnienia:
     *  statusy:
     *      0   - niewysłany
     *      1   - wysłany
     *      2   - dostarczony & zobaczony
     */
    function setNotificationFlag($id,$flag){
        if($flag==2){
            $b=$this->db->query("select notification_send from tasks where id='".$id."'");
            $r=$this->db->fetchByAssoc($b);
            if($r['notification_send']==0) return true;
        }
        $back=$this->db->query("update tasks set notification_send='".$flag."' where id='".$id."'");
        if($back!=false){
            return true;
        } else {
            return false;
        }
    }
    
    function setNotificationFlag2($id,$flag){
    	if($flag==2){
    		$b=$this->db->query("select notification_send from calls where id='".$id."'");
    		$r=$this->db->fetchByAssoc($b);
    		if($r['notification_send']==0) return true;
    	}
    	$back=$this->db->query("update calls set notification_send='".$flag."' where id='".$id."'");
    	if($back!=false){
    		return true;
    	} else {
    		return false;
    	}
    }
    
    function calculateNewTime($flag){
        $date = new DateTime();

        switch ($flag) {
            case '1':
                $date->modify('+5 minutes');
                break;
            case '2':
                $date->modify('+10 minutes');
                break;
            case '3':
                $date->modify('+15 minutes');
                break;
            case '4':
                $date->modify('+60 minutes');
                break;
            case '5':
                $date->modify('+120 minutes');
                break;
            case '6':
                $date->modify('+180 minutes');
                break;
            case '7':
                $date->modify('+1 day');
                break;
            case '8':
                $date->modify('+2 day');
                break;
            case '9':
                $date->modify('+3 day');
                break;
        }
        $date->modify('-2 hour');
        $this->date_now=$date->format('Y-m-d H:i:s');
    }
    
    function setNotificationDate($id,$flag){
        $this->calculateNewTime($flag);
        $back=$this->db->query("update tasks set notification_send='0', date_reminder='".$this->date_now."' where id='".$id."'");
        if($back!=false){
            return true;
        } else {
            return false;
        }
    }
    

    
    function sendNotification(){
        
    //    if($this->sendData(json_encode($this->res, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE))!=''){
            
            $this->setNotificationFlag($this->res['id'],'1');
            $this->changeDate($this->res);
            
            if($this->getUserData()!='' && ($this->res['reminder_type']=='2' || $this->res['reminder_type']=='3')){
                $arr=explode(',',$this->res['emails']);
                foreach ($arr as $email){
                    if($email!=''){
                $this->sendEmail($this->res['id'],$email);
                
                }
            }
            }
            if($this->res['reminder_type']=='1' || $this->res['reminder_type']=='3' || $this->res['reminder_type']=='7'){
                $arr=explode(',',$this->res['telephones']);
                foreach ($arr as $email){
                    if($email!=''){
                                 $this->setSmsNumber($email);
                               if($this->dataBase=='preDb_60b08fe051546309b61d2714d4a0438d'){
                               	$this->setSmsText($this->res['description']);
                               } else {
                $this->setSmsText('Przypomnienie: '.$this->res['description']);
                               }
                               if($this->dataBase=='preDb_60b08fe051546309b61d2714d4a0438d'){
                             echo "wysyłam sms!!!";
                $this->sms_send($this->params_sms);
                               }
                
                    }
    

            }
 
        }
  //  }
    }
    
    function getUserData(){
        $u= new User();
        $u->retrieve($this->res['assigned_user_id']);
        $email=$u->email1;
        $this->email=$email;
        $this->first_name=$u->first_name;
        $this->last_name=$u->last_name;
        $this->phoneNumber=$u->phone_other;
        unset($u);
        return $email;
    }
    
    function messegeContent(){
        if($this->res['record_id']!=''){
            $module=  $this->res['record_type'];
        } else {
            $module="Tasks";
        }
        if($this->res['record_id']!=''){
            $id=  $this->res['record_id'];
        } else {
            $id=$this->res['id'];
        }
        $this->message_content="Witaj ".$this->first_name.' '.$this->last_name.'!
                <br>Masz nowe przypomnienie odnośnie: '.$this->res['name'].'.<br>Więcej szczegółów pod adresem: '.$this->site_url.'/index.php?module='.$module.'&action=DetailView&record='.$id;
    }
    function messegeContent2(){
    	if($this->res['record_id']!=''){
    		$module=  $this->res['record_type'];
    	} else {
    		$module="Calls";
    	}
    	if($this->res['record_id']!=''){
    		$id=  $this->res['record_id'];
    	} else {
    		$id=$this->res['id'];
    	}
    	$this->message_content="Witaj ".$this->first_name.' '.$this->last_name.'!
                <br>Masz nowe przypomnienie odnośnie: '.$this->res['name'].'.<br>Więcej szczegółów pod adresem: '.$this->site_url.'/index.php?module='.$module.'&action=DetailView&record='.$id;
    }
    function sendEmail($id,$email){
        require_once 'include/ECM/EcmSendPdfButton/EcmSendPdfButton.inc';
        $t = new EcmSendPdfButton('Tasks', $this->res['id'],$email,'');
        $t2 = new Task();
        $t2->retrieve($id);
        if($t2->contact_id!=''){
            $c = new Contact();
            $c->retrieve($t2->contact_id);
            $t->setAdress($c->email1);
        }
        unset($t2);
        unset($c);
       
       
        $t->setAdress($email);
        $this->messegeContent();
        $t->setSubject('Nowe przypomnienie o: '.$this->res['name']);
        $t->setBody($this->message_content);
        $success = false;
        $success= $t->sendEmail();
    }
    function searchLeavedNotifications(){
         
        $this->return_list=array();
      
        $this->ask=$this->db->query("select id,date_reminder,assigned_user_id,name,description,DATE_FORMAT(date_start,'%d.%m.%Y %T') as date_start from tasks where notification_send='1' and date_reminder is not null and assigned_user_id='".$this->user_id."' order by date_reminder desc");
        while($this->res=$this->db->fetchByAssoc($this->ask)){
    
            $this->return_list[]=$this->res;
    
        }
        if(count($this->return_list)>0){
            return $this->return_list;
        } else {
            return '-1';
        }
         
    }
    function sms_send($params, $backup = false ) {
    
        static $content;
    
        if($backup == true){
            $url = 'https://api2.smsapi.pl/sms.do';
        }else{
            $url = 'https://api.smsapi.pl/sms.do';
        }
    
        $c = curl_init();
        curl_setopt( $c, CURLOPT_URL, $url );
        curl_setopt( $c, CURLOPT_POST, true );
        curl_setopt( $c, CURLOPT_POSTFIELDS, $params );
        curl_setopt( $c, CURLOPT_RETURNTRANSFER, true );
    
        $content = curl_exec( $c );
        $http_status = curl_getinfo($c, CURLINFO_HTTP_CODE);

        if($http_status != 200 && $backup == false){
            $backup = true;
            sms_send($params, $backup);
        }
    
        curl_close( $c );
        return $content;
    }
    

    
 
    function changeDate($array){
        if($this->res['remider_interval']!=''){
            if($this->res['remider_interval']!='0'){
            $date = new DateTime();
            
            switch ($this->res['remider_interval_type']) {
                case 'd':
                    $date->modify('+'.$this->res['remider_interval'].' day');
                    break;
                case 'm':
                    $date->modify('+'.$this->res['remider_interval'].' month');
                    break;
                case 'y':
                    $date->modify('+'.$this->res['remider_interval'].' year');
                    break;
            }
            $date->modify('-1 hour'); 
            $back=$this->db->query("update tasks set notification_send='0', date_reminder='". $date->format('Y-m-d H:i:s') ."' where id='".$this->res['id']."'");
            }
       
        }
    }
    
    function searchNotifications(){
         
        $this->ask=$this->db->query("
select id,date_reminder,assigned_user_id,reminder_type,telephones,emails,name,description,DATE_FORMAT(date_start,'%d.%m.%Y %T') as date_start,remider_interval,remider_interval_type,record_id,record_type 
from tasks where notification_send='0' and date_reminder is not null and date_reminder!='1999-12-31 23:00:00' and date_reminder + INTERVAL 1 HOUR < NOW()");
        while($this->res=$this->db->fetchByAssoc($this->ask)){
    
                $this->sendNotification();
            
        }
        
        $this->ask=$this->db->query("
select id,date_reminder,assigned_user_id,reminder_type,name,description,DATE_FORMAT(date_start,'%d.%m.%Y %T') as date_start,remider_interval,remider_interval_type
from calls where notification_send='0' and date_reminder is not null and date_reminder!='1999-12-31 23:00:00' and date_reminder < NOW()");
        while($this->res=$this->db->fetchByAssoc($this->ask)){
        
        	$this->sendNotification2();
        
        }
        return true;
    }
    
    function sendNotification2(){
    
    	/* if($this->sendData(json_encode($this->res, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE))!=''){
    
    
    	} */
    	$this->setNotificationFlag2($this->res['id'],'1');
    	if($this->getUserData()!='' && ($this->res['reminder_type']=='2' || $this->res['reminder_type']=='3')){
    		$this->sendEmail2();
    	}
    }
    
    function sendEmail2(){
    	require_once 'include/ECM/EcmSendPdfButton/EcmSendPdfButton.inc';
    	$t = new EcmSendPdfButton('Calls', $this->res['id'],$this->email,'');
    	$t->setAdress($this->email);
    	$this->messegeContent2();
    	$t->setSubject('Nowe przypomnienie o: '.$this->res['name']);
    	$t->setBody($this->message_content);
    	$success = false;
    	$success= $t->sendEmail();
    }
}


?>