<?php

class send_sms {
 
     var $url = 'http://cab.websms.ru/http_in6.asp';
     var $login = '';
     var $passwd = '';
     var $sms_from = 'FILYA';
     var $notify_type;
     var $channel = 'sms';

     function send ($phone, $text) {

                  
        $phone = $this->phone_format( $phone );
        $url = $this->url . '?Http_username='.urlencode($this->login).'&Http_password='.urlencode($this->passwd).'&Phone_list='.$phone.'&Message='.urlencode($text). '&fromPhone=' . $this->sms_from;
            
        $context = stream_context_create(array(
            'http' => array(
                'method' => 'GET',
                'header' => 'Content-type: application/x-www-form-urlencoded; charset=UTF-8'
            )
        ));  
        
        $resp = file_get_contents( $url, false, $context); 
        
        if (  strpos($resp, 'Result=ok') || strpos($resp, 'error_num=OK')) {
            return true;
        } else {
           	return false;
        }
            
     }
     
    function phone_format( $phone ) {
      $phone = '+7' . substr( preg_replace( '/[^0-9]/', '', $phone ), -10 );
      return $phone;
    }
     	 
     
     function to_pool($phone, $text, $sendtime = 0, $order_id = 0) {

        $phone = substr(preg_replace( '/[^0-9]/', '', $phone ), -10);
        if ($phone=='' || $text=='' ) return false;


        // проверяем тип оповещения в стоп-листе клиента
         if($this->notify_type){
             $types_obj = new cobject('shop_notify_types');
             $types_obj->byAttr('notify_type', $this->notify_type);

             $user_obj = new cobject('shop_users');
             $user_obj->byAttr('phone', $phone);

             $stop_obj = new cobject('shop_notify_stoplist');
             $db = $stop_obj->getDB()->q($stop_obj->getSelect(' AND `client_id`="'.$user_obj->id.'" AND `type_id`="'.$types_obj->id.'" AND `channel`="'.$this->channel.'"'));
             if($db->nr()){
                return false;
             }
         }


        $create_time = time();
        if (!$sendtime) $sendtime = $create_time;
        
        $obj = new cobject('_sys_sms_pool');
        
        $obj->set('number', $phone);
        $obj->set('text', $text);
        $obj->set('create_time', $create_time );
        $obj->set('send_time', 0);
        $obj->set('send_after', $sendtime );
        $obj->set('order_id', $order_id );
        $obj->set('retry_count', 0);
        $obj->save(false, true); // Без логов, отложенное добавление
        
        return $obj->id;
     }



}

?>
