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

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

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

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

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

	if(!sendy_report_analysis_save_state($report_type, $report_id, $app, get_app_info('main_userID'), $is_open ? 1 : 0))
		sendy_ai_report_state_response(500, array('error' => _('Unable to save campaign analysis state.')));

	sendy_ai_report_state_response(200, array('success' => true));
?>
