Files
intranet/web/intranet_repo/projects/seelsorge/toggle_availability.php
T

119 lines
4.8 KiB
PHP

<?php
/* Name: toggle_availability.php
Beschreibung: Verfuegbarkeit eintragen/entfernen (AJAX-Endpoint)
Liefert JSON-Response, sendet SMS+Mail bei Match */
header('Content-Type: application/json; charset=utf-8');
session_start();
if (!isset($_SESSION["user_id"]) || !isset($_POST["date"])) {
http_response_code(400);
echo json_encode(['ok' => false, 'error' => 'Fehlende Parameter']);
exit;
}
$date = $_POST["date"];
$formattedDate = date("d.m.Y", strtotime($date));
$userId = (int) $_SESSION["user_id"];
$pdo = require($_SERVER['DOCUMENT_ROOT'] . "/intranet_repo/general_files/ini/database.php");
// Pruefen ob Verfuegbarkeit bereits besteht
$stmt = $pdo->prepare("SELECT COUNT(*) AS count FROM verfuegbarkeiten WHERE datum = ? AND user_id = ?");
$stmt->execute([$date, $userId]);
$wasAvailable = $stmt->fetch()['count'] > 0;
// Eintragen oder Austragen
if ($wasAvailable) {
$stmt = $pdo->prepare("DELETE FROM verfuegbarkeiten WHERE datum = ? AND user_id = ?");
} else {
$stmt = $pdo->prepare("INSERT INTO verfuegbarkeiten (datum, user_id) VALUES (?, ?)");
}
if (!$stmt->execute([$date, $userId])) {
http_response_code(500);
echo json_encode(['ok' => false, 'error' => 'Datenbankfehler']);
$pdo = null;
exit;
}
$nowAvailable = !$wasAvailable;
$notifications = [];
// Bei neuem Eintrag: Match pruefen und benachrichtigen
if ($nowAvailable) {
// E-Mail-Spalte dynamisch ermitteln
$emailCol = null;
$emailCandidates = ['email', 'mail', 'email_address', 'e_mail', 'user_email'];
$inList = "'" . implode("','", $emailCandidates) . "'";
$res = $pdo->query("SELECT column_name FROM information_schema.columns WHERE table_name = 'user_general_information' AND column_name IN ($inList) LIMIT 1");
if ($res && $r = $res->fetch()) { $emailCol = $r['column_name']; }
$emailSelect = $emailCol ? ", u.\"{$emailCol}\" AS email" : ", '' AS email";
$sql = "SELECT u.user_id, u.first_name, u.last_name, u.phone{$emailSelect}
FROM verfuegbarkeiten v
JOIN user_general_information u ON v.user_id = u.user_id
WHERE v.datum = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$date]);
$matchUsers = $stmt->fetchAll();
if (count($matchUsers) > 1) {
$nameList = implode(', ', array_map(fn($u) => trim($u['first_name'] . ' ' . $u['last_name']), $matchUsers));
$smsText = mb_convert_encoding(
"Intranet NAK Reinickendorf\n\nIt's a match!\n\n{$nameList} haben am {$formattedDate} fuer einen Seelsorgebesuch Zeit!",
'UTF-8', 'auto'
);
// SMS an alle Beteiligten
foreach ($matchUsers as $u) {
if (!empty($u['phone'])) {
$smsData = json_encode([
'phone' => '+49' . $u['phone'],
'message' => $smsText
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$ctx = stream_context_create(['http' => [
'header' => "Content-Type: application/json; charset=utf-8",
'method' => 'POST',
'content' => $smsData,
'timeout' => 5
]]);
@file_get_contents(rtrim(intranet_env('SMS_GATEWAY_URL'), '/') . '/send_sms', false, $ctx);
$notifications[] = "SMS → " . $u['first_name'];
}
}
// E-Mail an alle Beteiligten
require_once $_SERVER['DOCUMENT_ROOT'] . '/intranet_repo/general_files/ini/send_mail.php';
$mailBetreff = "Seelsorge-Match am {$formattedDate}";
$mailNachricht = "It's a match!\n\n{$nameList} haben am {$formattedDate} für einen Seelsorgebesuch Zeit.\n\nBitte stimmt euch untereinander ab.";
$host = $_SERVER['HTTP_HOST'] ?? intranet_env('INTRANET_FQDN');
$btnUrl = "https://{$host}/intranet_repo/projects/seelsorge/seelsorge.php";
foreach ($matchUsers as $u) {
$email = trim($u['email'] ?? '');
if (!empty($email) && filter_var($email, FILTER_VALIDATE_EMAIL)) {
@send_intranet_mail($email, $mailBetreff, $mailNachricht, null, 'intranet@nak-reinickendorf.de', 'Zum Seelsorgeplaner', $btnUrl);
$notifications[] = "Mail → " . $u['first_name'];
}
}
}
}
// Aktuellen Count der verfuegbaren Diakon*innen fuer diesen Tag zurueckgeben
$stmt = $pdo->prepare("SELECT COUNT(*) AS cnt FROM verfuegbarkeiten WHERE datum = ?");
$stmt->execute([$date]);
$availCount = $stmt->fetch()['cnt'];
$pdo = null;
echo json_encode([
'ok' => true,
'nowAvailable' => $nowAvailable,
'availCount' => (int) $availCount,
'notifications' => $notifications
], JSON_UNESCAPED_UNICODE);
?>