<?php

$profile  = getenv("SAVVY_PROFILE");
if ($profile) {
  require("../../core/backend.${profile}.php");
} else {
  require('../../core/backend.php');
}

require_once('../common/Db.php');
require('./Email.php');

global $savvyext;

$batch_limit = 100;
$sleep_interval = 60;
$max_retries = 3;

$db = new Db();

$client = new GearmanClient();
$client->addServers($savvyext->cfgReadChar('gearman.servers'));

do {
	echo "[".date("Y-m-d H:i:s")."] Scheduler is starting\n";
	$i_need_some_sleep = true;

	$q = "UPDATE emails SET status=0, updated_at=NOW() WHERE status = 2 AND updated_at + interval '5 minutes' < now()";
  pg_query($db->getConnect(), $q);

  $emails = Email::findEmails($db->getConnect(), ['status' => 2], $batch_limit+1);
  if (is_array($emails) && count($emails) < $batch_limit) {
    $emails = Email::findEmails($db->getConnect(), ['status' => 0,'retries' => $max_retries], $batch_limit+1 - count($emails));
    if (is_array($emails) && count($emails)>0) {
      echo "[".date("Y-m-d H:i:s")."] Scheduling ".count($emails)." email(s)\n";
      $i = 1; // Base 1 for > condition
      foreach ($emails as $email) {
        if ($i>$batch_limit) {
          $i_need_some_sleep = true;
          break;
        }
        $q = "UPDATE emails SET status=2, updated_at=NOW() WHERE id=".$email['id'];
        pg_query($db->getConnect(), $q);
        $client->doBackground('sendemail', json_encode($email));
        $i++;
      }
      $i_need_some_sleep = false;
    }
  }

	if ($i_need_some_sleep) {
		sleep($sleep_interval); // Sleep for 1 minute between cycles
	}
} while(true);
