<?php
// $Id: sms_list.module,v 1.6 2010/08/30 05:15:15 abhisheknagar Exp $

/**
 * Implementation of hook_perm().
 */
function sms_list_perm() {
  return array('administer sms_list', 'send sms to sms_list');
} // function sms_list_perm()


/**
 * Implementation of hook_menu().
 */
function sms_list_menu() {
  $items = array();

  $items['admin/smsframework/sms_list'] = array(
    'title' => 'SMS List Configuration',
    'description' => 'Manage SMS List',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('sms_list_admin_form'),
    'access arguments' => array('administer sms_list'),
  );
  
   $items['sms_list/send'] = array(
    'title'            => 'Send SMS to SMS List',
    'page callback'    => 'drupal_get_form',
    'page arguments'   => array('sms_list_send'),
    'access arguments' => array('send sms to sms_list'),
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}
function sms_list_admin_form() {  

	$form['sms_list_info'] = array(
    '#type' => 'item',
    '#title' => t('SMS List Status'),
    '#value' => sms_list_status(),
	);

	$form['sms_list_subs'] = array(
    '#type' => 'textarea',
    '#title' => t('SMS List Subscription Message'),
    '#description' => t('Message Sent when user subscribes'),
    '#default_value' => variable_get('sms_list_subs_message', $default=NULL),
    );
    
    	$form['submit'] = array(
    '#type' => 'submit', 
    '#value' => t('Save Configuration'),
	);    
    return $form;
}

function sms_list_admin_form_submit($form, &$form_state) {
  // Process form submission to set the default gateway
  if ($form_state['values']['sms_list_subs']) {
    drupal_set_message(t('Subscription Message Updated'));
    variable_set('sms_list_subs_message', $form_state['values']['sms_list_subs']);
    }
}


function sms_list_status() {
	  $result = db_query("SELECT count(number) as count FROM {sms_list} WHERE subscribe = 1");
	while ($row = db_fetch_array($result)) {
    $status_counts[] = $row;
	}
	
	if ($status_counts) {
		  foreach ($status_counts as $status_count) {

			$status_subs = 'Total Subscribers: '. $status_count['count'];
		}
	}
	else 
	$status_subs = 'Total Subscribers: 0';
	
	$result = db_query("SELECT count(number) as count1 FROM {sms_list} WHERE subscribe = 0");
	while ($row = db_fetch_array($result)) {
    $status_countus[] = $row;
	}
	
	if ($status_countus) {
		  foreach ($status_countus as $status_countu) {

			$status_unsubs = 'Total UnSubscribed: '. $status_countu['count1'];
		}
	}
	else 
	$status_unsubs = 'Total UnSubscribed: 0';
	
	
	$result = db_query("SELECT count(message) as count2 FROM {sms_list_send}");
	while ($row = db_fetch_array($result)) {
    $status_send[] = $row;
	}
	
	if ($status_send) {
		  foreach ($status_send as $status_sent) {

			$status_sent_sms = 'Total SMS Sent to List: '. $status_sent['count2'];
		}
	}
	else 
	$status_unsubs = 'Total SMS Sent: 0';
	
	$status = $status_subs.'<br/>'.$status_unsubs.'<br/>'.$status_sent_sms;
  return $status;
}

function sms_list_send() {
	$form['sms_list_info'] = array(
    '#type' => 'item',
    '#title' => t('SMS List Status'),
    '#value' => sms_list_status(),
	);
	
	$form['message'] = array(
    '#type' => 'textarea',
    '#title' => t('Message'),
    '#cols' => 60,
    '#rows' => 5,
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Send'),
  );

  return $form;
}

function sms_list_send_submit(&$form, $form_state) {
  $result = db_query("SELECT distinct(number), gateway FROM {sms_list} WHERE subscribe = 1");

  while ($row = db_fetch_array($result)) {
    $numbers[] = $row;
  }
if($numbers){
	
  foreach ($numbers as $monumber) {
    sms_list_send_message($monumber['number'], $monumber['gateway'],$form_state['values']['message']);
  }
  drupal_set_message(t('The message was sent to %count Subscribers.', array('%count' => count($numbers))));
 
 $message = $form_state['values']['message'];
 $total_sent = count($numbers);
 
 db_query("INSERT INTO {sms_list_send} (message, count) VALUES ('$message',$total_sent)");
 
 watchdog('sms','SMS List sent Messages to  %count Subscribers', array('%count' => count($numbers)));

}
}

/**
* Send SMS to List
*/

function sms_list_send_message ($number, $option, $message) {
	
    return sms_send($number, $message, $options);
  
}



/**
 * Subscription Form
 */

function sms_list_form(&$form_state){
  $gateway = sms_default_gateway();
	
	$form['name'] = array(
      '#type' => 'textfield',
      '#title' => t('Full Name'),
      '#size' => 20,
      '#maxlength' => 100,
      '#required' => TRUE,
    );
	
	$form['number'] = array(
      '#type' => 'textfield',
      '#title' => t('Mobile No'),
      '#size' => 20,
      '#maxlength' => 12,
      '#required' => TRUE,
    );


if (function_exists($gateway['send form'])) {
    $form['gateway']['#tree'] = TRUE;
    $form['gateway'] = array_merge($gateway['send form']($required), $form['gateway']);
    $form['gateway'] = array_merge($gateway['send form']($required), $form['gateway']);
  }

  
    $form['action'] = array(
      '#type' => 'radios',
      '#default_value' => 'subscribe',
      '#options' => array('1' => t('Subscribe'), '0' => t('Unsubscribe')),
    );
	$form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Submit'),
    );


  return $form;

}
/**
 * Mobile Number Validation
 */
