<?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');}
		$user_id = Core::GetUserId();
        $array = getGlobalSettings(); foreach ($array as $settings){extract($settings);}
		$page_title = $lbl_page_title_campaign;
		$mode = $lbl_mode_manage;
?>	
<!DOCTYPE html PUBLIC "-//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 $mode ?></legend>
			<div class="align-left">
			<?php
        $act = isset($_GET['act']) ? $_GET['act'] : "";
        $campaign_id = isset($_GET['campaign_id']) ? $_GET['campaign_id'] : "";
        $campaign_p = isset($_GET['campaign_p']) ? $_GET['campaign_p'] : "";
        $camp_page_size = isset($_GET['camp_page_size']) ? $_GET['camp_page_size'] : "";
    ################################################################################
    ## +---------------------------------------------------------------------------+
    ## | 1. Creating & Calling:                                                    | 
    ## +---------------------------------------------------------------------------+
    ##  *** define a relative (virtual) path to datagrid.class.php file
    ##  *** (relatively to the current file)
    ##  *** RELATIVE PATH ONLY ***     
      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');
    
    ##
    ##  *** creating variables that we need for database connection 

      // includes database connection parameters
      include_once('../../../datagrid/config.inc.php');
    
      $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 
      $sql = "SELECT
				sms_campaign_header.id,
				sms_campaign_categ.description AS category,
				count_phones,
				DATE_FORMAT(sms_campaign_header.created_on, '%d-%m-%Y %H:%i') AS created_on,
				users.id AS created_by_id,
				users.username AS created_by,
				IF (sms_campaign_header.updated_on <> '0000-00-00 00:00:00', DATE_FORMAT(sms_campaign_header.updated_on, '%d-%m-%Y %H:%i'), '"._NO_CHANGE_YET."') AS updated_on,
				sms_campaign_header.updated_by,
				sms_campaign_header.updated_by AS updated_by_dummy,
				sms_campaign_header.active,
                IF(sms_campaign_header.id = ".(int)$campaign_id.", CONCAT('<font color=\"#ff0000\"><b>',sms_campaign_header.description,'</b></font><img src=\"../../../img/cal_minus.gif\" />'), sms_campaign_header.description) AS description,
            CONCAT ('<img src=\"../../../img/criteria.gif\" alt='\"_CRITERIA_IN_USE\"' /> (',
            (SELECT COUNT(id) FROM sms_campaign_criteria scc WHERE scc.campaign_id = sms_campaign_header.id), ')') AS link_to_criteria,
				'<img src=\"../../../img/get.gif\" alt=\"$lbl_fill\">' AS fill,
                '<img src=\"../../../img/remove.gif\" alt=\"$lbl_discharge\">' AS discharge
            FROM sms_campaign_header 
			LEFT OUTER JOIN users ON sms_campaign_header.created_by = users.id 
			lEFT OUTER JOIN sms_campaign_categ ON sms_campaign_header.category= sms_campaign_categ.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 = "hed_";    /* prevent overlays - must be started with a letter */
      $dgrid = new DataGrid($debug_mode, $messaging, $unique_prefix, DATAGRID_DIR);
	  //webnail get current mode
	  //$mode = isset($_GET[$unique_prefix.'mode']) ? $_GET[$unique_prefix.'mode'] : ""; 
	  $mode = isset($_REQUEST[$unique_prefix.'mode']) ? $_REQUEST[$unique_prefix.'mode'] : ""; 
      //$rid = (isset($_REQUEST[$unique_prefix.'rid'])) ? $_REQUEST[$unique_prefix.'rid'] : '';
	  
    ##  *** set encoding and collation (default: utf8/utf8_unicode_ci)
      $dg_encoding = "utf8";
      $dg_collation = "utf8_unicode_ci";
      $dgrid->SetEncoding($dg_encoding, $dg_collation);
    ##  *** set data source with needed options
      $default_order_field = "created_on";
      $default_order_type = "DESC";
      $dgrid->DataSource($db_conn, $sql, $default_order_field, $default_order_type);
      
    
    ## +---------------------------------------------------------------------------+
    ## | 2. General Settings:                                                      | 
    ## +---------------------------------------------------------------------------+
	##  *** allow multirow operations
        $multirow_option = false;
        $dgrid->AllowMultirowOperations($multirow_option);
        $multirow_operations = array(
            "edit"  => array("view"=>false),
            "delete"  => array("view"=>false),
            "details" => array("view"=>false), 
        );
        $dgrid->SetMultirowOperations($multirow_operations);
		//webnail
		if ($_SESSION['lang']=="EN"){
			$dg_language = "en";
		}elseif ($_SESSION['lang']=="GR"){	
			$dg_language = "gk";
		}else{	
			$dg_language = "en";
		}
		$dgrid->SetInterfaceLang($dg_language);  
        $postback_method = "ajax";
        $dgrid->SetPostBackMethod($postback_method);
         ##  *** set modes for operations ("type" => "link|button|image")
    ##  *** "view" - view mode | "edit" - add/edit/details modes
    ##  *** "byFieldValue"=>"fieldName" - make the field to be a link to edit mode page
    $modes = array(
         "add"	  =>array("view"=>true, "edit"=>false, "type"=>"button", "show_add_button"=>"outside"),
         "edit"	  =>array("view"=>true, "edit"=>true,  "type"=>"image" ),
         "cancel"  =>array("view"=>true, "edit"=>true,  "type"=>"button"),
         "details" =>array("view"=>false, "edit"=>false, "type"=>"image"),
         "delete"  =>array("view"=>false, "edit"=>false,  "type"=>"image"),

    );
    $dgrid->SetModes($modes);   
    ##  *** set CSS class for datagrid
    ##  *** "default|blue|gray|green|pink|empty|x-blue|x-gray|x-green" or your own css style
     $css_class = "default";
     $dgrid->SetCssClass($css_class);
    ##  *** set DataGrid caption
    $dg_caption = "";
      $dgrid->SetCaption($dg_caption);
    
    ## +---------------------------------------------------------------------------+
    ## | 3. Printing & Exporting Settings:                                         | 
    ## +---------------------------------------------------------------------------+
    ##  *** set printing option: true(default) or false 
      $printing_option = true;
      $dgrid->AllowPrinting($printing_option);
	  $exporting_option = true;
		$exporting_directory = "../../../exports/";               
		$export_all = true;
		$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("15"=>"15", "25"=>"25", "50"=>"50");
      $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 = true;
      $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(
      $lbl_grid_code=>array("type"=>"textbox", "table"=>"sms_campaign_header", "field"=>"id", "filter_condition"=>"", "show_operator"=>"false", "default_operator"=>"=", "case_sensitive"=>"false","comparison_type"=>"numeric", "width"=>"", "on_js_event"=>""),	  
      $lbl_grid_description=>array("type"=>"textbox", "table"=>"sms_campaign_header", "field"=>"description", "filter_condition"=>"", "show_operator"=>"false", "default_operator"=>"like", "case_sensitive"=>"false","comparison_type"=>"string", "width"=>"", "on_js_event"=>""),
      $lbl_grid_category=>array("type"=>"dropdownlist", "table"=>"sms_campaign_categ", "field"=>"description", "condition"=>"", "show_operator"=>"false", "case_sensitive"=>"false","comparison_type"=>"string", "width"=>"", "on_js_event"=>""),    
	 );
      $dgrid->SetFieldsFiltering($filtering_fields);
    
    ## +---------------------------------------------------------------------------+
    ## | 6. View Mode Settings:                                                    | 
    ## +---------------------------------------------------------------------------+
    ##  *** set view mode table properties
      $vm_table_properties = array("width"=>"100%");
      $dgrid->SetViewModeTableProperties($vm_table_properties);  
    ##  *** set columns in view mode
    ##  *** Ex.: "on_js_event"=>"onclick='alert(\"Yes!!!\");'"
    ##  ***      "barchart" : number format in SELECT SQL must be equal with number format in max_value
      $vm_colimns = array(      
        "id"     		  => array("header"=>$lbl_grid_code, "type"=>"label", "align"=>"left", "width"=>"20px", "wrap"=>"nowrap", "text_length"=>"-1", "tooltip"=>"true", "tooltip_type"=>"floating", "case"=>"normal", "summarize"=>"false", "sort_type"=>"string", "sort_by"=>"", "visible"=>"true", "on_js_event"=>"",  "field_data"=>"", "rel"=>"", "title"=>""),
        "description"     => array("header"=>$lbl_grid_description, "type"=>"label", "field_key_0"=>"category","field_data"=>"categ", "target"=>"_self", "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"=>""),
		"category" => array("header"=>$lbl_grid_category, "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"=>""),	
		"count_phones" => array("header"=>$lbl_grid_count_phones, "type"=>"label",      "align"=>"left", "wrap"=>"nowrap", "text_length"=>"50", "tooltip"=>"true", "tooltip_type"=>"simple", "case"=>"normal", "summarize"=>"true", "sort_type"=>"string", "sort_by"=>"", "visible"=>"true", "on_js_event"=>"", "thousands_separator"=>"."),			
		"created_on" => array("header"=>$lbl_grid_created_on, "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"=>""),	
        "created_by" => array("header"=>$lbl_grid_created_by, "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"=>""),			
  	    "updated_on" => array("header"=>$lbl_grid_updated_on, "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"=>""),
        "active"=>array("header"=>$lbl_grid_active, "type"=>"checkbox",  "align"=>"center", "sort_type"=>"string", "sort_by"=>"", "visible"=>"true", "on_js_event"=>"", "true_value"=>1, "false_value"=>0),
        "link_to_criteria" =>array("header"=>_CRITERIA_IN_USE, "type"=>"link", "align"=>"center",  "wrap"=>"nowrap", "visible"=>"true", "field_key"=>"id", "field_data"=>"link_to_criteria", "rel"=>"", "title"=>"", "target"=>"_self", "href"=>"camp_list.php?act=details&campaign_id={0}&campaign_p=".$campaign_p."&camp_page_size=".$camp_page_size),    	
        'fill'=>array("header"=>_FILL_NOUN, "type"=>"link", "align"=>"center", "summarize"=>"false", "visible"=>"true", "on_js_event"=>"onClick=\"return confirmFill()\"", "field_key"=>"id", "field_key_1"=>"field_name_1", "field_data"=>"field_name_2", "target"=>"_self", "href"=>"camp_list.php?hed_mode=fill&hed_rid={0}", "sortable"=>"false"),
        'discharge'=>array("header"=>_DISCHARGE_NOUN, "type"=>"link", "align"=>"center", "summarize"=>"false", "visible"=>"true", "on_js_event"=>"onClick=\"return confirmSubmit()\"", "field_key"=>"id", "field_key_1"=>"field_name_1", "field_data"=>"field_name_2", "rel"=>"", "target"=>"_self", "href"=>"camp_list.php?hed_mode=reset&hed_rid={0}", "sortable"=>"false"),	
        	      	   				
      );
	  $dgrid->SetSummarizeNumberFormat("0", ",", ".");
      $dgrid->SetColumnsInViewMode($vm_colimns);
