<?php
    //plesk
    ///var/www/vhosts/mycls.gr/cls149.mycls.gr/cls/modules/smsapi/smsapi_auto_send.php
    //set_include_path('var/www/vhosts/mycls.gr/cls149.mycls.gr/');
    include ('../../../scripts/classes.php');
    //include ('cls149.mycls.gr/scripts/classes.php');
    $installation_owner = Core::GetInstallationOwner();
    
    define('_LOGS_EMAIL_TO', 'info@webnail.gr');
    define('_LOGS_EMAIL_FROM', 'admin@mycls.gr');
    define('_CONNECTOR_NAME', 'CLS_AUTO_SMS'.$installation_owner);
    
    
    ## DEFINE FUNCTIONS
 
    
    // Read customer groups from CLS
        function GetActiveAutoSMS ()
    {
        $mysqli = Database::GetConnection();
        
        $sql_select = "SELECT id, campaign_id, description, sms_text, sender_id, time_set, error_flag FROM ".TABLE_SMS_AUTO_SETUP." 
                        WHERE is_active = 1
                        AND HOUR(time_set) = HOUR(NOW()) AND MINUTE(time_set) = MINUTE(NOW())";		
        $result_select = database_query($mysqli, $sql_select, DATA_AND_ROWS, ALL_ROWS, FETCH_ASSOC, false);
        return $result_select;
        mysqli_close($mysqli);
    }
    
    
 
        // Disable logins in WCE
        function SetErrorFlag($record_id)
    {
        $mysqli = Database::GetConnection();
        
  		$sql = "UPDATE ".TABLE_SMS_AUTO_SETUP." SET error_flag = 1, last_run_time = NOW() WHERE id = '".$record_id."'";		
		$result = database_void_query($mysqli, $sql, false);
        // or die("Query failed : " . mysqli_error($wce_conn));
        if($result) {
            return true;
        } else {
            return false;
        }
        mysqli_close($mysqli);
    }
    
            // Disable logins in WCE
        function SetLastExecutionDate($record_id)
    {
        $mysqli = Database::GetConnection();
        
  		$sql = "UPDATE ".TABLE_SMS_AUTO_SETUP." SET last_run_time = NOW() WHERE id = '".$record_id."'";		
		$result = database_void_query($mysqli, $sql, false);
        // or die("Query failed : " . mysqli_error($wce_conn));
        if($result) {
            return true;
        } else {
            return false;
        }
        mysqli_close($mysqli);
    }


    function UpdateErrorLog($error_code, $error_description)
    {
        $mysqli = Database::GetConnection();
        $user_id = 2; //system
        
  		$sql = "INSERT INTO ".TABLE_ERROR_LOG." (error_id, error_datetime, error_code, error_short_description, error_long_description, error_user_id, error_severity, error_handling) 
                VALUES (NULL, NOW(), '".$error_code."', 'SMSAPI_AUTO', '".$error_description."', '".$user_id."', 'HIGH', '0')";		
        
        $result = database_void_query($mysqli, $sql);
        if($result) {
            return true;
        } else {
            return false;
        }
        mysqli_close($mysqli);
    }
    
    
    
    function DaysToBirthday ($value)
    { 
        $birth_clause = " birth_date IS NOT NULL AND DATE_ADD(birth_date, INTERVAL YEAR(CURDATE())- YEAR(birth_date) YEAR) = DATE_ADD(CURDATE(), INTERVAL ".$value." DAY) ";
        return $birth_clause;
    }  
        
    
    function GetCampaignCustomers($campaign_id, $setup_id)
    {
        $mysqli = Database::GetConnection();
        $sql_select = "SELECT 
                        CAM.criterion_id, 
                        CAM.operator, 
                        CAM.value,
                        CRI.field,
                        CRI.rule,
                        CRI.is_calculated
                        FROM ".TABLE_SMS_CAMPAIGN_CRITERIA." CAM 
                        INNER JOIN ".TABLE_CORE_CRITERIA." CRI ON CRI.id = CAM.criterion_id
                        WHERE CAM.campaign_id = '".$campaign_id."'";		
        
        $result_criteria = database_query($mysqli, $sql_select, DATA_AND_ROWS, ALL_ROWS, FETCH_ASSOC, false);
        
        $build_statement_1 = "SELECT cust.id, cust.phone FROM cls_customers cust WHERE ";   
               
        for($i=0; $i < $result_criteria[1]; $i++){
            //check if the criterion is calculated or not
            if ($result_criteria[0][$i]['is_calculated'] != 1) {$build_statement .= $result_criteria[0][$i]['field']." ".$result_criteria[0][$i]['operator']." '".$result_criteria[0][$i]['value']."' AND ";}
            if ($result_criteria[0][$i]['is_calculated'] == 1) { 

                //check all functions one by one
                $rule_function = $result_criteria[0][$i]['rule'];
                if ($rule_function == 'ValidPhonesRule') $function_result = ValidPhonesRule($result_criteria[0][$i]['value']);
                if ($rule_function == 'DaysToBirthday' AND $result_criteria[0][$i]['operator'] == '='){ 
                    $function_result = DaysToBirthday($result_criteria[0][$i]['value']);
                }elseif ($rule_function == 'DaysToBirthday' AND $result_criteria[0][$i]['operator'] != '='){
                    $function_result = 'ERROR';
                }
                if ($function_result == 'ERROR'){
                    UpdateErrorLog('354', 'Invalid criteria used in campaign for setup'.' ('.$setup_id.')');
                    SetErrorFlag($setup_id);
                    exit();
                }else{
                    $build_statement_1 .= $function_result." AND ";
                }
            }
        }
     $build_statement_2 = substr($build_statement_1, 0, strrpos($build_statement_1, "AND "));    
     $build_statement = $build_statement_2.' AND cust.is_active=1';
     
     return $build_statement;
        
     mysqli_close($mysqli);
    }
    
        function SendSmsApiAuto($phone_number, $sender_id, $sms_text, $customer_id, $campaign_id, $setup_id) 
    {
        $mysqli = Database::GetConnection();
        $sms_mode = Core::GetSmsMode();
        $sms_settings = SmsApi::GetSmsApiSettings();
        $user_id = 2;
            
        $sms_username = $sms_settings['primary_acc_user'];
        $sms_password = md5($sms_settings['primary_acc_pass']);
        $sms_api_url = $sms_settings['url_http_send']; 
        $phone_prefix = $sms_settings['phones_country_pre'].$phone_number;
        $url_text = urlencode($sms_text);
        $sms_max_parts = $sms_settings['enable_concat'];
            
        //Curl it
        $connection = curl_init();
        curl_setopt($connection, CURLOPT_URL, $sms_api_url);
        curl_setopt($connection, CURLOPT_POST, true);
        
        curl_setopt($connection, CURLOPT_POSTFIELDS, 'username='.$sms_username.'&password='.$sms_password.'&from='.$sender_id.'&to='.$phone_prefix.'&message='.$url_text.'&normalize=1&nounicode=1&'.
        (($sms_max_parts != '') ? '&max_parts='.$sms_max_parts : '')); 
        
        curl_setopt($connection, CURLOPT_RETURNTRANSFER, true); 
        $api_response = curl_exec($connection);
        curl_close($connection); 
            
        if (substr($api_response, 0, 2) == 'OK' ){//2 if (substr($api_response, 0, 2) == 'OK' )
            # Get message id
            $api_message_id = Core::StringFromDelimiters($api_response, 'OK:', ':');
            $api_message_cost = substr($api_response, -5);
            
            $sql_outbox = "INSERT INTO ".TABLE_SMS_OUTBOX." 
                           (batch_id, phone, status, message_id, sender, message, message_url, priority_queue, delivery_delay, scheduled_time, source_module, created_on, created_by, campaign_id, customer_id, carrier, charge, time_sent) 
                           VALUES ('AUTO', '$phone_number', '000', '$api_message_id', '$sender_id', '$sms_text', '$url_text','1', '', '', '', NOW(), '$user_id', '$campaign_id', '$customer_id', 'SMSAPI', '$api_message_cost', NOW())";
            mysqli_query($mysqli, $sql_outbox) or die ("Error while updating sms_outbox");
        }elseif(strpos($api_response, 'ERROR') !== false ){
            UpdateErrorLog('352', 'Unable to send single SMS, '.$api_response);
            SetErrorFlag($setup_id);
        }else{    
            UpdateErrorLog('353', 'Unable to send single SMS, '.$api_response);
            SetErrorFlag($setup_id);
        }//end 2 
    }
    
    ## ----------------------------------------------
    ## CALL WORKFLOW
    ## ----------------------------------------------
        //get balance   
        $objSmsBalance = SmsApi::GetSmsApiBalance();
        $sms_credits_balance = $objSmsBalance['credit_balance'];
        if ($sms_credits_balance > 0) { // 1
            $active_rules = GetActiveAutoSMS();
            if ($active_rules[1] > 0) { // 2 Check if any active campaigns
                for($i=0; $i < $active_rules[1]; $i++){ // 3 Loop through campaigns
                    $campaign_id = $active_rules[0][$i]['campaign_id'];
                    $sender_id = $active_rules[0][$i]['sender_id'];
                    $sms_text = $active_rules[0][$i]['sms_text'];
                    $error_flag = $active_rules[0][$i]['error_flag'];
                    $setup_id = $active_rules[0][$i]['id'];
                    
                        if ($error_flag == 1) { // 4
                            UpdateErrorLog('350', 'Auto SMS did not start. Previous operation finished with errors');
                            mail(_LOGS_EMAIL_TO, 'AUTO_SMS_ERROR: '._CONNECTOR_NAME, 'Auto SMS did not start (camp '.$auto_id.'). Previous operation finished with errors', 'From:'._LOGS_EMAIL_FROM);
                        } else {    
                        //hit the ground
                        $camp_customers = GetCampaignCustomers($campaign_id, $setup_id);
                        $result_statement = database_query($mysqli, $camp_customers, DATA_AND_ROWS, ALL_ROWS, FETCH_ASSOC, false);;
                            for($k=0; $k < $result_statement[1]; $k++){ // 5 Loop through customers and send SMS
                                $customer_id = $result_statement[0][$k]['id'];
                                $customer_phone = $result_statement[0][$k]['phone'];
                                //echo $customer_id.'<br />'; //debug
                                SendSmsApiAuto($customer_phone, $sender_id, $sms_text, $customer_id, $campaign_id, $setup_id);
                                SetLastExecutionDate($setup_id);
                            } //end 5 
                        } //end  4
                }//end 3
            } else { //else 2
                exit();
            } //end 2 
        } else { //else 1
            UpdateErrorLog('351', 'Auto SMS did not start. Zero balance');
            exit();
        } //end 1
    
?>