<?php include('../functions.php');?>
<?php include('../login/auth.php');?>
<?php
	header('Content-Type: application/json; charset=utf-8');

	$app = isset($_POST['app']) && is_numeric($_POST['app']) ? (int)$_POST['app'] : 0;
	$items = isset($_POST['lists']) ? json_decode($_POST['lists'], true) : null;
	$main_user_id = (int)get_app_info('main_userID');

	if($app < 1 || !is_array($items))
	{
		http_response_code(400);
		echo json_encode(array('success' => false, 'message' => _('Invalid settings.')));
		exit;
	}

	// Confirm the current user owns this brand before accepting any list IDs.
	$owner = mysqli_prepare($mysqli, 'SELECT id FROM apps WHERE id = ? AND userID = ? LIMIT 1');
	mysqli_stmt_bind_param($owner, 'ii', $app, $main_user_id);
	mysqli_stmt_execute($owner);
	mysqli_stmt_store_result($owner);
	$owns_app = mysqli_stmt_num_rows($owner) === 1;
	mysqli_stmt_close($owner);
	if(!$owns_app)
	{
		http_response_code(403);
		echo json_encode(array('success' => false, 'message' => _('You do not have permission to update these lists.')));
		exit;
	}

	$allowed = array();
	$q = 'SELECT id FROM lists WHERE app = '.$app.' AND userID = '.$main_user_id.' AND hide = 0';
	$r = mysqli_query($mysqli, $q);
	if($r) while($row = mysqli_fetch_assoc($r)) $allowed[(int)$row['id']] = true;

	$submitted = array();
	foreach($items as $item)
	{
		$id = isset($item['id']) ? (int)$item['id'] : 0;
		if(!$id || !isset($allowed[$id]) || isset($submitted[$id]))
		{
			http_response_code(400);
			echo json_encode(array('success' => false, 'message' => _('One or more lists are invalid.')));
			exit;
		}
		$submitted[$id] = array(
			'visible' => !empty($item['visible']) ? 1 : 0,
			'name' => trim(isset($item['name']) ? $item['name'] : ''),
			'description' => trim(isset($item['description']) ? $item['description'] : ''),
			'sort' => isset($item['sort']) && is_numeric($item['sort']) ? max(0, (int)$item['sort']) : 0
		);
	}

	// The modal always submits every unhidden list. Reject partial payloads.
	if(count($submitted) !== count($allowed))
	{
		http_response_code(400);
		echo json_encode(array('success' => false, 'message' => _('The list settings are incomplete. Refresh the page and try again.')));
		exit;
	}

	if(function_exists('mysqli_begin_transaction'))
		mysqli_begin_transaction($mysqli);
	else
		mysqli_query($mysqli, 'START TRANSACTION');
	$stmt = mysqli_prepare($mysqli, 'UPDATE lists SET preference_visible = ?, preference_name = ?, preference_description = ?, preference_sort = ? WHERE id = ? AND app = ? AND userID = ? AND hide = 0');
	$saved = $stmt !== false;
	if($stmt)
	{
		$visible = 0;
		$public_name = '';
		$description = '';
		$sort = 0;
		$id = 0;
		mysqli_stmt_bind_param($stmt, 'issiiii', $visible, $public_name, $description, $sort, $id, $app, $main_user_id);
		foreach($submitted as $id => $item)
		{
			$visible = $item['visible'];
			$public_name = $item['name'];
			$description = $item['description'];
			$sort = $item['sort'];
			if(!mysqli_stmt_execute($stmt)) { $saved = false; break; }
		}
		mysqli_stmt_close($stmt);
	}

	if($saved && mysqli_commit($mysqli))
		echo json_encode(array('success' => true));
	else
	{
		mysqli_rollback($mysqli);
		http_response_code(500);
		echo json_encode(array('success' => false, 'message' => _('Unable to save settings. Please try again.')));
	}
?>
