<?php

class Email {

  static function createEmail($db, $to, $subject, $htmlBody) {
    $result = array();

    $status = '0';

    $values = array(
      "to_emails" => NULL,
      "subject" => NULL,
      "html_body" => NULL,
      "status"=>"0",
      "created_at"=>(new DateTime())->format('c'),
      "updated_at"=>(new DateTime())->format('c')
    );

    if(isset($to)) {
      $values["to_emails"] = Email::prepareEmailsQueryString($to);
    }

    if(isset($subject)) {
      $values["subject"] = pg_escape_string($subject);
    }

    if(isset($htmlBody)) {
      $values["html_body"] = pg_escape_string($htmlBody);
    }

    $values = array_filter($values, 'strlen');

    $q  = "INSERT INTO emails";

    // implode keys of $values...
    $q .= " (".implode(", ", array_keys($values)).")";

    // implode values of $values...
    $q .= " VALUES ('".implode("', '", $values)."') ";

    $rs = pg_query($db, $q);

    if (!$rs) {
      return array("success" => false, "message" => "Something went wrong!");
      exit;
    }
    return array("success" => (boolean)pg_affected_rows($rs), "message" => "Successfully create new email.");
  }

  static function getEmailById($db, $id) {
    $result = [];
    $q = "SELECT * from emails where id = '" . pg_escape_string($id) . "'";

    $rs = pg_query($db, $q);

    while ($row = pg_fetch_assoc($rs)) {
      array_push($result, Email::parseData($row));
    }

    return array("success" => true, "data" => $result[0]);
  }

  static function findEmails($db, $filter, $limit=0)
  {
    $results = array();
    $condition = [];
    $q = "SELECT * FROM emails";

    if (count($filter)) {
      $q .= " where ";
      if (isset($filter['status'])) {
        $condition[] = "status = '" . pg_escape_string($filter['status']) . "'";
      }
      if (isset($filter['retries'])) {
        $condition[] = "retries < ".((int)$filter['retries']);
      }
    }

    $q .= implode(" AND ", $condition);

    if ($limit>0) {
      $q.= " LIMIT ".$limit;
    }

    $rs = pg_query($db, $q);

    while ($row = pg_fetch_assoc($rs)) {
      array_push($results, Email::parseData($row));
    }

    return $results ?? NULL;
  }

  public static function updateEmail($db, $id, $to, $subject, $htmlBody, $status) {
    if (!isset($id)) {
      return;
    }

    $q = "update emails set ";
    $values = [
      "updated_at = '" . (new DateTime())->format('c') ."'"
    ];

    if (isset($to)) {
      // $q .= "to_email = " . Email::prepareEmailsQueryString($to);
      $values[] = "to_emails = '" . Email::prepareEmailsQueryString($to) . "'";
    }

    if (isset($subject)) {
      $values[] = "subject = '" . pg_escape_string($subject) . "'";
    }

    if (isset($htmlBody)) {
      $values[] = "html_body = '" . pg_escape_string($htmlBody) . "'";
    }

    if (isset($status)) {
      $values[] = "status = '" . pg_escape_string($status) . "'";
    }

    $q .= implode(", ", $values);
    $q .= " where id = " . pg_escape_string((string)$id);

    $r = pg_query($db, $q);

    if (!$r) {
      return array("success" => false, "message" => "Something went wrong!");
      exit;
    }

    return array("success" => true, "message" => "Successfully update email.");
  }

  private static function parseData($obj) {
    $emails = $obj['to_emails'];
    $emails = str_replace('{', '', $emails);
    $emails = str_replace('}', '', $emails);

    $emails = explode(',', $emails);

    $obj['to_emails'] = $emails;

    return $obj;
  }

  private static function prepareEmailsQueryString($to) {
    $result = "{";
    $result .= join(',', $to);
    $result .= "}";
    return $result;
  }
}
