<?php #lib/40_email.php

/********************************************************************************
 *	Content: email related functions                                        *
 *	Author: Nils Otterpohl                                                  *
 ********************************************************************************/

function emlSendEmail($to, $subject, $text) {
  global $mail;
  
  $mail->setFrom(MAILNOREPLY, "Webserver OF Innenstadt");
  $mail->isHTML(true);
  $mail->Subject = $subject;
  $mail->Body = $text;
  $mail->addAddress($to);
  $mail->send();
  $mail->clearAddresses();
}

// Aus pgs/xx_termine/lib.php

function printTeilnehmer($val) {
  $ret = "<tr><td>".$val["Nachnamen"].", ".$val["Vornamen"]."</td><td>";
  $traits = array();
  
  if ($val["ZF"]) $traits[] = "ZF";
  if ($val["GF"]) $traits[] = "GF";
  if ($val["KF"]) $traits[] = "KF";
  if ($val["AGT"]) $traits[] = "AGT";
  if ($val["TH"]) $traits[] = "TH";
  if (!$val["TM"]) $traits[] = "Kein Grundlehrgang";
  if (count($traits)) $ret.= implode(", ", $traits);
  
  $ret.= "</td><td>Corona-Unterweisung: ".($val["CoronaUnt"] ? "Ja" : "Nein")."</td>"
        ."<td>".($val["Teilnehmer"] ? "Dabei" : "Will")."</td></tr>\n";
  return $ret;
}

function informParticipant($name, $mail, $can, $dienst, $verantwortliche) {
  $text = "Hallo ".$name."!<br/><br/>\nDu hast dich für ".$dienst." angemeldet.<br/><br/>";
  if ($can) {
    $text.= "Du wurdest zu diesem Dienst als Teilnehmer ausgelost und <b>DARFST KOMMEN</b>. Sei bitte pünktlich und bring eine Maske mit!<br/>"
           ."Wenn Du dich am Tag des Dienstes nicht gesund fühlst, bleib zuhause! Wenn Du aus welchem Grund auch immer doch nicht kommen kannst, "
           ."teile dieses bitte unverzüglich deinen Diensthabenden mit: ".$verantwortliche."<br/><br/>\n";
  } else {
    $text.= "Leider hattest Du diesmal Pech und <u>DARFST N I C H T KOMMEN</u>. Dafür wirst Du bei den nächsten Verlosungen bevorzugt.<br/><br/>\n";
  }
  $text.= "Viele Grüße vom Webserver der OF Innenstadt!";
  emlSendEmail($mail, "Ergebnis der Platzvergabe für ".$dienst, $text);
}

function informParticipantFromID($mysqli, $terminID, $personalID, $can) {
  $qry = "SELECT Beginn,Thema,Verantwortliche,a.Name FROM Termine t LEFT JOIN Termine_Kategorien a ON a.ID = t.Kategorie WHERE t.ID = '".$terminID."'";
  $res = $mysqli->query($qry);
  $termin = $res->fetch_assoc();
  $qry = "SELECT Vornamen,Login FROM Personal p WHERE p.ID = '".$personalID."'";
  $res = $mysqli->query($qry);
  if ($personal = $res->fetch_assoc())
    informParticipant($personal["Vornamen"], $personal["Login"]."@feuerwehr-bs.net", $can, $termin["Name"]." am ".date("d.m.Y H:i", strtotime($termin["Beginn"])), $termin["Verantwortliche"]);
}

