<?php session_start();
if (isset($_SESSION['logged']) && $_SESSION['logged'] == 'yes') {
		include ('../../../scripts/classes.php');
		if ($_SESSION['lang']=="EN"){$lang="EN"; include ('../../../lang/en.php');}elseif ($_SESSION['lang']=="GR"){$lang="GR";include ('../../../lang/gr.php');}else {$lang="EN";include ('../../../en.php');}
        $get_sms_provider = Core::GetSmsProvider();
        if ($get_sms_provider != 'SMSAPI') die('This page is accessible only when SMSAPI is setup as the SMS module provider');
		$page_title = _AUTOMATED_SMS;
        $user_info = getUserSettings($_SESSION['user']);
        foreach ($user_info as $user_settings){extract($user_settings);} 
        
        $max_chars = SmsApi::GetSmsApiMaxChars();
        ($sms_settings['max_chars'] != $max_chars) ? $lbl_multiple_sms_setup = $lbl_multiple_sms_setup_yes : $lbl_multiple_sms_setup = $lbl_multiple_sms_setup_no;
           
?>	
<!DOCTYPE html SYSTEM "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title><?php echo $page_title ?></title>
<link rel="shortcut icon" href="../../../img/favicon.png" />
<link href="../../../cms1.css" rel="stylesheet" type="text/css" /> 
</head>
<body>
<script>top.document.title=self.document.title;</script>
	<div>
		<fieldset>
		<legend><?php echo _AUTOMATED_SMS ?></legend>
			<div class="align-left">
        <?php     
        
        //Clear errors button
        if (isset($_POST['clearErrors']) AND $_POST['clearErrors']=='clear') {
            $clear_errors = SmsApi::ClearAutoSmsErrors();
            if ($clear_errors === true) {
                $message_output = Core::DrawSystemMessage(_ERRORS_WERE_CLEARED, 'INFO');
                echo $message_output;
            } else {
                $message_output = Core::DrawSystemMessage(_NO_ERRORS_FOUND, 'WARNING');
                echo $message_output;
            }
        }
            
        define ("DATAGRID_DIR", "../../../datagrid/");                     /* Ex.: "datagrid/" */ 
        define ("PEAR_DIR", "../../../datagrid/pear/");                    /* Ex.: "datagrid/pear/" */
        
        require_once(DATAGRID_DIR.'datagrid.class.php');
        require_once(PEAR_DIR.'PEAR.php');
        require_once(PEAR_DIR.'DB.php');
        include_once('../../../datagrid/config.inc.php');    
      
    
      ob_start();
      $db_conn = DB::factory('mysql');  /* don't forget to change on appropriate db type */
      $result_conn = $db_conn->connect(DB::parseDSN('mysql://'.$DB_USER.':'.$DB_PASS.'@'.$DB_HOST.'/'.$DB_NAME));
      if(DB::isError($result_conn)){ die($result_conn->getDebugInfo()); }   
    ##  *** put a primary key on the first place 
       ##  *** put a primary key on the first place  
      $sql = "SELECT
            AUT.id,
            AUT.campaign_id,
            AUT.description,
            AUT.time_set,
            AUT.sms_text,
            AUT.created_on, 
            DATE_FORMAT(AUT.created_on, '%d-%m-%Y (%H:%i)') AS f_created_on,
            AUT.created_by, 
            AUT.updated_on, 
            IF(AUT.updated_on <> '0000-00-00 00:00:00', DATE_FORMAT(AUT.updated_on, '%d-%m-%Y (%H:%i)'), '') AS f_updated_on,
            IF(AUT.last_run_time <> '0000-00-00 00:00:00', DATE_FORMAT(AUT.last_run_time, '%d-%m-%Y (%H:%i)'), '') AS last_run,
            AUT.updated_by,
            AUT.is_active,
            HEA.description AS campaign,
            IF ((SELECT COUNT(id) FROM sms_campaign_criteria CAC WHERE CAC.campaign_id =  AUT.campaign_id)=0, '<span class=\'red-span\'>"._NO_CRITERIA_ALERT."</span>', 
            (SELECT GROUP_CONCAT(CRI.description, CAC.operator, CAC.value SEPARATOR '<br />') FROM sms_campaign_criteria CAC, core_criteria CRI WHERE CAC.campaign_id = AUT.campaign_id AND CRI.id = CAC.criterion_id ) ) AS criteria_count,
            IF (AUT.error_flag = 1, '<span class=\'red-span\'>"._ERROR."</span>', '<img src=\'../../../img/select.gif\' alt=\'"._NO_ERRORS."\' title=\'"._NO_ERRORS."\'/>') AS error_flag
            FROM sms_auto_setup AUT 	
            LEFT OUTER JOIN sms_campaign_header HEA ON HEA.id= AUT.campaign_id";
//			LEFT OUTER JOIN sms_campaign_header ON sms_campaign_details.campaign_id= sms_campaign_header.id  
  
    ##  *** set needed options and create a new class instance 
      $debug_mode = false;        /* display SQL statements while processing */    
      $messaging = true;          /* display system messages on a screen */ 
      $unique_prefix = "aut_";    /* prevent overlays - must be started with a letter */
      $dgrid= new DataGrid($debug_mode, $messaging, $unique_prefix, DATAGRID_DIR);
      $dgrid->SetEncoding("utf8", "utf8_unicode_ci");
    ##  *** set data source with needed options
      $default_order_field = "AUT.id";
      $default_order_type = "DESC";
      $dgrid->DataSource($db_conn, $sql, $default_order_field, $default_order_type);

      $mode = isset($_REQUEST[$unique_prefix.'mode']) ? $_REQUEST[$unique_prefix.'mode'] : ''; 
      $rid = isset($_REQUEST[$unique_prefix.'rid']) ? $_REQUEST[$unique_prefix.'rid'] : '';
        
      $fill_from_array = array("1"=>_YES, "0"=>_NO );
        
    ## +---------------------------------------------------------------------------+
    ## | 2. General Settings:                                                      | 
    ## +---------------------------------------------------------------------------+
    $dgrid->SetPostBackMethod("post");
    $dgrid->AllowMultirowOperations(false);
    $multirow_operations = array(
        "edit"  => array("view"=>false),
        "delete"  => array("view"=>false),
        "details" => array("view"=>false), 
        "clone" => array("view"=>false),
        );
    $dgrid->SetMultirowOperations($multirow_operations);
    if ($_SESSION['lang']=="EN"){$dg_language = "en";}elseif ($_SESSION['lang']=="GR"){$dg_language = "gk";}else{$dg_language = "en";}  
    $dgrid->SetInterfaceLang($dg_language);  

    $modes = array(
         "add"	  =>array("view"=>false, "edit"=>false, "type"=>"button", "show_add_button"=>"outside"),
         "edit"	  =>array("view"=>false, "edit"=>true,  "type"=>"image" ),
         "cancel"  =>array("view"=>true, "edit"=>true,  "type"=>"button"),
         "details" =>array("view"=>true, "edit"=>true, "type"=>"image"),
         "delete"  =>array("view"=>true, "edit"=>false,  "type"=>"image"),
    );
    $dgrid->SetModes($modes);   
    
    $css_class = "default";
    $dgrid->SetCssClass($css_class);
    
    $header_toolbar = '<div style="float:left;margin-top:20px;margin-bottom:-20px"><form action="smsapi_prepare_auto.php"><input type="submit" class="button" value="'._ADD.'"/></form></div>';
    $header_toolbar .= '<div style="float:left;margin-top:20px;margin-bottom:-20px; margin-left:10px"><form action="smsapi_auto_setup.php" method="post"><input type="hidden" name="clearErrors" value="clear" /><input type="submit" class="button" value="'._CLEAR_ERRORS.'"/></form></div>';
    
    $dgrid->SetCaption($header_toolbar);

    
    ## +---------------------------------------------------------------------------+
    ## | 3. Printing & Exporting Settings:                                         | 
    ## +---------------------------------------------------------------------------+
    ##  *** set printing option: true(default) or false 
      $printing_option = true;
      $dgrid->AllowPrinting($printing_option);
	  $exporting_option = false;
		$exporting_directory = "../../../exports";               
		$export_all = false;
		$dgrid->AllowExporting($exporting_option, $exporting_directory, $export_all);
		$exporting_types = array("excel"=>"true", "pdf"=>"false", "xml"=>"false");
		$dgrid->AllowExportingTypes($exporting_types);
    
    ## +---------------------------------------------------------------------------+
    ## | 4. Sorting & Paging Settings:                                             | 
    ## +---------------------------------------------------------------------------+
    ##  *** set paging option: true(default) or false 
      $paging_option = true;
      $rows_numeration = false;
      $numeration_sign = "";       
      $dgrid->AllowPaging($paging_option, $rows_numeration, $numeration_sign);
    ##  *** set paging settings
      $bottom_paging = array("results"=>true, "results_align"=>"left", "pages"=>true, "pages_align"=>"center", "page_size"=>true, "page_size_align"=>"right");
      $top_paging = array();
      $pages_array = array("25"=>"25", "50"=>"50", "100"=>"100", "250"=>"250");
      $default_page_size = 25;
      $dgrid->SetPagingSettings($bottom_paging, $top_paging, $pages_array, $default_page_size);
    
    ## +---------------------------------------------------------------------------+
    ## | 5. Filter Settings:                                                       | 
    ## +---------------------------------------------------------------------------+
    ##  *** set filtering option: true or false(default)
      $filtering_option = false;
      $show_search_type = true;
      $dgrid->AllowFiltering($filtering_option, $show_search_type);
    ##  *** set additional filtering settings
    ##  *** tips: use "," (comma) if you want to make search by some words, for ex.: hello, bye, hi
      $filtering_fields = array(   	
	 );	 
      $dgrid->SetFieldsFiltering($filtering_fields);
    
    ## +---------------------------------------------------------------------------+
    ## | 6. View Mode Settings:                                                    | 
    ## +---------------------------------------------------------------------------+
    ##  *** set view mode table properties
      $vm_table_properties = array("width"=>"100%");
      $dgrid->SetViewModeTableProperties($vm_table_properties);  
  
	  $vm_colimns = array(
	    "id" => array("header"=>"id", "type"=>"label", "align"=>"left", "case"=>"normal", "summarize"=>"false", "sort_type"=>"string", "sort_by"=>"", "visible"=>"true", "on_js_event"=>"",  "rel"=>""),
        "description" => array("header"=>_DESCRIPTION, "type"=>"label", "align"=>"left", "wrap"=>"nowrap", "text_length"=>"", "tooltip"=>"true", "tooltip_type"=>"simple", "case"=>"normal", "summarize"=>"false", "sort_type"=>"string", "sort_by"=>"", "visible"=>"true", "on_js_event"=>""),
        "campaign" => array("header"=>_CAMPAIGN, "type"=>"label", "align"=>"left", "wrap"=>"nowrap", "text_length"=>"50", "tooltip"=>"true", "tooltip_type"=>"simple", "case"=>"normal", "summarize"=>"false", "sort_type"=>"string", "sort_by"=>"", "visible"=>"true", "on_js_event"=>""),
        "time_set" => array("header"=>_TIME_TO_BE_EXECUTED, "type"=>"label", "align"=>"left", "wrap"=>"nowrap", "tooltip"=>"true", "tooltip_type"=>"simple", "case"=>"normal", "summarize"=>"false", "sort_type"=>"string", "sort_by"=>"", "visible"=>"true", "on_js_event"=>""),
		"is_active"=>array("header"=>_ACTIVE_FEMALE, "type"=>"checkbox",  "align"=>"center", "sort_type"=>"string", "sort_by"=>"", "visible"=>"true", "on_js_event"=>"", "true_value"=>1, "false_value"=>0),											
        "criteria_count" => array("header"=>_CRITERIA_IN_USE, "type"=>"label", "align"=>"left", "wrap"=>"nowrap", "tooltip"=>"true", "tooltip_type"=>"simple", "case"=>"normal", "summarize"=>"false", "sort_type"=>"string", "sort_by"=>"", "visible"=>"true", "on_js_event"=>""),
        "error_flag" => array("header"=>_STATUS, "type"=>"label", "align"=>"center", "wrap"=>"nowrap", "tooltip"=>"true", "tooltip_type"=>"simple", "case"=>"normal", "summarize"=>"false", "sort_type"=>"string", "sort_by"=>"", "visible"=>"true", "on_js_event"=>""),
         "last_run"     => array("header"=>_LAST_EXECUTION, "type"=>"label",  "align"=>"left", "width"=>"", "wrap"=>"nowrap", "text_length"=>"-1", "tooltip"=>"true", "tooltip_type"=>"floating", "case"=>"normal", "summarize"=>"false", "sort_type"=>"string", "sort_by"=>"created_on", "visible"=>"true", "on_js_event"=>""),
        "f_created_on"     => array("header"=>_CREATED_ON, "type"=>"label",  "align"=>"left", "width"=>"", "wrap"=>"nowrap", "text_length"=>"-1", "tooltip"=>"true", "tooltip_type"=>"floating", "case"=>"normal", "summarize"=>"false", "sort_type"=>"string", "sort_by"=>"created_on", "visible"=>"true", "on_js_event"=>""), 
        "created_by"     => array("header"=>_CREATED_BY, "type"=>"label",  "align"=>"left", "width"=>"", "wrap"=>"nowrap", "text_length"=>"-1", "tooltip"=>"true", "tooltip_type"=>"floating", "case"=>"normal", "summarize"=>"false", "sort_type"=>"string", "sort_by"=>"", "visible"=>"true", "on_js_event"=>""),    
        "f_updated_on"     => array("header"=>_UPDATED_ON, "type"=>"label",  "align"=>"left", "width"=>"", "wrap"=>"nowrap", "text_length"=>"-1", "tooltip"=>"true", "tooltip_type"=>"floating", "case"=>"normal", "summarize"=>"false", "sort_type"=>"string", "sort_by"=>"updated_on", "visible"=>"true", "on_js_event"=>""), 
        "updated_by"     => array("header"=>_UPDATED_BY, "type"=>"label",  "align"=>"left", "width"=>"", "wrap"=>"nowrap", "text_length"=>"-1", "tooltip"=>"true", "tooltip_type"=>"floating", "case"=>"normal", "summarize"=>"false", "sort_type"=>"string", "sort_by"=>"", "visible"=>"true", "on_js_event"=>""),
      );
      $dgrid->SetColumnsInViewMode($vm_colimns);
    
    
    
    ## +---------------------------------------------------------------------------+
    ## | 7. Add/Edit/Details Mode Settings:                                        | 
    ## +---------------------------------------------------------------------------+
    ##  *** set add/edit mode table properties
      $em_table_properties = array("width"=>"100%");
      $dgrid->SetEditModeTableProperties($em_table_properties);
    ##  *** set details mode table properties
      $dm_table_properties = array("width"=>"100%");
      $dgrid->SetDetailsModeTableProperties($dm_table_properties);
    ##  ***  set settings for add/edit/details modes
	  
	  $table_name  = "sms_auto_setup";
      $primary_key = "id";
      $condition   = "";
      $dgrid->SetTableEdit($table_name, $primary_key, $condition);	     
	  
      $em_columns ='';
      if ($mode == "details"){
      $em_columns = array(		
        "description"=>array("header"=>$lbl_grid_description, "type"=>"textbox", "req_type"=>"ry", "width"=>"300px", "title"=>"", "readonly"=>"false", "maxlength"=>"-1", "default"=>"", "unique"=>"false", "unique_condition"=>"", "visible"=>"true", "on_js_event"=>""),
        "sms_text"  =>array("header"=>_SMS_TEXT, "type"=>"textarea",   "req_type"=>"ry", "width"=>"210px", "title"=>_SMS_TEXT, "readonly"=>"false", "maxlength"=>"160", "default"=>"", "unique"=>"false", "unique_condition"=>"", "visible"=>"true", "on_js_event"=>"", "edit_type"=>"simple", "resizable"=>"false", "upload_images"=>"false", "rows"=>"7", "cols"=>"50"),
        "time_set"=>array("header"=>_EXECUTION_TIME, "type"=>"text", "req_type"=>"rn", "width"=>"300px", "title"=>"", "readonly"=>"false", "maxlength"=>"-1", "default"=>"", "unique"=>"false", "unique_condition"=>"", "visible"=>"true", "on_js_event"=>""),
        //"max_value"=>array("header"=>_MAX_ALLOWED_AMOUNT, "type"=>"textbox", "req_type"=>"snp", "width"=>"300px", "title"=>"", "readonly"=>"false", "maxlength"=>"-1", "default"=>"", "unique"=>"false", "unique_condition"=>"", "visible"=>"true", "on_js_event"=>""),				
        "is_active"   =>array("header"=>$lbl_grid_active, "source"=>$fill_from_array, "table"=>"cls_categories", "field"=>"active", "type"=>"enum",  "width"=>"210px", "title"=>"", "readonly"=>"false", "default"=>"1", "unique"=>"false", "unique_condition"=>"", "visible"=>"true")												
      );	   	
      }
        $dgrid->SetColumnsInEditMode($em_columns);
   
     
    ## +---------------------------------------------------------------------------+
    ## | 8. Bind the DataGrid:                                                     | 
    ## +---------------------------------------------------------------------------+
    ##  *** bind the DataGrid and draw it on the screen
      $dgrid->initFilteringState = "opened";
	  $dgrid->firstFieldFocusAllowed = true;
      $dgrid->Bind();        
      
        if(($mode == "update") && ($rid != "-1") && $dgrid->IsOperationCompleted()) {
            $update_sql = "UPDATE ".$table_name." SET updated_by = '".$username."' WHERE id = '".$rid."'";
            mysqli_query($mysqli, $update_sql) or die("Query failed : " . mysqli_error($mysqli));
            echo "<meta http-equiv=\"refresh\" content=\"0;URL=".$_SERVER['PHP_SELF']."\">";  
        }
        
      ob_end_flush();
    
    ################################################################################  	  
  
?>
        </div>
		</fieldset>
	</div>
</body>
</html>
<?php
} else {
    header('Location: login.php');
}
?>
