<?php
function sendy_ensure_subscribe_form_fields_column()
{
	global $mysqli;
	$q = "SHOW COLUMNS FROM lists WHERE Field = 'subscribe_form_fields'";
	$r = mysqli_query($mysqli, $q);
	if (!$r || mysqli_num_rows($r) == 0)
		mysqli_query($mysqli, 'ALTER TABLE lists ADD COLUMN subscribe_form_fields MEDIUMTEXT AFTER what_to_expect');
}

function sendy_get_subscribe_form_field_options($custom_fields)
{
	$options = array(
		array('key' => 'name', 'label' => 'Name', 'type' => 'default'),
		array('key' => 'email', 'label' => 'Email', 'type' => 'default')
	);
	
	if($custom_fields!='')
	{
		$custom_fields_array = explode('%s%', $custom_fields);
		for($i=0; $i<count($custom_fields_array); $i++)
		{
			$cf_array = explode(':', $custom_fields_array[$i]);
			$options[] = array(
				'key' => sendy_get_subscribe_form_custom_field_key($cf_array[0]),
				'label' => $cf_array[0],
				'type' => isset($cf_array[1]) ? $cf_array[1] : 'Text',
				'name' => str_replace(' ', '', $cf_array[0])
			);
		}
	}
	
	return $options;
}

function sendy_get_subscribe_form_custom_field_key($field_name)
{
	return 'cf_'.md5($field_name);
}

function sendy_get_selected_subscribe_form_fields($saved_fields, $options)
{
	$valid = array();
	$all = array();
	for($i=0; $i<count($options); $i++)
	{
		$valid[$options[$i]['key']] = true;
		$all[] = $options[$i]['key'];
	}
	
	if($saved_fields=='') return $all;
	
	$selected = array();
	$saved_fields_array = explode(',', $saved_fields);
	for($i=0; $i<count($saved_fields_array); $i++)
	{
		$key = trim($saved_fields_array[$i]);
		if(isset($valid[$key])) $selected[] = $key;
	}
	
	if(!in_array('email', $selected)) $selected[] = 'email';
	return array_values(array_unique($selected));
}

function sendy_subscribe_form_field_is_selected($selected_fields, $key)
{
	return in_array($key, $selected_fields);
}
?>