function sendParticipantsListToResponsibles($mysqli, $terminID) {
  $qry = "SELECT t.Beginn,IF(t.Beginn>=NOW(),1,0) nichtvorbei,t.Thema,t.Verantwortliche,a.Name as aName FROM Termine t "
        ."LEFT JOIN Termine_Kategorien a ON a.ID=t.Kategorie "
        ."WHERE t.ID='".$terminID."'";
  $res = $mysqli->query($qry);
  $tmrow = $res->fetch_assoc();

  if ("1" == $tmrow["nichtvorbei"]) {
    // Generate participants list
    $qry = "SELECT p.ID,p.Login,p.Nachnamen,p.Vornamen,pk.Name pkName,pf.Kürzel pfKürzel,GROUP_CONCAT(l.Kürzel) lKürzel, tt.Status "
          ."FROM Termine_Teilnahmen tt "
          ."LEFT JOIN Personal p ON p.ID=tt.Personal "
          ."LEFT JOIN Personal_Kategorien pk ON pk.ID=p.Kategorie "
          ."LEFT JOIN Personal_Funktionen pf ON pf.ID=p.Funktion "
          ."LEFT JOIN Personal_Lehrgänge pl ON pl.Personal=p.ID "
          ."LEFT JOIN Lehrgänge l ON l.ID=pl.Lehrgänge "
          ."WHERE tt.Termine='".$terminID."' "
          ."GROUP BY p.ID ORDER BY tt.Status DESC, p.Kategorie DESC";
    $res = $mysqli->query($qry);

    $status = "";
    $recipients = array();
    $liste = "<h3>Teilnahmeliste für ".$tmrow["aName"]." am ".date("d.m.Y H:i", strtotime($tmrow["Beginn"])).": ".$tmrow["Thema"]."</h3>\n<table border=1>\n";
    $markedCauser = false;
    $liste.= "<tr><th>Name</th><th>Funktionen</th><th>Corona-Unterweisung</th></tr>\n";
    while ($row = $res->fetch_assoc()) {
      if ($status!=$row["Status"]) {
        $status = $row["Status"];
        if ("2" == $status) {
          $liste.= "<tr><th colspan=3>Diensthabende</th></tr>\n";
        } else if ("1" == $status) {
          $liste.= "<tr><th colspan=3>Erlaubte Teilnehmer</th></tr>\n";
        } else if ("0" == $status) {
          $liste.= "<tr><th colspan=3>Weitere Interessenten</th></tr>\n";
      } }
      $liste.= "<tr><td>".$row["Nachnamen"].", ".$row["Vornamen"]."</td><td>";
      $ausb = explode(",", $row["lKürzel"]);

      $traits = array();
      if ($row["pfKürzel"]!=null) $traits[] = $row["pfKürzel"];
      if (in_array("KF", $ausb)) $traits[] = "KF";
      if (in_array("MA", $ausb)) $traits[] = "MA";
      if (in_array("AGT", $ausb)) $traits[] = "AGT";
      if (in_array("TH", $ausb)) $traits[] = "TH";
      if (!in_array("TM1", $ausb)) $traits[] = "Ohne TM1";
      if (count($traits)) $liste.= implode(", ", $traits);

      $liste.= "</td><td>".(in_array("CU", $ausb) ? "Ja" : "Nein")."</td></tr>\n";

      if ("2" == $row["Status"]) {
        $recipients[] = $row["Login"]."@feuerwehr-bs.net";
      }
    }
    $liste.= "</table>\n";

    if (!in_array("nils.otterpohl@feuerwehr-bs.net", $recipients))
      $recipients[] = "nils.otterpohl@feuerwehr-bs.net";
    foreach ($recipients as $recipient) {
      emlSendEmail($recipient, "Teilnahmeliste - Dienst ".date("D, den d.m.Y um H:i", strtotime($tmrow["Beginn"])), $liste);
    }

    return $liste;
  }
  return "";
}

// 


































// mysql_con mysqli
// string subject
// string text
// int notificationLvl : {1: Neuer Thread, 2: Neue Nachricht}
// string neededRecipientRight
/*function emlSendNotification($mysqli, $sendUser, $subject, $text, $notificationLvl, $neededRecipientRight = null) {
  global $mail;
  
  $mail->setFrom(MAILNOREPLY, "Sophia und Nils Hochzeitswebsite");
  $mail->isHTML(false);
  $mail->Subject = $subject;
  $to_tpl = tplExtrSection($text, "###TO###");
  
  $qry = "SELECT DISTINCT u.email, u.groupID FROM users u "
        .($neededRecipientRight!==null ? "LEFT JOIN rolerights rr ON rr.roleID=u.roleID LEFT JOIN rights r ON r.ID=rr.rightID " : "")
        ."WHERE u.ID!=".$sendUser." AND u.notifications>=".$notificationLvl." ".($neededRecipientRight!==null ? "AND r.name='".$neededRecipientRight."' " : "");
  $res = $mysqli->query($qry);
  while ($row = $res->fetch_assoc()) {
    $nameres = $mysqli->query("SELECT prenames `###PRENAMES###`, surnames `###SURNAMES###`, addressing `###ADDRESSING###`, IFNULL(nickname, prenames) `###NICKNAME###` "
                             ."FROM guests WHERE companion=0 AND groupID=".$row["groupID"]);
    $to = "";
    while ($namerow = $nameres->fetch_assoc()) {
      $to.= tplReplMarkerArray($to_tpl, $namerow);
    }
    $mail->Body = tplReplSection($text, "###TO###", $to);
    $mail->addAddress($row["email"]);
    $mail->send();
    $mail->clearAddresses();
  }
}*/

