<?php
	ini_set('display_errors', 0);
	mysqli_report(MYSQLI_REPORT_OFF);
	include('includes/config.php');
	include('includes/helpers/locale.php');

	function dbConnect()
	{
		global $mysqli, $dbHost, $dbUser, $dbPass, $dbName, $dbPort, $charset;
		$mysqli = isset($dbPort) ? new mysqli($dbHost, $dbUser, $dbPass, $dbName, $dbPort) : new mysqli($dbHost, $dbUser, $dbPass, $dbName);
		if($mysqli->connect_error) exit('Database error');
		mysqli_set_charset($mysqli, isset($charset) ? $charset : 'utf8');
		return $mysqli;
	}
	dbConnect();
	include('includes/helpers/short.php');
	include('includes/helpers/preferences.php');

	function preference_h($value)
	{
		return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
	}

	function preference_event($app, $list, $email, $action)
	{
		global $mysqli;
		$ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
		$agent = isset($_SERVER['HTTP_USER_AGENT']) ? substr($_SERVER['HTTP_USER_AGENT'], 0, 500) : '';
		$q = 'INSERT INTO subscriber_preference_events (app, list, email, action, ip, user_agent, created) VALUES ('
			.(int)$app.', '.($list === null ? 'NULL' : (int)$list).', "'.mysqli_real_escape_string($mysqli, $email).'", "'
			.mysqli_real_escape_string($mysqli, $action).'", "'.mysqli_real_escape_string($mysqli, $ip).'", "'
			.mysqli_real_escape_string($mysqli, $agent).'", '.time().')';
		mysqli_query($mysqli, $q);
	}

	$preview = isset($_GET['preview']) && $_GET['preview'] === '1';
	$token = isset($_GET['t']) ? $_GET['t'] : (isset($_POST['t']) ? $_POST['t'] : '');
	$token_data = sendy_preferences_token_data($token);
	$invalid = $token_data === false;
	$saved = false;
	$error = '';
	$lists = array();
	$app_name = _('Email preferences');
	$brand_logo = '';
	$email = '';

	if(!$invalid)
	{
		$app = $token_data['app'];
		$email = $token_data['email'];
		$q = 'SELECT app_name, from_email, brand_logo_filename, custom_domain, custom_domain_protocol, custom_domain_enabled FROM apps WHERE id = '.$app.' LIMIT 1';
		$r = mysqli_query($mysqli, $q);
		if(!$r || mysqli_num_rows($r) == 0) $invalid = true;
		else
		{
			$row = mysqli_fetch_array($r);
			$app_name = $row['app_name'];
			if($row['brand_logo_filename']!='')
			{
				$logo_filename = basename($row['brand_logo_filename']);
				$brand_logo = file_exists(__DIR__.'/uploads/'.$app.'/logos/'.$logo_filename)
					? rtrim(APP_PATH, '/').'/uploads/'.$app.'/logos/'.rawurlencode($logo_filename)
					: rtrim(APP_PATH, '/').'/uploads/logos/'.rawurlencode($logo_filename);
			}
			else
			{
				$from_parts = explode('@', $row['from_email']);
				if(isset($from_parts[1]) && $from_parts[1]!='')
					$brand_logo = 'https://www.google.com/s2/favicons?domain='.rawurlencode($from_parts[1]).'&sz=64';
			}
		}
	}

	if(!$invalid)
	{
		$q = 'SELECT id, userID, name, preference_name, preference_description, preference_sort FROM lists WHERE app = '.$app.' AND preference_visible = 1 AND hide = 0 ORDER BY preference_sort ASC, name ASC';
		$r = mysqli_query($mysqli, $q);
		if($r) while($row = mysqli_fetch_assoc($r)) $lists[(int)$row['id']] = $row;

		if(!$preview && $_SERVER['REQUEST_METHOD'] === 'POST')
		{
			$csrf = isset($_POST['csrf']) ? $_POST['csrf'] : '';
			$expected_csrf = hash_hmac('sha256', 'preferences-form|'.$token, API_KEY);
			if(!hash_equals($expected_csrf, $csrf)) $error = _('The form has expired. Please open your preference link again.');
			else
			{
				$selected = isset($_POST['lists']) && is_array($_POST['lists']) ? array_map('intval', $_POST['lists']) : array();
				$selected = array_flip($selected);
				$unsubscribe_all = isset($_POST['unsubscribe_all']);
				$email_sql = mysqli_real_escape_string($mysqli, $email);
				mysqli_begin_transaction($mysqli);

				if($unsubscribe_all)
				{
					$q = 'SELECT subscribers.id, subscribers.list FROM subscribers INNER JOIN lists ON lists.id = subscribers.list WHERE lists.app = '.$app.' AND subscribers.email = "'.$email_sql.'" AND subscribers.unsubscribed = 0';
					$r = mysqli_query($mysqli, $q);
					$changed = array();
					if($r) while($row = mysqli_fetch_assoc($r)) $changed[] = (int)$row['list'];
					mysqli_query($mysqli, 'UPDATE subscribers INNER JOIN lists ON lists.id = subscribers.list SET subscribers.unsubscribed = 1, subscribers.timestamp = '.time().' WHERE lists.app = '.$app.' AND subscribers.email = "'.$email_sql.'"');
					foreach($changed as $list_id) preference_event($app, $list_id, $email, 'unsubscribed');
				}
				else
				{
					$name = '';
					$r_name = mysqli_query($mysqli, 'SELECT subscribers.name FROM subscribers INNER JOIN lists ON lists.id = subscribers.list WHERE lists.app = '.$app.' AND subscribers.email = "'.$email_sql.'" AND subscribers.name != "" LIMIT 1');
					if($r_name && mysqli_num_rows($r_name)) $name = mysqli_fetch_assoc($r_name)['name'];
					$brand_blocked = false;
					$r_blocked = mysqli_query($mysqli, 'SELECT subscribers.id FROM subscribers INNER JOIN lists ON lists.id = subscribers.list WHERE lists.app = '.$app.' AND subscribers.email = "'.$email_sql.'" AND (subscribers.bounced = 1 OR subscribers.complaint = 1) LIMIT 1');
					if($r_blocked && mysqli_num_rows($r_blocked)) $brand_blocked = true;

					foreach($lists as $list_id => $list)
					{
						$want = isset($selected[$list_id]);
						$r_sub = mysqli_query($mysqli, 'SELECT id, unsubscribed, bounced, complaint, confirmed FROM subscribers WHERE list = '.$list_id.' AND email = "'.$email_sql.'" LIMIT 1');
						$subscriber = $r_sub && mysqli_num_rows($r_sub) ? mysqli_fetch_assoc($r_sub) : false;

						if($want && !$brand_blocked)
						{
							if($subscriber && !$subscriber['bounced'] && !$subscriber['complaint'])
							{
								if($subscriber['unsubscribed'] || !$subscriber['confirmed']) preference_event($app, $list_id, $email, 'subscribed');
								mysqli_query($mysqli, 'UPDATE subscribers SET unsubscribed = 0, confirmed = 1, gdpr = 1, timestamp = '.time().' WHERE id = '.(int)$subscriber['id']);
							}
							else if(!$subscriber)
							{
								mysqli_query($mysqli, 'INSERT INTO subscribers (userID, name, email, list, timestamp, confirmed, unsubscribed, bounced, complaint, gdpr) VALUES ('.(int)$list['userID'].', "'.mysqli_real_escape_string($mysqli, $name).'", "'.$email_sql.'", '.$list_id.', '.time().', 1, 0, 0, 0, 1)');
								preference_event($app, $list_id, $email, 'subscribed');
							}
						}
						else if(!$want && $subscriber && !$subscriber['unsubscribed'])
						{
							mysqli_query($mysqli, 'UPDATE subscribers SET unsubscribed = 1, timestamp = '.time().' WHERE id = '.(int)$subscriber['id']);
							preference_event($app, $list_id, $email, 'unsubscribed');
						}
					}
					if($brand_blocked && count($selected)) $error = _('Preferences were saved, but subscriptions cannot be restored for an address marked as bounced or complained.');
				}

				if(mysqli_commit($mysqli)) $saved = true;
				else { mysqli_rollback($mysqli); $error = _('Unable to save your preferences. Please try again.'); }
			}
		}

		foreach($lists as $list_id => &$list)
		{
			$r_sub = mysqli_query($mysqli, 'SELECT unsubscribed, bounced, complaint, confirmed FROM subscribers WHERE list = '.$list_id.' AND email = "'.mysqli_real_escape_string($mysqli, $email).'" LIMIT 1');
			$sub = $r_sub && mysqli_num_rows($r_sub) ? mysqli_fetch_assoc($r_sub) : false;
			$list['checked'] = $preview ? true : ($sub && !$sub['unsubscribed'] && !$sub['bounced'] && !$sub['complaint'] && $sub['confirmed']);
		}
		unset($list);
	}
