<?php include('../functions.php');?>
<?php include('../login/auth.php');?>
<?php 	
	//init
	$campaign_id = isset($_POST['campaign_id']) && is_numeric($_POST['campaign_id']) ? mysqli_real_escape_string($mysqli, (int)$_POST['campaign_id']) : exit;
	$loader = get_app_info('dark_mode') ? 'loader-dark.gif' : 'loader-light.gif';
	
	//get send count
	$q = 'SELECT to_send, recipients, send_status, send_error FROM campaigns WHERE id = '.$campaign_id;
	$r = mysqli_query($mysqli, $q);
	if ($r)
	{
	    while($row = mysqli_fetch_array($r))
	    {
			$to_send = $row['to_send'];
			$recipients = $row['recipients'];
			$send_status = $row['send_status'];
			$send_error = $row['send_error'];
	    }  
	}

	//If a sender process disappeared while a durable SES batch claim exists,
	//surface the interruption even before the next cron run.
	if($send_status!='interrupted')
	{
		$in_flight_result = mysqli_query($mysqli, 'SELECT COUNT(*) AS in_flight FROM queue WHERE campaign_id = '.$campaign_id.' AND sent = 2');
		$lock_name = mysqli_real_escape_string($mysqli, 'sendy_campaign_send_'.$campaign_id);
		$lock_result = mysqli_query($mysqli, 'SELECT IS_USED_LOCK("'.$lock_name.'") AS lock_owner');
		if($in_flight_result && $lock_result)
		{
			$in_flight_row = mysqli_fetch_array($in_flight_result);
			$lock_row = mysqli_fetch_array($lock_result);
			if((int)$in_flight_row['in_flight'] > 0 && $lock_row['lock_owner'] === NULL)
			{
				$send_status = 'interrupted';
				$send_error = 'The previous sender stopped while an Amazon SES batch was in flight.';
				mysqli_query($mysqli, 'UPDATE campaigns SET send_status = "interrupted", send_error = "'.$send_error.'" WHERE id = '.$campaign_id);
			}
		}
	}
	
	$percentage = $recipients!=0 ? $recipients / $to_send * 100 : 0;
	
	if($send_status=='interrupted')
		echo '<span data-sendy-interrupted="1" class="text-error" title="'.htmlspecialchars($send_error, ENT_QUOTES, 'UTF-8').'">'.$recipients.' <span>('.round($percentage).'%)</span> - '._('Interrupted').'</span>';
	else if($to_send == $recipients)
		echo $recipients;
	else
		echo $recipients.' <span style="color:#488846;">('.round($percentage).'%)</span> <img src="'.get_app_info('path').'/img/'.$loader.'" style="width:16px;"/>';
?>
