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

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

	function sendy_ai_improvements_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;
	$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;
	$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 || ($content_type!='campaign' && $content_type!='autoresponder'))
		sendy_ai_improvements_state_response(400, array('error' => _('Invalid email content.')));

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

	if(!sendy_content_improvements_save_state($content_type, $content_id, $parent_id, $app, get_app_info('main_userID'), $is_open ? 1 : 0))
		sendy_ai_improvements_state_response(500, array('error' => _('Unable to save improvement suggestion state.')));

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