## MASTER/DETAIL
if($act == "details"){
        ##  *** put a primary key on the first place 
        $sql=" SELECT   
            scc.id, 
            scc.criterion_id, 
            scc.operator, 
            scc.value, 
            scc.created_on, 
            scc.created_by,
            ccr.description AS criterion_name
        FROM sms_campaign_criteria scc
        LEFT OUTER JOIN core_criteria ccr ON scc.criterion_id= ccr.id 
        WHERE scc.campaign_id = ".(int)$campaign_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 = "ccc_";    /* prevent overlays - must be started with a letter */
         $dgrid1 = new DataGrid($debug_mode, $messaging, $unique_prefix, DATAGRID_DIR);

        
        ##  *** set data source with needed options
         $default_order_field = "id";
         $default_order_type = "ASC";
         $dgrid1->dataSource($db_conn, $sql, $default_order_field, $default_order_type);
         
        ##  *** set DataGrid caption
         $dg_caption = "<div style='width:100%;background-color:#F4F9FB;padding:1px'><h2><img src='../../../img/criteria.gif' /> "._CRITERIA_IN_USE."</h2></div>";
         $dgrid1->setCaption($dg_caption);
         $paging_option = false;
        $rows_numeration = true;
        $numeration_sign = "#";       
        $dgrid1->AllowPaging($paging_option, $rows_numeration, $numeration_sign);
        
        ##  *** set variables that used to get access to the page (like: my_page.php?act=34&id=56 etc.) 
        $postback_method = "ajax";
        $dgrid1->SetPostBackMethod($postback_method);
        
         $http_get_vars = array("act", "campaign_id");
         $dgrid1->SetHttpGetVars($http_get_vars);
         $modes = array(
         "add"	  =>array("view"=>true, "edit"=>false, "type"=>"button", "show_add_button"=>"outside"),
         "edit"	  =>array("view"=>true, "edit"=>true,  "type"=>"image" ),
         "cancel"  =>array("view"=>true, "edit"=>true,  "type"=>"button"),
         "details" =>array("view"=>false, "edit"=>false, "type"=>"image"),
         "delete"  =>array("view"=>true, "edit"=>true,  "type"=>"button"),

        );
        $dgrid1->SetModes($modes);   

        ## +---------------------------------------------------------------------------+
        ## | 3. Printing & Exporting Settings:                                         | 
        ## +---------------------------------------------------------------------------+
        ##  *** set printing option: true(default) or false 
         $printing_option = false;
         $dgrid1->AllowPrinting($printing_option);
         $sorting_option = false;
         $dgrid1->AllowSorting($sorting_option); 
        
        ## +---------------------------------------------------------------------------+
        ## | 6. View Mode Settings:                                                    | 
        ## +---------------------------------------------------------------------------+
        ##  *** set view mode table properties
         $vm_table_properties = array("width"=>"40%");
         $dgrid1->setViewModeTableProperties($vm_table_properties);  
        ##  *** set columns in view mode
        ##  *** Ex.: "on_js_event"=>"onclick='alert(\"Yes!!!\");'"
        ##  ***      "barchart" : number format in SELECT SQL must be equal with number format in max_value
         $vm_colimns = array(  
            "criterion_name" =>array("header"=>$lbl_criterion,  "type"=>"label", "align"=>"left", "width"=>"", "wrap"=>"nowrap", "text_length"=>"-1",  "case"=>"normal", "summarize"=>"false", "sort_by"=>"", "visible"=>"true", "on_js_event"=>""),
            "operator"       =>array("header"=>$lbl_operator,   "type"=>"label", "align"=>"left", "width"=>"", "wrap"=>"nowrap", "text_length"=>"-1",   "case"=>"normal", "summarize"=>"false", "sort_by"=>"", "visible"=>"true", "on_js_event"=>""),
            "value"          =>array("header"=>$lbl_grid_value,   "type"=>"label", "align"=>"left", "width"=>"", "wrap"=>"nowrap", "text_length"=>"-1",  "case"=>"normal", "summarize"=>"false", "sort_by"=>"", "visible"=>"true", "on_js_event"=>""),            
         );
         $dgrid1->setColumnsInViewMode($vm_colimns);
        
        ## +---------------------------------------------------------------------------+
        ## | 7. Add/Edit/Details Mode settings:                                        | 
        ## +---------------------------------------------------------------------------+
        ##  ***  set settings for edit/details mode
         $em_table_properties = array("width"=>"50%");
         $dgrid1->SetEditModeTableProperties($em_table_properties);
        ##  ***  set settings for edit/details mode
         $table_name = "sms_campaign_criteria";
         $primary_key = "id";
         $condition = "";
         $dgrid1->setTableEdit($table_name, $primary_key, $condition);

         $drop_down_operators = array("="=>$lbl_equals_to, ">"=>$lbl_greater_than, ">="=>$lbl_greater_equal_than, "<"=>$lbl_less_than,  "<="=>$lbl_less_equal_than,  );
         
         $em_columns = array(
            "campaign_id"        =>array("header"=>$lbl_campaign_code, "type"=>"textbox",  "width"=>"210px", "title"=>$lbl_campaign_code, "default"=>(int)$campaign_id, "readonly"=>"true"),
            "criterion_id"        =>array("header"=>$lbl_criterion,           "type"=>"enum",  "width"=>"210px", "req_type"=>"ry", "title"=>$lbl_criterion),
            "operator"       =>array("header"=>$lbl_operator,          "type"=>"enum",     "source"=>$drop_down_operators, "view_type"=>"dropdownlist",  "width"=>"140px",  "req_type"=>"ry", "title"=>$lbl_grid_value),
            "value"             =>array("header"=>$lbl_grid_value,          "type"=>"textbox",  "width"=>"210px", "req_type"=>"", "title"=>$lbl_grid_value),
            "delimiter_1"    =>array("inner_html"=>"</br>".$lbl_and_criterion_condition_text),
         );
         $dgrid1->SetColumnsInEditMode($em_columns);
        ##  *** set foreign keys for add/edit/details modes (if there are linked tables)
        ##  *** Ex.: "condition"=>"TableName_1.FieldName > 'a' AND TableName_1.FieldName < 'c'"
        ##  *** Ex.: "on_js_event"=>"onclick='alert(\"Yes!!!\");'"
         $foreign_keys = array(
           "criterion_id"=>array("table"=>"core_criteria", "field_key"=>"id", "field_name"=>"description", "view_type"=>"dropdownlist", "order_by_field"=>"description", "order_type"=>"ASC", "condition"=>"active=1"),
           //"campaign_id"=>array("table"=>"sms_campaign_header", "field_key"=>"id", "field_name"=>"description", "view_type"=>"dropdownlist", "order_by_field"=>"description", "order_type"=>"ASC"),
         ); 
         $dgrid1->SetForeignKeysEdit($foreign_keys);
    }
    
    
    ## +---------------------------------------------------------------------------+
    ## | 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_campaign_header";
      $primary_key = "id";
      $condition   = "";
      $dgrid->SetTableEdit($table_name, $primary_key, $condition);
      $em_columns = array(); //initialize value
      
   	if ($mode=="add"){	     
      $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"=>""),	
            "category" =>array("header"=>$lbl_grid_category, "type"=>"foreign_key","req_type"=>"ry", "title"=>"", "readonly"=>"false", "default"=>"", "unique"=>"false", "unique_condition"=>"", "visible"=>"true"),
            "created_on" =>array("header"=>$lbl_grid_created_on, "type"=>"hidden",  "default"=>date("Y-m-d H:i:s", time()), "req_type"=>"sy", "width"=>"210px", "on_js_event"=>""),	
            "created_by" =>array("header"=>$lbl_grid_created_by,  "type"=>"hidden", "default"=>$user_id),																
      );
	  }elseif ($mode=="details"){
	  $em_columns = array(
            "id"   =>array("header"=>$lbl_grid_code, "type"=>"label", "width"=>"30px"),			
            "description"=>array("header"=>$lbl_grid_description, "type"=>"label"),	
            "category" =>array("header"=>$lbl_grid_category, "type"=>"foreign_key"),
            "count_phones"=>array("header"=>$lbl_grid_count_phones, "type"=>"label"), 
			"created_on" =>array("header"=>$lbl_grid_created_on, "type"=>"datetimedmy", "value"=>date("d-m-Y H:i:s")),	
            "created_by" =>array("header"=>$lbl_grid_created_by,  "type"=>"foreign_key"),	
            "updated_on" =>array("header"=>$lbl_grid_updated_on, "type"=>"datetimedmy", "value"=>date("d-m-Y H:i:s")),			
            "updated_by" =>array("header"=>$lbl_grid_updated_by,  "type"=>"foreign_key"),		
			"active" =>array("header"=>$lbl_grid_active,  "type"=>"checkbox"),														
      );	   
	  }elseif ($mode=="edit"){
	  $em_columns = array(
            "id"   =>array("header"=>$lbl_grid_code, "type"=>"label", "width"=>"30px", "title"=>"", "readonly"=>"true", "visible"=>"true"),			
            "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"=>""),	
            "category" =>array("header"=>$lbl_grid_category, "type"=>"foreign_key","req_type"=>"ry", "title"=>"", "readonly"=>"false", "default"=>"", "unique"=>"false", "visible"=>"true"),		
            "updated_by" =>array("header"=>$lbl_grid_updated_by,  "type"=>"hidden","req_type"=>"ry", "default"=>$user_id, "value"=>$user_id, "readonly"=>"false"),															
      );	  
	  }  
      $dgrid->SetColumnsInEditMode($em_columns);
    ##  *** set auto-generated columns in edit mode
      $auto_column_in_edit_mode = false;
      $dgrid->SetAutoColumnsInEditMode($auto_column_in_edit_mode);
    ##  *** set foreign keys for add/edit/details modes (if there are linked tables)
    ##  *** Ex.: "field_name"=>"CONCAT(field1,','field2) as field3" 
    ##  *** Ex.: "condition"=>"TableName_1.FieldName > 'a' AND TableName_1.FieldName < 'c'"
    ##  *** Ex.: "on_js_event"=>"onclick='alert(\"Yes!!!\");'"
      $foreign_keys = array(
        "category"=>array("table"=>"sms_campaign_categ", "field_key"=>"id", "field_name"=>"description", "view_type"=>"dropdownlist", "order_by_field"=>"id", "order_type"=>"ASC", "condition" =>"active = 1"),	
        "created_by"=>array("table"=>"users", "field_key"=>"id", "field_name"=>"username", "view_type"=>"dropdownlist", "order_by_field"=>"id", "order_type"=>"ASC", "on_js_event"=>""),		
        "updated_by"=>array("table"=>"users", "field_key"=>"id", "field_name"=>"username", "view_type"=>"dropdownlist", "order_by_field"=>"id", "order_type"=>"ASC", "on_js_event"=>""),					
      ); 
      $dgrid->SetForeignKeysEdit($foreign_keys);
     
    ## +---------------------------------------------------------------------------+
    ## | 8. Bind the DataGrid:                                                     | 
    ## +---------------------------------------------------------------------------+
    ##  *** bind the DataGrid and draw it on the screen
    ob_start();    
      $dgrid->Bind();            
      if($act == "details"){ $dgrid1->Bind();}
    ob_end_flush();  	  
    ?>
    <script>
    function confirmSubmit()
    {
    var agree=confirm("<?php echo $lbl_confirm_reset ?>");
    if (agree)
    	return true ;
    else
    	return false ;
    }
    </script>
    <script>
    function confirmFill()
    {
    var agree=confirm("<?php echo $lbl_confirm_fill; ?>");
    if (agree)
    	return true ;
    else
    	return false ;
    }
    </script>
