<?php
	include('../functions.php');
	include('../login/auth.php');
	include('../helpers/openai.php');

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

	function sendy_ai_subject_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;
	$html = isset($_POST['html']) ? $_POST['html'] : '';
	$plain = isset($_POST['plain']) ? $_POST['plain'] : '';
	$current_subject = isset($_POST['current_subject']) ? $_POST['current_subject'] : '';
	$prompt_mode = isset($_POST['prompt_mode']) ? $_POST['prompt_mode'] : 'compelling';
	$custom_prompt = isset($_POST['custom_prompt']) ? $_POST['custom_prompt'] : '';

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

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

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

	if(!sendy_ai_addon_enabled())
		sendy_ai_subject_response(403, array('error' => _('Unlock AI features to generate subject lines.'), '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_subject_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_subject_response(400, array('error' => _('Save an OpenAI API key in Brand settings > AI settings first.')));

	try
	{
		$client = new SendyOpenAiClient($openai_api_key);
		$subject = $client->generate_subject_line($html, $plain, $current_subject, $prompt_mode, $custom_prompt);

		sendy_ai_subject_response(200, array(
			'subject' => $subject
		));
	}
	catch(Exception $e)
	{
		error_log('[Sendy AI subject generator] '.$e->getMessage().': in '.__FILE__.' on line '.__LINE__);
		sendy_ai_subject_response(500, array(
			'error' => $e->getMessage()
		));
	}
?>
