<?php
	include('../functions.php');
	include('../login/auth.php');
	include('../helpers/openai.php');
	include('../helpers/report-analysis.php');
	include('../helpers/content-improvements-analysis.php');

	header('Content-Type: application/json');

	function sendy_ai_improvements_response($status_code, $payload)
	{
		http_response_code($status_code);
		echo json_encode($payload);
		exit;
	}

	$app = isset($_POST['app']) && is_numeric($_POST['app']) ? (int)$_POST['app'] : 0;
	$content_type = isset($_POST['content_type']) ? $_POST['content_type'] : '';
	$content_id = isset($_POST['content_id']) && is_numeric($_POST['content_id']) ? (int)$_POST['content_id'] : 0;
	$parent_id = isset($_POST['parent_id']) && is_numeric($_POST['parent_id']) ? (int)$_POST['parent_id'] : 0;
	$html = isset($_POST['html']) ? $_POST['html'] : '';
	$plain = isset($_POST['plain']) ? $_POST['plain'] : '';
	$current_subject = isset($_POST['current_subject']) ? $_POST['current_subject'] : '';
	$content_preview = trim(preg_replace('/\s+/', ' ', html_entity_decode(strip_tags($plain.' '.$html), ENT_QUOTES, 'UTF-8')));

	if($app==0)
		sendy_ai_improvements_response(400, array('error' => _('Invalid brand.')));

	$_GET['i'] = $app;

	if($content_type!='campaign' && $content_type!='autoresponder')
		sendy_ai_improvements_response(400, array('error' => _('Invalid email content.')));

	if($content_preview=='')
		sendy_ai_improvements_response(400, array('error' => _('Write some email content first, then I can suggest improvements.')));

	if($app != (int)get_app_info('app'))
		sendy_ai_improvements_response(403, array('error' => _('You do not have access to this brand.')));

	if(get_app_info('is_sub_user') && (int)get_app_info('restricted_to_app') !== $app)
		sendy_ai_improvements_response(403, array('error' => _('You do not have access to this brand.')));

	if(sendy_brand_ai_disabled($app))
		sendy_ai_improvements_response(403, array('error' => _('AI features are disabled for this brand.')));

	if(!sendy_ai_addon_enabled())
		sendy_ai_improvements_response(403, array('error' => _('Unlock AI features to suggest improvements.'), 'ai_addon_required' => true));

	$q = 'SELECT openai_api_key FROM apps WHERE id = '.$app.' AND userID = '.get_app_info('main_userID').' LIMIT 1';
	$r = mysqli_query($mysqli, $q);
	if(!$r || mysqli_num_rows($r)==0)
		sendy_ai_improvements_response(404, array('error' => _('Brand not found.')));

	$row = mysqli_fetch_array($r);
	$openai_api_key = isset($row['openai_api_key']) ? trim($row['openai_api_key']) : '';

	if($openai_api_key=='')
		sendy_ai_improvements_response(400, array('error' => _('Save an OpenAI API key in Brand settings > AI settings first.')));

	try
	{
		$client = new SendyOpenAiClient($openai_api_key);
		$analysis = $client->generate_email_content_improvements($html, $plain, $current_subject);
		$analysis = sendy_report_analysis_html($analysis);
		$source_json = json_encode(array(
			'subject' => $current_subject,
			'plain' => $plain,
			'html' => $html
		));
		if($source_json===false) $source_json = '';

		if(!sendy_content_improvements_save_result($content_type, $content_id, $parent_id, $app, get_app_info('main_userID'), $analysis, $source_json, 1))
			sendy_ai_improvements_response(500, array('error' => _('Unable to save improvement suggestions.')));

		sendy_ai_improvements_response(200, array(
			'analysis' => $analysis
		));
	}
	catch(Exception $e)
	{
		error_log('[Sendy email improvement suggestions] '.$e->getMessage().': in '.__FILE__.' on line '.__LINE__);
		sendy_ai_improvements_response(500, array(
			'error' => $e->getMessage()
		));
	}
?>
