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

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

	function sendy_ai_report_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;
	$report_type = isset($_POST['report_type']) ? $_POST['report_type'] : '';
	$report_id = isset($_POST['report_id']) && is_numeric($_POST['report_id']) ? (int)$_POST['report_id'] : 0;
	if($app!=0) $_GET['i'] = $app;

	if($app==0 || $report_id==0 || ($report_type!='campaign' && $report_type!='autoresponder'))
		sendy_ai_report_response(400, array('error' => _('Invalid report.')));

	if($app != (int)get_app_info('app'))
		sendy_ai_report_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_report_response(403, array('error' => _('You do not have access to this brand.')));

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

	if(!sendy_ai_addon_enabled())
		sendy_ai_report_response(403, array('error' => _('Unlock AI features to analyze reports.'), '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_report_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_report_response(400, array('error' => _('Save an OpenAI API key in Brand settings > AI settings first.')));

	$metrics = $report_type=='campaign' ? sendy_campaign_report_analysis_metrics($report_id) : sendy_autoresponder_report_analysis_metrics($report_id);
	if(!is_array($metrics))
		sendy_ai_report_response(404, array('error' => _('Report not found.')));

	try
	{
		$client = new SendyOpenAiClient($openai_api_key);
		$analysis = $client->generate_campaign_report_analysis($metrics);
		$score = $client->generate_campaign_report_score($metrics);
		$analysis = sendy_report_analysis_html($analysis);
		$metrics_json = json_encode($metrics);
		if($metrics_json===false) $metrics_json = '';

		if(!sendy_report_analysis_save_result($report_type, $report_id, $app, get_app_info('main_userID'), $analysis, $metrics_json, 1, $score))
			sendy_ai_report_response(500, array('error' => _('Unable to save campaign analysis.')));

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