function sms_list_form_validate($form, &$form_state) {
  if (!sms_formatter($form_state['values']['number'])) {
    form_set_error('number', t('You must enter a valid phone number.'));
  }
}

/**
 * Subscription Submission
 */

function sms_list_form_submit($form, &$form_state){
	  sms_list_send_confirmation($form_state['values']['number'], $form_state['values']['gateway'], $form_state['values']['name'],$form_state['values']['action']);

}


/**
 * Implementation of hook_block().
 */
function sms_list_block($op = 'list', $delta = 0, $edit = array()) {
switch($op){

	case 'list':
		    // Generate listing of blocks from this module, for the admin/block page
		    $block = array();
		    $block[0]["info"] = t('SMS List Subscribe Block');
		    return $block;
	case 'view':
	    $block = array(
		'subject' => 'Subscribe via SMS',
		'content' => drupal_get_form('sms_list_form', $account),
		 
		
);
	return $block;
  } 
}
/**
 * this function is to be used for sending code for confirmation but currently is not being used
 **/


function sms_list_send_confirmation($number, $options, $name, $action) {
  $code = rand(1000, 9999);
  $data[0] = array(
    'number'  => $number,
    'status'  => 1,
    'code'    => $code,
    'gateway' => $options,
    'name' => $name,
    'action' => $action,
  );
  sms_list_save(array('sms_list' => $data), 'mobile');  
  //sms_send($number, _sms_user_confirm_message($code), $options);
  

}

function sms_list_save($edit, $category) {
  if (($category == 'mobile' ) && $edit['sms_list']) {
    foreach ($edit['sms_list'] as $delta => $number) {
      if (is_numeric($delta)) {
        $db_values = array($number['number'], isset($number['code']) ? $number['code'] : NULL,$number['name'], $number[action], $number[status], serialize($number['gateway']));

			$check = $db_values[0];

			$number_exist=db_query("SELECT count(subscribe) as count from {sms_list} where number = $check");
			
			while ($row = db_fetch_array($number_exist)) {
			$numbers[] = $row;
			}

			foreach ($numbers as $monumber) {
			 $count_subscribe=$monumber['count'];
			}
  
  			if ($count_subscribe != 1) {
				db_query("INSERT INTO {sms_list} (number, code, name, subscribe, status, gateway)
				VALUES ('%d', '%d', '%s','%s','%d', '%s')", array_merge($db_values, array($delta)));
				drupal_set_message ("SMS Service Subscribed");
				$number=$db_values[0];
				sms_send($number, _sms_list_subs_message($message), $options);

				}
			
			else {
				
				db_query("UPDATE {sms_list} set subscribe =$db_values[3] where number = $db_values[0]");
				drupal_set_message ("SMS Service Updated");
			}
      }
    }
    $edit['sms_list'] = NULL;
  }
}

function _sms_list_subs_message($message) {
	$text_format = variable_get('sms_list_subs_message', $default=NULL);
	$text = token_replace_multiple($text_format);
  return $text;
}
