<?php include('../functions.php');?>
<?php include('../login/auth.php');?>
<?php include('../helpers/short.php');?>
<?php
	//------------------------------------------------------//
	//                      	INIT                       //
	//------------------------------------------------------//

	function parse_id_list($val)
	{
		$val = trim($val);
		if($val=='' || $val=='0') return '0';

		$ids = array();
		$vals = explode(',', $val);
		foreach($vals as $id)
		{
			$id = trim($id);
			if($id==='' || !ctype_digit($id)) return false;

			$id = (int)$id;
			if($id > 0) $ids[$id] = $id;
		}

		if(count($ids)==0) return '0';
		return implode(',', $ids);
	}

	$email_list_incl = isset($_POST['include_lists']) ? parse_id_list($_POST['include_lists']) : exit;
	$email_list_excl = isset($_POST['exclude_lists']) ? parse_id_list($_POST['exclude_lists']) : exit;
	$email_list_seg_incl = isset($_POST['include_lists_seg']) ? parse_id_list($_POST['include_lists_seg']) : exit;
	$email_list_seg_excl = isset($_POST['exclude_lists_seg']) ? parse_id_list($_POST['exclude_lists_seg']) : exit;

	if($email_list_incl===false || $email_list_excl===false || $email_list_seg_incl===false || $email_list_seg_excl===false) exit;

	if($email_list_incl==0 && $email_list_seg_incl==0)
	{
		echo 0;
		exit;
	}
	if(($email_list_excl != 0 || $email_list_seg_excl != 0) && ($email_list_incl==0 && $email_list_seg_incl==0))
	{
		echo 0;
		exit;
	}

	//Include main list query
	$include_queries = array();
	if($email_list_incl != 0) $include_queries[] = 's.list IN ('.$email_list_incl.')';
	if($email_list_seg_incl != 0) $include_queries[] = 'ss.seg_id IN ('.$email_list_seg_incl.')';
	$include_query = '('.implode(' OR ', $include_queries).') ';

	//Exclude list and segmentation queries
	$exclude_query = '';
	if($email_list_excl != 0)
		$exclude_query .= 'AND NOT EXISTS (SELECT 1 FROM subscribers ex WHERE ex.email = s.email AND ex.list IN ('.$email_list_excl.')) ';
	if($email_list_seg_excl != 0)
		$exclude_query .= 'AND NOT EXISTS (SELECT 1 FROM subscribers exs INNER JOIN subscribers_seg exss ON (exs.id = exss.subscriber_id) WHERE exs.email = s.email AND exss.seg_id IN ('.$email_list_seg_excl.')) ';

	//------------------------------------------------------//
	//                      FUNCTIONS                       //
	//------------------------------------------------------//

	//Check if we should send to GDPR subscribers only
	$gdpr_only = 0;
	if($email_list_incl!=0) $q = 'SELECT gdpr_only FROM apps LEFT JOIN lists ON (apps.id = lists.app) WHERE lists.id IN ('.$email_list_incl.') LIMIT 1';
	else $q = 'SELECT gdpr_only FROM apps LEFT JOIN seg ON (apps.id = seg.app) WHERE seg.id IN ('.$email_list_seg_incl.') LIMIT 1';
	$r = mysqli_query($mysqli, $q);
	if ($r) while($row = mysqli_fetch_array($r)) $gdpr_only = $row['gdpr_only'];
	$gdpr_line = $gdpr_only ? 'AND s.gdpr = 1 ' : '';

	$seg_join = $email_list_seg_incl==0 ? ' ' : ' LEFT JOIN subscribers_seg ss ON (s.id = ss.subscriber_id) ';
	$where = 'WHERE '.$include_query.
			 $exclude_query.
			 'AND s.unsubscribed = 0 AND s.bounced = 0 AND s.complaint = 0 AND s.confirmed = 1 '.$gdpr_line;

	//Get total unique recipients without returning the full recipient set to PHP
	$q  = 'SELECT COUNT(DISTINCT s.email) AS total FROM subscribers s';
	$q .= $seg_join;
	$q .= $where;
	$r = mysqli_query($mysqli, $q);
	if (!$r)
	{
		error_log("[Unable to calculate recipient count]".mysqli_error($mysqli).': in '.__FILE__.' on line '.__LINE__);
		echo 'failed';
		exit;
	}
	$row = mysqli_fetch_array($r);
	$total = $row['total'];

	//Get up to 100 deterministic subscribers for real data preview without grouping the full recipient set.
	$subs_array = array();
	$seen_emails = array();
	$i = 1;
	$last_id = 0;
	$batch_size = 1000;
	$preview_failed = false;

	while($i <= 100)
	{
		$q  = 'SELECT s.id, s.list, s.email FROM subscribers s';
		$q .= $seg_join;
		$q .= $where;
		$q .= 'AND s.id > '.$last_id.' ORDER BY s.id ASC LIMIT '.$batch_size;
		$r = mysqli_query($mysqli, $q);
		if (!$r)
		{
			error_log("[Unable to calculate recipient previews]".mysqli_error($mysqli).': in '.__FILE__.' on line '.__LINE__);
			$preview_failed = true;
			break;
		}

		if(mysqli_num_rows($r)==0) break;

		while($row = mysqli_fetch_array($r))
		{
			$last_id = (int)$row['id'];
			$email_key = strtolower($row['email']);
			if(isset($seen_emails[$email_key])) continue;

			$seen_emails[$email_key] = true;
			$subs_array['s'.$i] = array(
				'id' => encrypt_val($row['id']),
				'list_id' => encrypt_val($row['list']),
				'email' => $row['email']
			);

			$i++;
			if($i > 100) break;
		}

		if(mysqli_num_rows($r) < $batch_size) break;
	}

	if (!$preview_failed)
	{
		echo $total.'|'.json_encode($subs_array);
	}
	else
	{
		echo 'failed';
	}
?>
