<?php include('../functions.php');?>
<?php include('../login/auth.php');?>
<?php include('../helpers/openai.php');?>
<?php
	$aid = isset($_POST['aid']) && is_numeric($_POST['aid']) ? (int)$_POST['aid'] : exit;
	$ares_id = isset($_POST['ares_id']) && is_numeric($_POST['ares_id']) ? (int)$_POST['ares_id'] : 0;
	$ares_type = isset($_POST['ares_type']) && is_numeric($_POST['ares_type']) ? (int)$_POST['ares_type'] : 0;
	$is_template = isset($_POST['is_template']) && $_POST['is_template']==1;
	$task = isset($_POST['ai-task']) ? trim($_POST['ai-task']) : '';
	$look_feel = isset($_POST['ai-look-feel']) ? trim($_POST['ai-look-feel']) : '';
	$requirements = isset($_POST['ai-requirements']) ? trim($_POST['ai-requirements']) : '';
	$prompt = trim("Task:\n".$task."\n\nLook and feel:\n".$look_feel."\n\nRequirements:\n".$requirements);

	if($task=='' && $look_feel=='' && $requirements=='')
		$prompt = isset($_POST['ai-prompt']) ? trim($_POST['ai-prompt']) : '';

	if($prompt=='')
		show_error(_('Unable to create with AI'), '<p>'._('A prompt is required to generate an email.').'</p>', true);

	$user_prompt = $prompt;

	if(get_app_info('is_sub_user') && (int)get_app_info('restricted_to_app') !== $aid)
	{
		$redirect_page = $is_template ? '/create-template?i=' : '/create?i=';
		echo '<script type="text/javascript">window.location="'.addslashes(get_app_info('path')).$redirect_page.get_app_info('restricted_to_app').'"</script>';
		exit;
	}

	if(sendy_brand_ai_disabled($aid))
		show_error(_('Unable to create with AI'), '<p>'._('AI features are disabled for this brand.').'</p>', true);

	if(!sendy_ai_addon_enabled())
		show_error(_('✨ Add-on AI features to your Sendy'), sendy_ai_paywall_body_html().'<p><a href="'.htmlspecialchars(sendy_ai_addon_url(), ENT_QUOTES, 'UTF-8').'" target="_blank">'._('Get the AI add-on').'</a></p>', true);

	$q = 'SELECT from_name, from_email, reply_to, query_string, opens_tracking, links_tracking, openai_api_key FROM apps WHERE id = '.$aid.' AND userID = '.get_app_info('main_userID').' LIMIT 1';
	$r = mysqli_query($mysqli, $q);
	if(!$r || mysqli_num_rows($r)==0)
		show_error(_('Unable to create with AI'), '<p>'._('Brand not found.').'</p>', true);

	$row = mysqli_fetch_array($r);
	$from_name = mysqli_real_escape_string($mysqli, $row['from_name']);
	$from_email = mysqli_real_escape_string($mysqli, $row['from_email']);
	$reply_to = mysqli_real_escape_string($mysqli, $row['reply_to']);
	$query_string = mysqli_real_escape_string($mysqli, $row['query_string']);
	$opens_tracking = (int)$row['opens_tracking'];
	$links_tracking = (int)$row['links_tracking'];
	$openai_api_key = isset($row['openai_api_key']) ? trim($row['openai_api_key']) : '';

	if($openai_api_key=='')
		show_error(_('Unable to create with AI'), '<p>'._('Save an OpenAI API key in Brand settings > AI settings first.').'</p>', true);

	$reference_context = sendy_get_ai_reference_email_context($prompt);
	if($reference_context!='')
	{
		$prompt .= "\n\nReference email context from the URL in the prompt:\n".$reference_context;
		$prompt .= "\n\nUse the reference context only for requested visual direction, color scheme, spacing, and layout inspiration. If the user asks to follow the reference color scheme, palette, colors, background, or dark/light theme, prioritize the extracted reference palette over any generic default such as a clean white background. Do not copy tracking links, unsubscribe links, subscriber data, or private identifiers from the reference email.";
	}

	$prompt .= "\n\nRequired Sendy system links: any \"View in browser\", \"View web version\", or web version link must use href=\"[webversion]\" exactly. Any \"Unsubscribe\" link must use href=\"[unsubscribe]\" exactly. Do not use full URLs, #, or placeholder URLs for these two system links.";

	$logo_placeholder_url = get_app_info('path').'/img/ai-placeholder-logo.svg';
	$hero_placeholder_url = get_app_info('path').'/img/ai-placeholder-hero.svg';
	$uses_images = preg_match('/\b(html|image|images|logo|hero|banner|newsletter|template)\b/i', $user_prompt);
	if($uses_images)
		$prompt .= "\n\nPlaceholder image URLs to use exactly:\n- Logo image: ".$logo_placeholder_url."\n- Hero image: ".$hero_placeholder_url."\nDo not use via.placeholder.com, placeholder.com, placehold.co, dummyimage.com, or any other remote placeholder image service.";

	try
	{
		$client = new SendyOpenAiClient($openai_api_key, array('timeout' => 90));
		$html = $client->generate_email_newsletter_html($prompt);
		if($uses_images)
			$html = sendy_replace_ai_placeholder_images($html, $logo_placeholder_url, $hero_placeholder_url);
		$html = sendy_normalize_ai_system_links($html);
	}
	catch(Exception $e)
	{
		error_log('[Sendy AI email generator] '.$e->getMessage().': in '.__FILE__.' on line '.__LINE__);
		show_error(_('Unable to create with AI'), '<p>'.htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8').'</p>', true);
	}

	$title = mysqli_real_escape_string($mysqli, _('AI generated newsletter'));
	$html_text = mysqli_real_escape_string($mysqli, $html);

	if($is_template)
	{
		$q = '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').', '.$aid.', "'.$title.'", "'.$html_text.'", "", "'.$from_name.'", "'.$from_email.'", "'.$reply_to.'", "dragdrop", "")';
	}
	else if($ares_id)
	{
		$time_condition = $ares_type==1 ? 'immediately' : '';
		$q = 'INSERT INTO ares_emails (ares_id, from_name, from_email, reply_to, query_string, title, html_text, plain_text, wysiwyg, editor_mode, editor_project_data, created, time_condition, opens_tracking, links_tracking) VALUES ('.$ares_id.', "'.$from_name.'", "'.$from_email.'", "'.$reply_to.'", "'.$query_string.'", "'.$title.'", "'.$html_text.'", "", 0, "dragdrop", "", '.time().', "'.$time_condition.'", '.$opens_tracking.', '.$links_tracking.')';
	}
	else
	{
		$q = 'INSERT INTO campaigns (userID, app, from_name, from_email, reply_to, query_string, title, label, html_text, plain_text, wysiwyg, editor_mode, editor_project_data, opens_tracking, links_tracking) VALUES ('.get_app_info('main_userID').', '.$aid.', "'.$from_name.'", "'.$from_email.'", "'.$reply_to.'", "'.$query_string.'", "'.$title.'", "", "'.$html_text.'", "", 0, "dragdrop", "", '.$opens_tracking.', '.$links_tracking.')';
	}

	$r = mysqli_query($mysqli, $q);
	if(!$r)
	{
		$error_message = $is_template ? _('Failed to create template with AI') : ($ares_id ? _('Failed to create autoresponder email with AI') : _('Failed to create campaign with AI'));
		show_error($error_message, '<p>'.mysqli_error($mysqli).'</p>', true);
	}

	$inserted_id = mysqli_insert_id($mysqli);

	if($is_template)
		header("Location: ".get_app_info('path')."/edit-template?i=".$aid."&t=$inserted_id");
	else if($ares_id)
		header("Location: ".get_app_info('path')."/autoresponders-edit?i=".$aid."&a=$ares_id&ae=$inserted_id");
	else
		header("Location: ".get_app_info('path')."/edit?i=".$aid."&c=$inserted_id");

	function sendy_replace_ai_placeholder_images($html, $logo_placeholder_url, $hero_placeholder_url)
	{
		return preg_replace_callback('/(<img\b[^>]*\bsrc=["\'])([^"\']+)(["\'][^>]*>)/i', function($matches) use ($logo_placeholder_url, $hero_placeholder_url) {
			$src = html_entity_decode($matches[2], ENT_QUOTES, 'UTF-8');

			if(preg_match('/(?:via\.placeholder\.com|placeholder\.com|placehold\.co|dummyimage\.com)\/(?:[^"\']*)?(?:logo|180x50|200x60|150x50)/i', $src))
				return $matches[1].$logo_placeholder_url.$matches[3];

			if(preg_match('/(?:via\.placeholder\.com|placeholder\.com|placehold\.co|dummyimage\.com)\/(?:[^"\']*)?(?:hero|600x320|600x300|640x320)/i', $src))
				return $matches[1].$hero_placeholder_url.$matches[3];

			return $matches[0];
		}, $html);
	}

	function sendy_normalize_ai_system_links($html)
	{
		return preg_replace_callback('/<a\b([^>]*)>(.*?)<\/a>/is', function($matches) {
			$attrs = $matches[1];
			$content = $matches[2];
			$text = strtolower(trim(html_entity_decode(strip_tags($content), ENT_QUOTES, 'UTF-8')));

			$href = '';
			if(preg_match('/\bhref\s*=\s*(["\'])(.*?)\1/i', $attrs, $href_match))
				$href = strtolower(trim(html_entity_decode($href_match[2], ENT_QUOTES, 'UTF-8')));

			$replacement_href = '';
			if(strpos($text, 'unsubscribe')!==false || strpos($href, 'unsubscribe')!==false)
				$replacement_href = '[unsubscribe]';
			else if(strpos($text, 'view in browser')!==false || strpos($text, 'view web version')!==false || strpos($text, 'web version')!==false || strpos($href, 'webversion')!==false || strpos($href, 'web-version')!==false || strpos($href, '/w/')!==false)
				$replacement_href = '[webversion]';

			if($replacement_href=='')
				return $matches[0];

			if(preg_match('/\bhref\s*=\s*(["\'])(.*?)\1/i', $attrs))
				$attrs = preg_replace('/\bhref\s*=\s*(["\'])(.*?)\1/i', 'href="'.$replacement_href.'"', $attrs, 1);
			else
				$attrs .= ' href="'.$replacement_href.'"';

			return '<a'.$attrs.'>'.$content.'</a>';
		}, $html);
	}

	function sendy_get_ai_reference_email_context($prompt)
	{
		$urls = sendy_extract_ai_prompt_urls($prompt);

		foreach($urls as $url)
		{
			if(!sendy_should_fetch_ai_reference_url($url))
				continue;

			$html = file_get_contents_curl($url);
			if($html=='' || $html=='blocked')
				continue;

			$context = sendy_summarize_ai_reference_email($html, $url);
			if($context!='')
				return $context;
		}

		return '';
	}

	function sendy_extract_ai_prompt_urls($text)
	{
		$urls = array();
		if(!preg_match_all('/https?:\/\/[^\s<>"\']+/i', $text, $matches))
			return $urls;

		foreach($matches[0] as $url)
		{
			$url = rtrim($url, ".,;:)]}'\"");
			if($url!='' && !in_array($url, $urls))
				$urls[] = $url;
		}

		return $urls;
	}

	function sendy_should_fetch_ai_reference_url($url)
	{
		$parts = parse_url($url);
		if(!$parts || !isset($parts['scheme']) || !isset($parts['host']))
			return false;

		$scheme = strtolower($parts['scheme']);
		if($scheme!='http' && $scheme!='https')
			return false;

		$path = isset($parts['path']) ? strtolower($parts['path']) : '';
		if(preg_match('/\.(jpg|jpeg|png|gif|svg|webp|pdf|zip|mp4|mov|avi|css|js)(?:$|\?)/i', $path))
			return false;

		return true;
	}

	function sendy_summarize_ai_reference_email($html, $url)
	{
		$html = substr($html, 0, 300000);
		$parts = array();
		$parts[] = 'Reference URL: '.$url;

		$palette = sendy_extract_ai_reference_palette_guidance($html);
		if($palette!='')
			$parts[] = $palette;

		$colors = sendy_extract_ai_reference_colors($html);
		if(count($colors))
			$parts[] = 'Additional color values found in the reference: '.implode(', ', $colors);

		$layout = sendy_extract_ai_reference_layout($html);
		if($layout!='')
			$parts[] = $layout;

		$text = sendy_extract_ai_reference_visible_text($html);
		if($text!='')
			$parts[] = 'Visible copy and section clues: '.$text;

		return implode("\n", $parts);
	}

	function sendy_extract_ai_reference_palette_guidance($html)
	{
		$backgrounds = array();
		$text_colors = array();
		$accent_colors = array();

		if(preg_match_all('/\b(bgcolor)\s*=\s*["\']?([^"\'\s>]+)/i', $html, $matches, PREG_SET_ORDER))
		{
			foreach($matches as $match)
				$backgrounds[] = $match[2];
		}

		if(preg_match_all('/\b(background(?:-color)?|color|border(?:-[a-z]+)?-color|border-color)\s*:\s*([^;"\']+)/i', $html, $matches, PREG_SET_ORDER))
		{
			foreach($matches as $match)
			{
				$property = strtolower($match[1]);
				$value = sendy_ai_extract_css_color_value($match[2]);
				if($value=='')
					continue;

				if(strpos($property, 'background')===0)
					$backgrounds[] = $value;
				else if(strpos($property, 'border')===0)
					$accent_colors[] = $value;
				else
					$text_colors[] = $value;
			}
		}

		if(preg_match_all('/<a\b[^>]*style\s*=\s*(["\'])(.*?)\1/i', $html, $matches, PREG_SET_ORDER))
		{
			foreach($matches as $match)
			{
				if(preg_match('/\bcolor\s*:\s*([^;]+)/i', $match[2], $color_match))
				{
					$value = sendy_ai_extract_css_color_value($color_match[1]);
					if($value!='')
						$accent_colors[] = $value;
				}

				if(preg_match('/\bbackground(?:-color)?\s*:\s*([^;]+)/i', $match[2], $color_match))
				{
					$value = sendy_ai_extract_css_color_value($color_match[1]);
					if($value!='')
						$accent_colors[] = $value;
				}
			}
		}

		$backgrounds = sendy_rank_ai_reference_colors($backgrounds, 6);
		$text_colors = sendy_rank_ai_reference_colors($text_colors, 6);
		$accent_colors = sendy_rank_ai_reference_colors($accent_colors, 6);

		$theme = sendy_detect_ai_reference_theme($backgrounds);
		$parts = array();
		if($theme!='')
			$parts[] = 'Detected theme: '.$theme;
		if(count($backgrounds))
			$parts[] = 'Background/container colors to prioritize: '.implode(', ', $backgrounds);
		if(count($text_colors))
			$parts[] = 'Text colors to prioritize: '.implode(', ', $text_colors);
		if(count($accent_colors))
			$parts[] = 'Accent/button/link colors to prioritize: '.implode(', ', $accent_colors);

		if(!count($parts))
			return '';

		return 'Reference palette guidance: '.implode('. ', $parts).'.';
	}

	function sendy_extract_ai_reference_colors($html)
	{
		$colors = array();

		if(preg_match_all('/#[0-9a-f]{3}(?:[0-9a-f]{3})?\b/i', $html, $matches))
			$colors = array_merge($colors, $matches[0]);

		if(preg_match_all('/\b(?:rgb|rgba)\([^)]+\)/i', $html, $matches))
			$colors = array_merge($colors, $matches[0]);

		if(preg_match_all('/\b(?:bgcolor|color)=["\']?([^"\'\s>]+)/i', $html, $matches))
			$colors = array_merge($colors, $matches[1]);

		$counts = array();
		foreach($colors as $color)
		{
			$color = strtolower(trim($color));
			if($color=='' || in_array($color, array('inherit', 'transparent', 'none', 'auto')))
				continue;

			if(!isset($counts[$color]))
				$counts[$color] = 0;
			$counts[$color]++;
		}

		arsort($counts);
		return array_slice(array_keys($counts), 0, 12);
	}

	function sendy_ai_extract_css_color_value($value)
	{
		$value = strtolower(trim($value));
		$value = preg_replace('/\s*!important\b/i', '', $value);

		if(preg_match('/#[0-9a-f]{3}(?:[0-9a-f]{3})?\b/i', $value, $match))
			return strtolower($match[0]);

		if(preg_match('/\b(?:rgb|rgba)\([^)]+\)/i', $value, $match))
			return strtolower($match[0]);

		if(preg_match('/\b(black|white|red|green|blue|yellow|orange|purple|pink|gray|grey|silver|maroon|navy|teal|aqua|lime|olive|fuchsia)\b/i', $value, $match))
			return strtolower($match[1]);

		return '';
	}

	function sendy_rank_ai_reference_colors($colors, $limit)
	{
		$counts = array();
		foreach($colors as $color)
		{
			$color = sendy_ai_extract_css_color_value($color);
			if($color=='' || in_array($color, array('inherit', 'transparent', 'none', 'auto')))
				continue;

			if(!isset($counts[$color]))
				$counts[$color] = 0;
			$counts[$color]++;
		}

		arsort($counts);
		return array_slice(array_keys($counts), 0, $limit);
	}

	function sendy_detect_ai_reference_theme($backgrounds)
	{
		foreach($backgrounds as $color)
		{
			if(sendy_ai_color_is_dark($color))
				return 'dark background';
		}

		foreach($backgrounds as $color)
		{
			if(sendy_ai_color_is_light($color))
				return 'light background';
		}

		return '';
	}

	function sendy_ai_color_is_dark($color)
	{
		$luma = sendy_ai_color_luma($color);
		return $luma!==null && $luma<80;
	}

	function sendy_ai_color_is_light($color)
	{
		$luma = sendy_ai_color_luma($color);
		return $luma!==null && $luma>200;
	}

	function sendy_ai_color_luma($color)
	{
		$color = strtolower(trim($color));
		$named = array(
			'black' => array(0, 0, 0),
			'white' => array(255, 255, 255),
			'gray' => array(128, 128, 128),
			'grey' => array(128, 128, 128),
			'navy' => array(0, 0, 128),
			'maroon' => array(128, 0, 0)
		);

		if(isset($named[$color]))
		{
			$rgb = $named[$color];
			return (0.2126 * $rgb[0]) + (0.7152 * $rgb[1]) + (0.0722 * $rgb[2]);
		}

		if(preg_match('/^#([0-9a-f]{3})$/i', $color, $matches))
		{
			$r = hexdec(str_repeat(substr($matches[1], 0, 1), 2));
			$g = hexdec(str_repeat(substr($matches[1], 1, 1), 2));
			$b = hexdec(str_repeat(substr($matches[1], 2, 1), 2));
			return (0.2126 * $r) + (0.7152 * $g) + (0.0722 * $b);
		}

		if(preg_match('/^#([0-9a-f]{6})$/i', $color, $matches))
		{
			$r = hexdec(substr($matches[1], 0, 2));
			$g = hexdec(substr($matches[1], 2, 2));
			$b = hexdec(substr($matches[1], 4, 2));
			return (0.2126 * $r) + (0.7152 * $g) + (0.0722 * $b);
		}

		if(preg_match('/rgba?\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)/i', $color, $matches))
			return (0.2126 * (int)$matches[1]) + (0.7152 * (int)$matches[2]) + (0.0722 * (int)$matches[3]);

		return null;
	}

	function sendy_extract_ai_reference_layout($html)
	{
		$items = array();
		$table_count = preg_match_all('/<table\b/i', $html, $unused);
		$row_count = preg_match_all('/<tr\b/i', $html, $unused);
		$image_count = preg_match_all('/<img\b/i', $html, $unused);
		$link_count = preg_match_all('/<a\b/i', $html, $unused);

		$items[] = 'Structure counts: '.$table_count.' tables, '.$row_count.' rows, '.$image_count.' images, '.$link_count.' links.';

		if(preg_match('/<body\b([^>]*)>/i', $html, $matches))
			$items[] = 'Body attributes/styles: '.sendy_ai_clean_summary_text($matches[1], 500);

		if(preg_match_all('/\b(?:width|max-width)\s*[:=]\s*["\']?([0-9]{2,4}px?|[0-9]{1,3}%)/i', $html, $matches))
		{
			$widths = array();
			foreach($matches[1] as $width)
			{
				if(!in_array($width, $widths))
					$widths[] = $width;
				if(count($widths)>=8)
					break;
			}
			if(count($widths))
				$items[] = 'Widths used: '.implode(', ', $widths);
		}

		if(preg_match_all('/<img\b[^>]*>/i', $html, $matches))
		{
			$images = array();
			foreach($matches[0] as $tag)
			{
				$alt = sendy_ai_get_tag_attribute($tag, 'alt');
				$width = sendy_ai_get_tag_attribute($tag, 'width');
				$height = sendy_ai_get_tag_attribute($tag, 'height');
				$summary = 'image';
				if($width!='' || $height!='')
					$summary .= ' '.$width.'x'.$height;
				if($alt!='')
					$summary .= ' alt "'.sendy_ai_clean_summary_text($alt, 80).'"';
				$images[] = $summary;
				if(count($images)>=6)
					break;
			}
			if(count($images))
				$items[] = 'Image sequence: '.implode('; ', $images);
		}

		if(preg_match_all('/<a\b[^>]*>(.*?)<\/a>/is', $html, $matches))
		{
			$links = array();
			foreach($matches[1] as $link_html)
			{
				$link_text = sendy_ai_clean_summary_text(strip_tags($link_html), 80);
				if($link_text!='' && !in_array($link_text, $links))
					$links[] = $link_text;
				if(count($links)>=8)
					break;
			}
			if(count($links))
				$items[] = 'Link/CTA text found: '.implode(', ', $links);
		}

		return implode("\n", $items);
	}

	function sendy_extract_ai_reference_visible_text($html)
	{
		$text = preg_replace('/<script\b[^>]*>.*?<\/script>/is', ' ', $html);
		$text = preg_replace('/<style\b[^>]*>.*?<\/style>/is', ' ', $text);
		$text = html_entity_decode(strip_tags($text), ENT_QUOTES, 'UTF-8');

		return sendy_ai_clean_summary_text($text, 1800);
	}

	function sendy_ai_get_tag_attribute($tag, $attribute)
	{
		if(preg_match('/\b'.preg_quote($attribute, '/').'\s*=\s*(["\'])(.*?)\1/i', $tag, $matches))
			return html_entity_decode($matches[2], ENT_QUOTES, 'UTF-8');

		if(preg_match('/\b'.preg_quote($attribute, '/').'\s*=\s*([^\s>]+)/i', $tag, $matches))
			return html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');

		return '';
	}

	function sendy_ai_clean_summary_text($text, $limit)
	{
		$text = html_entity_decode($text, ENT_QUOTES, 'UTF-8');
		$text = preg_replace('/\s+/', ' ', trim($text));

		if(strlen($text)>$limit)
			$text = substr($text, 0, $limit).'...';

		return $text;
	}
?>