<?php if(isset($_GET[$unique_prefix.'mode']) && ($_GET[$unique_prefix.'mode'] == "reset") )
		{
  // PREPARE THE IDs selected FOR A QUERY
				   	$rid =$_GET['hed_rid'];
				   	//echo "$rid";
					$sql = "DELETE FROM sms_campaign_details WHERE campaign_id ='$rid'";
					mysqli_query($mysqli, $sql);
	//update header with count_phones
					$count_sql = "SELECT COUNT(id) AS rows_counter FROM sms_campaign_details WHERE campaign_id='$rid'";
					$result_count = mysqli_query($mysqli, $count_sql) or die(mysqli_error($mysqli));
                    $numrows_count = 0;
                        while ($rows_counter = mysqli_fetch_array($result_count, MYSQLI_ASSOC)) {
                            $numrows_count = $rows_counter['rows_counter'];
                        }    
					//echo $numrows_count;
					$sql_up = "UPDATE sms_campaign_header SET count_phones ='$numrows_count' WHERE id='$rid'";
				 	$res = mysqli_query($mysqli, $sql_up) or die(mysqli_error($mysqli));
   // refresh your page
   echo "<meta http-equiv=\"refresh\" content=\"0;URL=".$_SERVER['PHP_SELF']."\">"; 
			} 
    ################################################################################   
