<?php

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

require './vendor/autoload.php';

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

global $savvyext;

$db = new Db();

$apiKey = $savvyext->cfgReadChar('mailsend.api_key');
$sg = new \SendGrid($apiKey);


$worker= new GearmanWorker();
$worker->addServers($savvyext->cfgReadChar('gearman.servers'));
$worker->addFunction('sendemail', 'sendEmailJob');

while (1)
{
	$worker->work();
	if ($worker->returnCode() != GEARMAN_SUCCESS) break;
}

function sendEmailJob($job) {
  global $db, $sg;
	echo "[".date("Y-m-d H:i:s")."] Send Email job starting\n";

  $workload = $job->workload();
  $email = json_decode($workload, true);  
  $id = $email['id'];

  echo "[".date("Y-m-d H:i:s")."] Processing email ID #${id}\n";

//  $q = "UPDATE emails SET status=2, updated_at=NOW() WHERE id=${id}";
//  pg_query($db->getConnect(), $q);

  if (is_array($email) && array_key_exists('to_emails',$email) 
   && is_array($email['to_emails']) && count($email['to_emails'])>0) {

    $receivers = array_map(function($to) {
      return ['email' => $to];
    }, $email['to_emails']);

    // Prepare sendgrid receivers
    $sendgridReceivers = prepareReceivers($receivers, []);
    $subject = $email['subject'] ?? '';
    $template = $email['html_body'] ?? '';

    // Prepare email will be sent through sendgrid
    $parsedEmail = SendGridService::prepareEmail($sendgridReceivers, $subject, $template, []);

    // Send email
    try {
      $response = $sg->send($parsedEmail);
      //Email::updateEmail($db->getConnect(), $id, NULL, NULL, NULL, '1');
      if ($response->statusCode()==202) {
        $q = "UPDATE emails SET status=1,updated_at=NOW(),message=NULL WHERE id=".$id;
        $r = pg_query($db->getConnect(), $q);
      } else {
        throw new Exception("Invalid return status code: ".$response->statusCode());
      }
      echo "[".date("Y-m-d H:i:s")."] Email sent successfully.\n";
    } catch(Exception $e) {
      // TODO: Handle send email error.
      // Maybe we can log the error here
      $msg = pg_escape_string(substr($e->getMessage(),0,200));
      $q = "UPDATE emails SET  status=0, retries=retries+1, updated_at=NOW(),message='${msg}' WHERE id= ${id}";
      $r = pg_query($db->getConnect(), $q);
      echo "[".date("Y-m-d H:i:s")."] Email not sent: ${msg}\n";
    }
  }
	echo "[".date("Y-m-d H:i:s")."] Send Email job complete\n";
}

function prepareReceivers($receivers = [], $subs = []) {
  $results = [];
  foreach ( $receivers as $key => $receiver ) {
    $substitutions = array_merge($subs, $receiver['substitutions'] ?? []);
    $results[] = SendGridService::prepareSengridToObject($receiver, $substitutions ?? []) ?? NULL;
  }
  return $results;
}
