<?php include('../functions.php');?>
<?php include('../login/auth.php');?>
<?php 
	//------------------------------------------------------//
	//                      VARIABLES                       //
	//------------------------------------------------------//
	
	$template_id = isset($_POST['template_id']) && is_numeric($_POST['template_id']) ? mysqli_real_escape_string($mysqli, (int)$_POST['template_id']) : exit;
	$app_id = isset($_POST['on-brand']) && is_numeric($_POST['on-brand']) ? mysqli_real_escape_string($mysqli, (int)$_POST['on-brand']) : exit;
	
	if(get_app_info('is_sub_user'))
	{
		if(get_app_info('app')!=get_app_info('restricted_to_app') || $app_id!=get_app_info('restricted_to_app'))
		{
			header("Location: ".get_app_info('path')."/templates?i=".get_app_info('restricted_to_app'));
			exit;
		}
	}
	
	$q = 'SELECT id FROM apps WHERE id = '.$app_id.' AND userID = '.get_app_info('main_userID').' LIMIT 1';
	$r = mysqli_query($mysqli, $q);
	if (!$r || mysqli_num_rows($r) == 0) exit;
	
	//------------------------------------------------------//
	//                      FUNCTIONS                       //
	//------------------------------------------------------//
	
	//get template's data
	$q = 'SELECT app, template_name, html_text, plain_text, from_name, from_email, reply_to, editor_mode, editor_project_data FROM template WHERE id = '.$template_id.' AND userID = '.get_app_info('main_userID').' LIMIT 1';
	$r = mysqli_query($mysqli, $q);
	if ($r && mysqli_num_rows($r) > 0)
	{
	    while($row = mysqli_fetch_array($r))
	    {
			if(get_app_info('is_sub_user') && $row['app']!=get_app_info('restricted_to_app'))
			{
				header("Location: ".get_app_info('path')."/templates?i=".get_app_info('restricted_to_app'));
				exit;
			}
			
			$template_name = $row['template_name'];
			$html_text = $row['html_text'];
			$plain_text = $row['plain_text'];
			$from_name = $row['from_name'];
			$from_email = $row['from_email'];
			$reply_to = $row['reply_to'];
			$editor_mode = resolve_editor_mode($row['editor_mode'], null, 'dragdrop');
			$editor_project_data = $row['editor_project_data']=='' ? '' : $row['editor_project_data'];
	    }  
	}
	else exit;
	
	//Insert into database
	$q3 = 'INSERT INTO template (userID, app, template_name, html_text, plain_text, from_name, from_email, reply_to, editor_mode, editor_project_data) VALUES ('.get_app_info('main_userID').', '.$app_id.', "'.mysqli_real_escape_string($mysqli, $template_name).'", "'.mysqli_real_escape_string($mysqli, $html_text).'", "'.mysqli_real_escape_string($mysqli, $plain_text).'", "'.mysqli_real_escape_string($mysqli, $from_name).'", "'.mysqli_real_escape_string($mysqli, $from_email).'", "'.mysqli_real_escape_string($mysqli, $reply_to).'", "'.$editor_mode.'", "'.mysqli_real_escape_string($mysqli, $editor_project_data).'")';
	$r3 = mysqli_query($mysqli, $q3);
	if ($r3)
	     header("Location: ".get_app_info('path')."/templates?i=".$app_id);
	else
		echo 'Error duplicating.';
?>
