<?php include('../functions.php');?>
<?php include('../login/auth.php');?>
<?php include('../helpers/subscribe-form-fields.php');?>
<?php 
	$lid = is_numeric($_POST['lid']) ? mysqli_real_escape_string($mysqli, (int)$_POST['lid']) : exit;
	$fields = isset($_POST['fields']) ? $_POST['fields'] : '';
	
	sendy_ensure_subscribe_form_fields_column();
	
	$q = 'SELECT custom_fields FROM lists WHERE id = '.$lid;
	$r = mysqli_query($mysqli, $q);
	if(!$r || mysqli_num_rows($r)==0) exit;
	
	while($row = mysqli_fetch_array($r)) $custom_fields = $row['custom_fields'];
	
	$options = sendy_get_subscribe_form_field_options($custom_fields);
	$valid = array();
	for($i=0; $i<count($options); $i++) $valid[$options[$i]['key']] = true;
	
	$selected = array('email');
	if($fields!='')
	{
		$fields_array = explode(',', $fields);
		for($i=0; $i<count($fields_array); $i++)
		{
			$key = trim($fields_array[$i]);
			if($key!='email' && isset($valid[$key])) $selected[] = $key;
		}
	}
	
	$selected = array_values(array_unique($selected));
	$selected_fields = mysqli_real_escape_string($mysqli, implode(',', $selected));
	$q = 'UPDATE lists SET subscribe_form_fields = "'.$selected_fields.'" WHERE id = '.$lid;
	$r = mysqli_query($mysqli, $q);
	if($r) echo 'saved';
	else echo 'failed';
?>
