<?php include('../functions.php');?>
<?php include('../login/auth.php');?>
<?php 
	//------------------------------------------------------//
	//                      	INIT                       //
	//------------------------------------------------------//
	
	$edit = isset($_GET['edit']) ? $_GET['edit'] : '';
	$ae = isset($_GET['ae']) ? mysqli_real_escape_string($mysqli, $_GET['ae']) : '';
	$ares_id = mysqli_real_escape_string($mysqli, $_GET['a']);
	$time_condition_number = mysqli_real_escape_string($mysqli, $_POST['time_condition_number']);
	$time_condition_intervals = mysqli_real_escape_string($mysqli, $_POST['time_condition_intervals']);
	$time_condition_beforeafter = mysqli_real_escape_string($mysqli, $_POST['time_condition_beforeafter']);
	$ares_type = $_POST['ares_type'];
	$subject = mysqli_real_escape_string($mysqli, $_POST['subject']);
	$from_name = mysqli_real_escape_string($mysqli, $_POST['from_name']);
	$from_email = mysqli_real_escape_string($mysqli, $_POST['from_email']);
	$reply_to = mysqli_real_escape_string($mysqli, $_POST['reply_to']);
	$plain = addslashes($_POST['plain']);
	$html = stripslashes($_POST['html']);
	$query_string = addslashes($_POST['query_string']);
	if(trim($html)=='<html><head></head><body></body></html>') $html = '';
	$filename = $_FILES['attachments']['name'];	
	$file = $_FILES['attachments']['tmp_name'];	
	$wysiwyg = isset($_POST['wysiwyg']) ? mysqli_real_escape_string($mysqli, $_POST['wysiwyg']) : 1;
	$editor_mode = isset($_POST['editor_mode']) ? sanitize_editor_mode($_POST['editor_mode'], '') : '';
	$editor_project_data_post = isset($_POST['editor_project_data']) ? trim($_POST['editor_project_data']) : '';
	$w_clicked = isset($_POST['w_clicked']) ? $_POST['w_clicked'] : null;
	$track_opens = isset($_POST['opens']) ? $_POST['opens'] : 1;
	$track_clicks = isset($_POST['clicks']) ? $_POST['clicks'] : 1;
	$wysiwyg = $wysiwyg=='1' ? 1 : 0;
	$time_condition_sign = $time_condition_beforeafter=='before' ? '-' : '+';
	$save_only = 0;
	if(isset($_POST['save-only'])) $save_only = is_numeric($_POST['save-only']) ? $_POST['save-only'] : 0;
	$save_as_template = isset($_POST['save_as_template']) && $_POST['save_as_template']=='on' ? true : false;
	$in_list_seg = isset($_POST['in_list_seg']) ? mysqli_real_escape_string($mysqli, $_POST['in_list_seg']) : '';
	$ex_list_seg = isset($_POST['ex_list_seg']) ? mysqli_real_escape_string($mysqli, $_POST['ex_list_seg']) : '';
	$current_html = '';
	$current_editor_mode = '';
	$current_editor_project_data = '';
	$current_wysiwyg = $wysiwyg;
	$editor_project_data = '';
	
	//get allowed attachments
	$q = 'SELECT allowed_attachments FROM apps WHERE id = '.get_app_info('app');
	$r = mysqli_query($mysqli, $q);
	if ($r) while($row = mysqli_fetch_array($r)) $allowed = array_map('trim', explode(',', $row['allowed_attachments']));
	$allow_attachments = $row['allowed_attachments']='' ? 0 : 1;
	
	if($ares_type==1)
	{
		//drip
		if($time_condition_intervals == 'immediately')
			$time_condition = $time_condition_intervals;
		else
			$time_condition = $time_condition_sign.$time_condition_number.' '.$time_condition_intervals;
	}
	else
	{
		//others
		if($time_condition_beforeafter == 'on')
			$time_condition = '';
		else
			$time_condition = $time_condition_sign.$time_condition_number.' '.$time_condition_intervals;
	}
	
	//------------------------------------------------------//
	//                      FUNCTIONS                       //
	//------------------------------------------------------//
	
	//make attachments directory if it don't exist
	$attachments_base_path = sendy_uploads_path(get_app_info('app'), 'attachments', '../../uploads', true);
	
	if($edit)
	{
		$q = 'SELECT html_text, editor_mode, editor_project_data, wysiwyg FROM ares_emails WHERE id='.$ae.' AND ares_id='.$ares_id;
		$r = mysqli_query($mysqli, $q);
		if ($r && mysqli_num_rows($r) > 0)
		{
			while($row = mysqli_fetch_array($r))
			{
				$current_html = $row['html_text']=='' ? '' : stripslashes($row['html_text']);
				$current_editor_mode = $row['editor_mode']=='' ? '' : stripslashes($row['editor_mode']);
				$current_editor_project_data = $row['editor_project_data']=='' ? '' : $row['editor_project_data'];
				$current_wysiwyg = $row['wysiwyg'];
			}
		}
	}
	
	if($editor_mode=='')
	{
		if($edit) $editor_mode = resolve_editor_mode($current_editor_mode, $current_wysiwyg, 'html');
		else $editor_mode = $wysiwyg ? 'wysiwyg' : 'html';
	}
	$wysiwyg = editor_mode_to_wysiwyg($editor_mode);
	
	if($editor_project_data_post!='')
		$editor_project_data = mysqli_real_escape_string($mysqli, $editor_project_data_post);
	else if($edit)
	{
		if($editor_mode=='dragdrop')
			$editor_project_data = '';
		else if($current_html === $html && $current_editor_project_data!='')
			$editor_project_data = mysqli_real_escape_string($mysqli, $current_editor_project_data);
	}
	
	if($edit)
	{
		$q = 'UPDATE ares_emails SET from_name="'.$from_name.'", from_email="'.$from_email.'", reply_to="'.$reply_to.'", title="'.$subject.'", plain_text="'.$plain.'", html_text="'.addslashes($html).'", query_string="'.$query_string.'", time_condition="'.$time_condition.'", wysiwyg='.$wysiwyg.', editor_mode="'.$editor_mode.'", editor_project_data="'.$editor_project_data.'", opens_tracking = '.$track_opens.', links_tracking = '.$track_clicks.', segs = "'.$in_list_seg.'", segs_excl = "'.$ex_list_seg.'" WHERE id='.$ae.' AND ares_id='.$ares_id;
		$r = mysqli_query($mysqli, $q);
		if ($r)
		{
			//Upload attachment(s)
			if($allow_attachments && $file[0]!='') //check if user uploaded any attachments
			{
				$attachments_path = sendy_uploads_path(get_app_info('app'), 'attachments/a'.$ae, '../../uploads', true);
				for($i=0;$i<count($file);$i++)
				{
					$extension_explode = explode('.', $filename[$i]);
					$extension = $extension_explode[count($extension_explode)-1];
					if(in_array(strtolower($extension), $allowed))
					{
						if(!move_uploaded_file($file[$i], $attachments_path.'/'.$filename[$i]))
						{
							show_error(_('Unable to upload attachment'), '<p>'._('Please ensure the /uploads/ folder permission is set to 777.').'</p>');
							exit;
						}
					}
				}
			}
		}
		else
		{
			show_error(_('Unable to save autoresponder email'), '<p>'.mysqli_error($mysqli).'</p><p>Or check <a href="https://sendy.co/troubleshooting#403-forbidden-error-when-clicking-save-and-next">https://sendy.co/troubleshooting#403-forbidden-error-when-clicking-save-and-next</a> as you may have "mod_security" enabled on your server.</p>');
			exit;
		}
	}
	else
	{
		//Insert into campaigns
		$q = 'INSERT INTO ares_emails (ares_id, from_name, from_email, reply_to, title, plain_text, html_text, query_string, time_condition, created, wysiwyg, editor_mode, editor_project_data, opens_tracking, links_tracking, segs, segs_excl) VALUES ('.$ares_id.', "'.$from_name.'", "'.$from_email.'", "'.$reply_to.'", "'.$subject.'", "'.$plain.'", "'.addslashes($html).'", "'.$query_string.'", "'.$time_condition.'", "'.time().'", '.$wysiwyg.', "'.$editor_mode.'", "'.$editor_project_data.'", '.$track_opens.', '.$track_clicks.', "'.$in_list_seg.'", "'.$ex_list_seg.'")';
		$r = mysqli_query($mysqli, $q);
		if ($r)
		{
			//get the ares id from the new insert
		    $ae = mysqli_insert_id($mysqli);
		    
			//Upload attachment(s)
			if($allow_attachments && $file[0]!='') //check if user uploaded any attachments
			{
				$attachments_path = sendy_uploads_path(get_app_info('app'), 'attachments/a'.$ae, '../../uploads', true);
				for($i=0;$i<count($file);$i++)
				{
					$extension_explode = explode('.', $filename[$i]);
					$extension = $extension_explode[count($extension_explode)-1];
					if(in_array(strtolower($extension), $allowed))
					{
						if(!move_uploaded_file($file[$i], $attachments_path.'/'.$filename[$i]))
						{
							show_error(_('Unable to upload attachment'), '<p>'._('Please ensure the /uploads/ folder permission is set to 777.').'</p>');
							exit;
						}
					}
				}
			}
		}
		else
		{
			show_error(_('Unable to create autoresponder email'), '<p>'.mysqli_error($mysqli).'</p><p>Or check <a href="https://sendy.co/troubleshooting#403-forbidden-error-when-clicking-save-and-next">https://sendy.co/troubleshooting#403-forbidden-error-when-clicking-save-and-next</a> as you may have "mod_security" enabled on your server.</p>');
			exit;
		}
	}
	
	//Check if user wants to save email campaign as a template too
	if($save_as_template)
	{
		$q = 'INSERT INTO template (userID, app, template_name, html_text, plain_text, editor_mode, editor_project_data) VALUES ('.get_app_info('main_userID').', '.get_app_info('app').', "'.$subject.'", "'.addslashes($html).'", "'.$plain.'", "'.$editor_mode.'", "'.$editor_project_data.'")';
		$r = mysqli_query($mysqli, $q);
		if (!$r)
		{
		    show_error(_('Unable to create template'), '<p>'.mysqli_error($mysqli).'</p>', true);
			exit;
		}
	}
	
	//After saving, redirect to appropriate page
	if($w_clicked || $save_only)
		header('Location: '.get_app_info('path').'/autoresponders-edit?i='.get_app_info('app').'&a='.$ares_id.'&ae='.$ae);
	else
		header('Location: '.get_app_info('path').'/autoresponders-emails?i='.get_app_info('app').'&a='.$ares_id);
?>