// Sendet eine Mail an ALLE User (die nicht abgesagt haben)
// mysql_con mysqli
// int sendUser
// string from
// string subject
// string text
// string neededRecipientRight
/*function emlSendMassMail($mysqli, $sendUser, $from, $subject, $text, $neededRecipientRight = null) {
  global $mail;
  
  if (!$res = $mysqli->query("SELECT DISTINCT IFNULL(u.eMailFrom, u.email) email FROM users u WHERE u.ID=".$sendUser))
    addError("Mysql", $mysqli->error);
  $from_mail = $res->fetch_assoc()["email"];
  $mail->setFrom($from_mail, $from);
  
  $mail->isHTML(true);
  $mail->Subject = $subject;
  $to_tpl = tplExtrSection($text, "###TO###");
  
  $qry = "SELECT DISTINCT u.email, u.groupID FROM guests g LEFT JOIN users u ON u.groupID=g.groupID "
        .($neededRecipientRight!==null ? "LEFT JOIN rolerights rr ON rr.roleID=u.roleID LEFT JOIN rights r ON r.ID=rr.rightID " : "")
        ."WHERE u.ID!=".$sendUser." AND IFNULL(g.comes, 99)!=0 ".($neededRecipientRight!==null ? "AND r.name='".$neededRecipientRight."' " : "");
  $res = $mysqli->query($qry);
  while ($row = $res->fetch_assoc()) {
    $tores = $mysqli->query("SELECT prenames `###PRENAMES###`, surnames `###SURNAMES###`, addressing `###ADDRESSING###`, IFNULL(nickname, prenames) `###NICKNAME###` "
                           ."FROM guests WHERE companion=0 AND groupID=".$row["groupID"]);
    $to = "";
    while ($torow = $tores->fetch_assoc()) {
      $to.= tplReplMarkerArray($to_tpl, $torow);
    }
    $mail->Body = tplReplSection($text, "###TO###", $to);
    $mail->addAddress($row["email"]);
    $mail->send();
    $mail->clearAddresses();
  }
}*/

// Sendet eine Mail an EINEN User
// mysql_con mysqli
// int targetUser
// string subject
// string text
/*function emlSendSingleMail($mysqli, $targetUser, $subject, $text) {
  global $mail;
  $ret = false;
  
  $targetMail = null;
  $groupID = null;
  if ($stmt = $mysqli->prepare("SELECT email, groupID FROM users u WHERE u.ID = ?")) {
    $stmt->bind_param("i", $targetUser);
    $stmt->execute();
    $stmt->bind_result($targetMail, $groupID);
    $stmt->fetch();
    $stmt->close();
  } else {
    addError("Mysql", $mysqli->error);
  }
  if ($targetMail!=null && $groupID!=null) {
    $mail->setFrom(MAILNOREPLY, "Sophia und Nils Hochzeitswebsite");
    
    $mail->isHTML(true);
    $mail->Subject = $subject;
    $to_tpl = tplExtrSection($text, "###TO###");
    
    $tores = $mysqli->query("SELECT prenames `###PRENAMES###`, surnames `###SURNAMES###`, addressing `###ADDRESSING###`, IFNULL(nickname, prenames) `###NICKNAME###` "
                             ."FROM guests WHERE companion=0 AND groupID=".$groupID);
    $to = "";
    while ($torow = $tores->fetch_assoc()) {
      $to.= tplReplMarkerArray($to_tpl, $torow);
    }
    $mail->Body = tplReplSection($text, "###TO###", $to);
    $mail->addAddress($targetMail);
    $mail->send();
    $mail->clearAddresses();
    $ret = true;
  }
  return $ret;
}*/
