$extraHeaders */ function mail_send(string $to, string $subject, string $body, array $extraHeaders = []): bool { if (!filter_var($to, FILTER_VALIDATE_EMAIL)) { return false; } $headers = [ 'From: ' . (string) config('app.mail_from', 'Drink it cold '), 'MIME-Version: 1.0', 'Content-Type: text/plain; charset=UTF-8', 'Content-Transfer-Encoding: 8bit', ]; foreach ($extraHeaders as $header) { $clean = trim(preg_replace('/[\r\n]+/', ' ', $header) ?? ''); if ($clean !== '') { $headers[] = $clean; } } return @mail( $to, mb_encode_mimeheader($subject, 'UTF-8', 'B'), $body, implode("\r\n", $headers) ); } /** * Verschickt eine Textnachricht mit einem Dateianhang (multipart/mixed). * * Gedacht für Buchungsunterlagen (Mietvertrag, Auftragsbestätigung, Rechnung). * Der Anhang wird Base64-kodiert; Dateiname und MIME-Typ kommen vom Aufrufer. */ function mail_send_attachment( string $to, string $subject, string $body, string $fileName, string $mimeType, string $data ): bool { if (!filter_var($to, FILTER_VALIDATE_EMAIL) || $data === '') { return false; } $safeName = trim((string) preg_replace('/[\r\n"]+/', '', $fileName)); $safeType = trim((string) preg_replace('/[\r\n]+/', '', $mimeType)); $boundary = 'dic-' . bin2hex(random_bytes(12)); $headers = [ 'From: ' . (string) config('app.mail_from', 'Drink it cold '), 'MIME-Version: 1.0', 'Content-Type: multipart/mixed; boundary="' . $boundary . '"', ]; $parts = [ '--' . $boundary, 'Content-Type: text/plain; charset=UTF-8', 'Content-Transfer-Encoding: 8bit', '', $body, '--' . $boundary, 'Content-Type: ' . $safeType . '; name="' . $safeName . '"', 'Content-Transfer-Encoding: base64', 'Content-Disposition: attachment; filename="' . $safeName . '"', '', chunk_split(base64_encode($data), 76, "\r\n"), '--' . $boundary . '--', ]; return @mail( $to, mb_encode_mimeheader($subject, 'UTF-8', 'B'), implode("\r\n", $parts), implode("\r\n", $headers) ); } function reminder_mail_recipients(): array { $sql = "SELECT u.employee_id, u.email, u.first_name, u.last_name, e.name AS employee_name FROM users u JOIN employees e ON e.id = u.employee_id WHERE u.status = 'active' AND u.employee_id IS NOT NULL AND u.email IS NOT NULL AND u.email <> '' ORDER BY e.sort_order"; $out = []; foreach (db()->query($sql)->fetchAll() as $row) { $out[(int) $row['employee_id']] = $row; } return $out; } /** * Verschickt alle offenen, heute (oder in den letzten 7 Tagen) fälligen * Erinnerungen als einen Digest pro Mitarbeiter. * * @return array{enabled: bool, sent: int, skipped: int, errors: array, details: array} */ function reminder_send_due(int $lookbackDays = 7): array { $result = ['enabled' => mail_is_enabled(), 'sent' => 0, 'skipped' => 0, 'errors' => [], 'details' => []]; if (!$result['enabled']) { return $result; } $today = today_iso(); $from = add_days($today, -max(1, $lookbackDays)); $recipients = reminder_mail_recipients(); $rows = reminder_list($from, $today, 0, false, REMINDER_SEND_MIN_AGE_MINUTES); if (!$rows) { return $result; } $byEmployee = []; foreach ($rows as $row) { // Rücknahme-Erinnerungen gehören ggf. dem abweichend zugewiesenen Mitarbeiter. $employeeId = booking_employee_for_kind($row['booking'], (string) $row['kind']); if (!isset($recipients[$employeeId])) { $result['skipped']++; continue; } // Bereits verschickt? $stmt = db()->prepare('SELECT 1 FROM reminder_mail_log WHERE booking_id = ? AND kind = ? AND due_date = ?'); $stmt->execute([(int) $row['booking']['id'], $row['kind'], $row['due_date']]); if ($stmt->fetchColumn()) { $result['skipped']++; continue; } $byEmployee[$employeeId][] = $row; } $appUrl = rtrim((string) config('app.public_url', ''), '/'); foreach ($byEmployee as $employeeId => $items) { $recipient = $recipients[$employeeId]; $lines = [ 'Guten Tag ' . $recipient['employee_name'] . ',', '', 'diese Erinnerungen stehen an:', '', ]; foreach ($items as $item) { $booking = $item['booking']; $lines[] = '• ' . fmt_date($item['due_date']) . ' – ' . $item['label']; $lines[] = ' ' . $item['message']; $lines[] = ' ' . $booking['customer_name'] . ', ' . $booking['trailer_label'] . ' (' . $booking['trailer_color_name'] . ')'; $lines[] = ' Miete: ' . fmt_date($booking['start_date']) . ' bis ' . fmt_date($booking['end_date']); if ($appUrl !== '') { $lines[] = ' ' . $appUrl . '/bookings/' . (int) $booking['id']; } $lines[] = ''; } $lines[] = 'Diese Nachricht wurde automatisch von der Terminplanung erzeugt.'; $body = implode("\n", $lines); $subject = 'Drink it cold – ' . count($items) . ' fällige Erinnerung' . (count($items) === 1 ? '' : 'en'); $ok = mail_send((string) $recipient['email'], $subject, $body); if (!$ok) { $result['errors'][] = 'Versand an ' . $recipient['email'] . ' fehlgeschlagen.'; continue; } $log = db()->prepare( 'INSERT IGNORE INTO reminder_mail_log (booking_id, kind, due_date, employee_id, sent_to, sent_at) VALUES (?, ?, ?, ?, ?, ?)' ); foreach ($items as $item) { $log->execute([ (int) $item['booking']['id'], $item['kind'], $item['due_date'], $employeeId, (string) $recipient['email'], utc_now(), ]); $result['sent']++; } $result['details'][] = $recipient['email'] . ' (' . count($items) . ')'; } return $result; } /** * Automatische Zahlungserinnerung an Kunden, die die Restzahlung per * Überweisung zahlen: transfer_reminder_days() Tage vor Mietbeginn wird die * Zahlungserinnerung erzeugt und als PDF gemailt. Ein Nachlauf von * $lookbackDays Tagen holt Termine nach, falls der Cron pausiert war. * * @return array{enabled: bool, sent: int, skipped: int, errors: array, details: array} */ function payment_reminder_send_due(int $lookbackDays = 7): array { $result = ['enabled' => mail_is_enabled(), 'sent' => 0, 'skipped' => 0, 'errors' => [], 'details' => []]; if (!$result['enabled'] || !documents_schema_ready()) { return $result; } $today = today_iso(); $until = add_days($today, transfer_reminder_days()); $from = add_days($today, -max(1, $lookbackDays)); try { // Migration 019 muss gelaufen sein, sonst bleibt der Lauf ohne Fehler. $column = db()->query("SHOW COLUMNS FROM bookings LIKE 'balance_method'"); if ($column === false || $column->fetchColumn() === false) { $result['errors'][] = 'Migration 019_balance_method.sql fehlt – Restzahlung per Überweisung wird noch nicht ausgewertet.'; return $result; } $stmt = db()->prepare( "SELECT id FROM bookings WHERE balance_method = 'transfer' AND status <> 'cancelled' AND start_date >= ? AND start_date <= ? ORDER BY start_date, id" ); $stmt->execute([$from, $until]); $ids = array_map('intval', $stmt->fetchAll(PDO::FETCH_COLUMN)); } catch (Throwable $error) { $result['errors'][] = 'Zahlungserinnerungen nicht lesbar: ' . $error->getMessage(); return $result; } foreach ($ids as $id) { $booking = booking_find($id); if (!$booking) { $result['skipped']++; continue; } $to = trim((string) ($booking['email'] ?? '')); if (!filter_var($to, FILTER_VALIDATE_EMAIL)) { $result['skipped']++; continue; } if (document_reminder_amounts($booking)['open'] <= 0) { $result['skipped']++; continue; } // Ein Versand pro Termin: verschiebt sich der Mietbeginn, gibt es einen // neuen Schlüssel und damit eine neue Erinnerung. $dueDate = add_days((string) $booking['start_date'], -transfer_reminder_days()); $check = db()->prepare('SELECT 1 FROM payment_reminder_log WHERE booking_id = ? AND due_date = ?'); $check->execute([$id, $dueDate]); if ($check->fetchColumn()) { $result['skipped']++; continue; } // Schon manuell gemailt? Dann keine zweite Erinnerung hinterherschicken. $manual = db()->prepare( "SELECT 1 FROM booking_documents WHERE booking_id = ? AND kind = 'reminder' AND mailed_at IS NOT NULL AND mailed_at >= ?" ); $manual->execute([$id, $dueDate . ' 00:00:00']); if ($manual->fetchColumn()) { $result['skipped']++; continue; } try { $doc = document_create($booking, DOCUMENT_KIND_REMINDER, '', null); if (!document_mail_to_customer($booking, $doc)) { $result['errors'][] = 'Zahlungserinnerung an ' . $to . ' konnte nicht versendet werden (Buchung #' . $id . ').'; continue; } db()->prepare( 'INSERT IGNORE INTO payment_reminder_log (booking_id, due_date, sent_to, sent_at) VALUES (?, ?, ?, ?)' )->execute([$id, $dueDate, $to, utc_now()]); $result['sent']++; $result['details'][] = 'Buchung #' . $id . ' → ' . $to; } catch (Throwable $error) { $result['errors'][] = 'Buchung #' . $id . ': ' . $error->getMessage(); } } return $result; } /* ------------------------------------------------------- Bewertungsmail */ /** Vorlauf der Bewertungsmail nach der Rückgabe in Tagen. */ function review_mail_days(): int { return max(1, min(120, (int) config('app.review_mail_days', 7))); } /** Link zur Google-Bewertung (config app.review_url). */ function review_mail_url(): string { $url = trim((string) config('app.review_url', '')); return $url !== '' ? $url : 'https://g.co/kgs/eBcVxRZ'; } /** * Automatische Bewertungsmail ein paar Tage nach der Rückgabe. * * Der Kunde hat diese Mail bisher manuell verschickt. Jede Buchung bekommt sie * genau einmal (Protokoll review_mail_log, Migration 022); ein Nachlauf von * $lookbackDays Tagen holt Termine nach, falls der Cron pausiert war. * * @return array{enabled: bool, sent: int, skipped: int, errors: array, details: array} */ function review_mail_send_due(int $lookbackDays = 7): array { $result = ['enabled' => mail_is_enabled(), 'sent' => 0, 'skipped' => 0, 'errors' => [], 'details' => []]; if (!$result['enabled']) { return $result; } try { $table = db()->query("SHOW TABLES LIKE 'review_mail_log'"); if ($table === false || $table->fetchColumn() === false) { $result['errors'][] = 'Migration 022_review_mail_log.sql fehlt – Bewertungsmails werden nicht verschickt.'; return $result; } $due = add_days(today_iso(), -review_mail_days()); $from = add_days($due, -max(1, $lookbackDays)); $stmt = db()->prepare( "SELECT id FROM bookings WHERE status <> 'cancelled' AND end_date >= ? AND end_date <= ? ORDER BY end_date, id" ); $stmt->execute([$from, $due]); $ids = array_map('intval', $stmt->fetchAll(PDO::FETCH_COLUMN)); } catch (Throwable $error) { $result['errors'][] = 'Bewertungsmails nicht lesbar: ' . $error->getMessage(); return $result; } $legal = legal_data(); $link = review_mail_url(); foreach ($ids as $id) { $booking = booking_find($id); if (!$booking) { $result['skipped']++; continue; } $to = trim((string) ($booking['email'] ?? '')); if (!filter_var($to, FILTER_VALIDATE_EMAIL)) { $result['skipped']++; continue; } $check = db()->prepare('SELECT 1 FROM review_mail_log WHERE booking_id = ?'); $check->execute([$id]); if ($check->fetchColumn()) { $result['skipped']++; continue; } $subject = 'Ihre Meinung ist uns wichtig – Drink it cold'; $body = 'Guten Tag ' . (string) $booking['customer_name'] . ",\n\n" . "vielen Dank, dass Sie bei Drink it cold einen Kühlanhänger / eine Truhe gemietet haben.\n" . "Wir hoffen, dass Sie mit unserem Service rundum zufrieden waren.\n\n" . "Es würde uns sehr freuen, wenn Sie sich einen kurzen Moment Zeit nehmen und Ihre Erfahrung mit uns " . "auf Google teilen würden. Ihre Bewertung hilft nicht nur uns, sondern auch zukünftigen Kunden bei " . "ihrer Entscheidung.\n\n" . "Hier bewerten: " . $link . "\n\n" . "Ebenso würden wir uns freuen, Sie auch in Zukunft bei Bedarf wieder als Kunden begrüßen zu dürfen.\n" . "Vielen Dank für Ihre Unterstützung!\n\n" . 'Ihr ' . (string) $legal['business_name'] . "-Team\n\n" . mail_auto_hint(); try { if (!mail_send($to, $subject, $body)) { $result['errors'][] = 'Bewertungsmail an ' . $to . ' konnte nicht versendet werden (Buchung #' . $id . ').'; continue; } db()->prepare('INSERT IGNORE INTO review_mail_log (booking_id, sent_to, sent_at) VALUES (?, ?, ?)') ->execute([$id, $to, utc_now()]); $result['sent']++; $result['details'][] = 'Buchung #' . $id . ' → ' . $to; } catch (Throwable $error) { $result['errors'][] = 'Buchung #' . $id . ': ' . $error->getMessage(); } } return $result; }