if(isset($_GET[$unique_prefix.'mode']) && ($_GET[$unique_prefix.'mode'] == "fill") ){
				   	$rid =$_GET['hed_rid'];
				   	//echo "$rid";
    $sql_criteria = "SELECT
                    caa.criterion_id, 
                    caa.operator, 
                    caa.value,
                    ccr.description,
                    ccr.field,
                    ccr.is_calculated,
                    ccr.rule
                    FROM sms_campaign_criteria caa 
                    LEFT OUTER JOIN core_criteria ccr ON caa.criterion_id= ccr.id 
                    WHERE campaign_id='$rid'";
	$result_criteria = mysqli_query($mysqli, $sql_criteria) or die("Query failed : " . mysqli_error($mysqli));
	if (mysqli_num_rows($result_criteria) == 0){                                                    ## if no criteria are used select all customers	
        $sql_cust_target = "SELECT cust.id, cust.phone FROM cls_customers cust";                        ## select all customers
        $statement = $sql_cust_target;                                                                                           
        //echo $sql_cust_target;                                                                   ## print sql statement
        //die("NO RESULTS ERROR");
	}else {	
        $sql_cust_target = "SELECT cust.id, cust.phone FROM cls_customers cust WHERE ";   
        //preapare the function for the birthdays criterion
       ## FUNCTION DECLARATION added for SMS Module on 1.4.7 18/09/2014
       function DaysToBirthday ($value){ 
            $array_sms = getSMSSettings(); foreach ($array_sms as $sms_settings){extract($sms_settings);} 
            $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;
       }  
               
        while ($cri = mysqli_fetch_array($result_criteria, MYSQLI_ASSOC)) {
            //check if the criterion is calculated or not
            if ($cri['is_calculated'] != 1) {$sql_cust_target .= $cri['field']." ".$cri['operator']." '".$cri['value']."' AND ";}
            if ($cri['is_calculated'] == 1) { 

                //check all functions one by one
                $rule_function = $cri['rule'];
                if ($rule_function == 'ValidPhonesRule') $function_result = ValidPhonesRule($cri['value']);
                if ($rule_function == 'DaysToBirthday' AND $cri['operator'] == '='){ 
                    $function_result = DaysToBirthday($cri['value']);
                }elseif ($rule_function == 'DaysToBirthday' AND $cri['operator'] != '='){
                    $function_result = 'ERROR';
                }
                if ($function_result == 'ERROR'){
                    echo "<div class=\"critical\"><ul><li>"._INVALID_CRITERIA_VALUES.$cri['description']." (".$cri['operator'].$cri['value'].")</li></ul></div>";
                    exit();
                }else{
                    $sql_cust_target .= $function_result." AND ";
                }
            }
        }
     $statement = substr($sql_cust_target, 0, strrpos($sql_cust_target, "AND "));    
     $statement = $statement.' AND cust.is_active=1';
     }   
    echo "<div class=\"success\"><ul><li>".$statement."</li></ul></div>";

    $result_statement = mysqli_query($mysqli, $statement) or die("Query failed : " . mysqli_error($mysqli));
    $random_digit = generatePassword($length=3, $strength=2);
    $batch_id = date("dmyHis").'-'.$random_digit;;
    mysqli_query($mysqli, "DELETE FROM sms_campaign_details WHERE campaign_id ='$rid' AND batch_id<>'$batch_id'") or die(mysqli_error($mysqli));
        while ($cph = mysqli_fetch_array($result_statement, MYSQLI_ASSOC)) 
        {
            $c_id = $cph['id']; //echo $c_id; //debug
            $c_phone = $cph['phone']; // echo $c_phone;//debug
            mysqli_query ($mysqli, "INSERT INTO sms_campaign_details (id, phone, campaign_id, batch_id, customer_id,  created_on, created_by) 
            VALUES (NULL , '$c_phone', '$rid', '$batch_id', '$c_id', NOW(), '$user_id' )")or die(mysqli_error($mysqli));			
        }
        //update header with count_phones
		$count_sql = "SELECT id FROM sms_campaign_details WHERE campaign_id='$rid'";
		$result_count = mysqli_query($mysqli, $count_sql) or die(mysqli_error($mysqli));
		$numrows_count = mysqli_num_rows($result_count);
		echo "<div class=\"success\"><ul><li>"._RESULTED.$numrows_count."</li></ul></div>";
		$sql = "UPDATE sms_campaign_header SET count_phones ='$numrows_count', updated_on = NOW() WHERE id='$rid'";
	 	$res = mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli));                          
        // REFRESH PAGE
        echo "<meta http-equiv=\"refresh\" content=\"0;URL=".$_SERVER['PHP_SELF']."\">";  
    }
?>
			</div>
		</fieldset>
	</div>
</body>
</html>
<?php
} else {
    header('Location: login.php');
}
?>