?>
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<meta name="robots" content="noindex, nofollow">
	<title><?php echo preference_h($app_name);?> — <?php echo _('Email preferences');?></title>
	<style>
		body{margin:0;background:#f7f9fc;color:#252a34;font-family:Arial,Helvetica,sans-serif}.card{box-sizing:border-box;max-width:600px;margin:60px auto;padding:34px;background:#fff;border-radius:8px;box-shadow:0 16px 46px -30px rgba(0,0,0,.6)}h1{margin:0 0 8px;font-size:27px}.title{display:flex;align-items:center;gap:10px}.title-icon{width:25px;height:25px;flex:0 0 auto;color:#596273}.brand-identity{display:flex;align-items:flex-start;gap:7px;margin:0 0 18px}.brand-identity p{margin:0}.brand-logo{width:16px;height:16px;flex:0 0 auto;margin-top:3px;object-fit:contain}p{line-height:1.5;color:#626b78}.email{font-weight:bold;color:#252a34}.topic{display:grid;grid-template-columns:20px minmax(0,1fr);column-gap:12px;align-items:start;padding:17px 0;border-top:1px solid #e8ebef}.topic input{margin:3px 0 0}.topic strong,.topic small{grid-column:2;display:block}.topic small{margin-top:4px;color:#68717e;line-height:1.4}.actions{margin-top:24px}.button{border:0;border-radius:4px;background:#222;color:#fff;padding:11px 18px;font-size:14px;cursor:pointer}.danger{margin-top:0}.notice{padding:12px 14px;border-radius:4px;background:#edf8ef;color:#246a32}.error{padding:12px 14px;border-radius:4px;background:#fff0f0;color:#9e2b2b}@media(max-width:660px){.card{margin:0;min-height:100vh;border-radius:0;padding:25px 20px}}
	</style>
</head>
<body>
	<div class="card">
	<?php if($invalid):?>
		<h1><?php echo _('This preference link is invalid or has expired.');?></h1>
		<p><?php echo _('Use the manage subscription link in a more recent email.');?></p>
	<?php else:?>
		<h1 class="title"><svg class="title-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="5" width="18" height="14" rx="2"></rect><path d="m4 7 8 6 8-6"></path></svg><?php echo _('Manage subscription');?></h1>
		<div class="brand-identity">
			<?php if($brand_logo!=''):?><img class="brand-logo" src="<?php echo preference_h($brand_logo);?>" alt=""><?php endif;?>
			<p><?php echo preference_h($app_name);?><br><span class="email"><?php echo preference_h($email);?></span></p>
		</div>
		<?php if($preview):?><p class="notice"><?php echo _('Preview mode — subscription changes are disabled.');?></p><?php endif;?>
		<?php if($saved && !$error):?><p class="notice"><?php echo _('Your email preferences have been saved.');?></p><?php endif;?>
		<?php if($error):?><p class="error"><?php echo preference_h($error);?></p><?php endif;?>
		<form method="post" action="">
			<input type="hidden" name="t" value="<?php echo preference_h($token);?>">
			<input type="hidden" name="csrf" value="<?php echo hash_hmac('sha256', 'preferences-form|'.$token, API_KEY);?>">
			<?php if(count($lists)):?>
			<?php foreach($lists as $list_id => $list):?>
			<label class="topic">
				<input type="checkbox" class="preference-list-checkbox" name="lists[]" value="<?php echo $list_id;?>" <?php if($list['checked']) echo 'checked';?> <?php if($preview) echo 'disabled';?>>
				<strong><?php echo preference_h($list['preference_name']!='' ? $list['preference_name'] : $list['name']);?></strong>
				<?php if($list['preference_description']!=''):?><small><?php echo nl2br(preference_h($list['preference_description']));?></small><?php endif;?>
			</label>
			<?php endforeach;?>
			<?php else:?><p><?php echo _('There are currently no email preferences available to manage.');?></p><?php endif;?>
			<label class="topic danger"><input type="checkbox" id="unsubscribe-all" name="unsubscribe_all" value="1" <?php if($preview) echo 'disabled';?>><strong><?php echo _('Unsubscribe me from all emails');?></strong></label>
			<div class="actions"><button class="button" type="submit" <?php if($preview) echo 'disabled';?>><?php echo _('Update subscription');?></button></div>
		</form>
	<?php endif;?>
	</div>
	<script>
		(function(){
			var unsubscribeAll = document.getElementById('unsubscribe-all');
			var listCheckboxes = document.querySelectorAll('.preference-list-checkbox');
			if(!unsubscribeAll) return;

			unsubscribeAll.addEventListener('change', function(){
				if(!this.checked) return;
				for(var i=0; i<listCheckboxes.length; i++) listCheckboxes[i].checked = false;
			});

			for(var i=0; i<listCheckboxes.length; i++)
			{
				listCheckboxes[i].addEventListener('change', function(){
					if(this.checked) unsubscribeAll.checked = false;
				});
			}
		})();
	</script>
</body>
</html>
