/ abgelegt und * nur über eine angemeldete Route ausgeliefert (der storage-Ordner ist per * .htaccess gesperrt). Mietvertrag und Auftragsbestätigung erzeugt die App * selbst (app/pdf.php), die Rechnung lädt der Admin als PDF aus Lexware hoch. * * Mietvertrag-Varianten: Lieferung, Selbstabholer, Truhe. Die Variante ergibt * sich aus der Buchung (Truhe = Anhängername beginnt mit "Truhe", sonst * Lieferung/Abholung) und lässt sich beim Erzeugen überschreiben. * * Aufbewahrung: einen Monat nach Mietende löscht privacy_cleanup() die Dateien * (app.document_retention_days, Standard 30 Tage). */ const DOCUMENT_KIND_CONTRACT = 'contract'; const DOCUMENT_KIND_CONFIRMATION = 'confirmation'; const DOCUMENT_KIND_INVOICE = 'invoice'; /** @return array */ function document_kinds(): array { return [ DOCUMENT_KIND_CONTRACT => 'Mietvertrag', DOCUMENT_KIND_CONFIRMATION => 'Auftragsbestätigung', DOCUMENT_KIND_INVOICE => 'Rechnung', ]; } function document_kind_label(string $kind): string { return document_kinds()[$kind] ?? $kind; } /** @return array */ function document_variants(): array { return [ 'delivery' => 'Mit Lieferung', 'pickup' => 'Selbstabholer', 'chest' => 'Truhe', ]; } function document_variant_label(string $variant): string { return document_variants()[$variant] ?? 'Mit Lieferung'; } /** Passende Variante zur Buchung (Truhe, Lieferung oder Selbstabholer). */ function document_variant_default(array $booking): string { $label = (string) ($booking['trailer_label'] ?? ''); if ($label !== '' && mb_stripos(trim($label), 'truhe') === 0) { return 'chest'; } return (string) ($booking['kind'] ?? 'pickup') === 'delivery' ? 'delivery' : 'pickup'; } /** * Variantentexte, in app/config.local.php unter `documents` überschreibbar: * * 'documents' => ['delivery' => ['hint' => '…', 'accessories' => ['…']], …] */ function document_texts(string $variant): array { $defaults = [ 'delivery' => [ 'subject' => 'Kühlanhänger', 'hint' => 'Wichtig zu beachten ist, dass der Kühlanhänger nicht mit einem Stromaggregat ' . 'betrieben werden darf. Der Anhänger ist stets gegen Wegrollen und Diebstahl zu sichern.', 'accessories' => ['3 Schlüssel', '1 Stromkabel (15 m)', '2 Diebstahlsicherungen (Kupplung & Kralle)'], 'pickup_fields' => false, ], 'pickup' => [ 'subject' => 'Kühlanhänger', 'hint' => 'Wichtig zu beachten ist, dass der Kühlanhänger nicht mit einem Stromaggregat ' . 'betrieben werden darf. Der Anhänger ist stets gegen Wegrollen und Diebstahl zu sichern.', 'accessories' => ['3 Schlüssel', '1 Stromkabel (15 m)', '2 Diebstahlsicherungen (Kupplung & Kralle)'], 'pickup_fields' => true, ], 'chest' => [ 'subject' => 'Kühltruhe', 'hint' => 'Wichtig zu beachten ist, dass die Kühltruhe nicht mit einem Stromaggregat betrieben ' . 'werden darf und nur an einer geerdeten Steckdose angeschlossen wird.', 'accessories' => ['1 Stromkabel (15 m)'], 'pickup_fields' => true, ], ]; $variant = array_key_exists($variant, $defaults) ? $variant : 'delivery'; $merged = $defaults[$variant]; $configured = config('documents.' . $variant, []); if (is_array($configured)) { foreach ($configured as $key => $value) { if (is_string($key) && (is_string($value) || is_array($value) || is_bool($value))) { $merged[$key] = $value; } } } $merged['accessories'] = array_values(array_map('strval', (array) ($merged['accessories'] ?? []))); return $merged; } /* --------------------------------------------------------------- Speicher */ /** * Ist die Tabelle für Buchungsunterlagen vorhanden? Solange die Migration * (012_booking_documents.sql) nicht gelaufen ist, bleiben Buchungsseite und * Cron sonst mit einem SQL-Fehler stehen. */ function documents_schema_ready(): bool { static $ready = null; if ($ready !== null) { return $ready; } try { $stmt = db()->query("SHOW TABLES LIKE 'booking_documents'"); $ready = $stmt !== false && $stmt->fetchColumn() !== false; } catch (Throwable) { $ready = false; } return $ready; } function document_store_root(): string { $storage = rtrim((string) config('app.storage_path', DIC_ROOT . '/storage'), '/'); return $storage . '/documents'; } function document_booking_dir(int $bookingId, bool $create = false): string { $dir = document_store_root() . '/' . $bookingId; if ($create && !is_dir($dir)) { @mkdir($dir, 0775, true); } return $dir; } /** @return list> */ function documents_for_booking(int $bookingId): array { if (!documents_schema_ready()) { return []; } $stmt = db()->prepare('SELECT * FROM booking_documents WHERE booking_id = ? ORDER BY created_at DESC, id DESC'); $stmt->execute([$bookingId]); return $stmt->fetchAll(); } function document_find(int $id): ?array { if (!documents_schema_ready()) { return null; } $stmt = db()->prepare('SELECT * FROM booking_documents WHERE id = ? LIMIT 1'); $stmt->execute([$id]); $row = $stmt->fetch(); return $row ?: null; } function document_path(array $doc): string { return document_store_root() . '/' . (int) $doc['booking_id'] . '/' . (string) $doc['stored_file']; } function document_signature_path(array $doc): ?string { $file = trim((string) ($doc['signature_file'] ?? '')); if ($file === '') { return null; } $path = document_store_root() . '/' . (int) $doc['booking_id'] . '/' . $file; return is_file($path) ? $path : null; } function document_file_name(string $kind, string $variant, array $booking): string { $prefix = $kind === DOCUMENT_KIND_CONTRACT ? 'Mietvertrag' : 'Auftragsbestaetigung'; $parts = [$prefix]; if ($variant !== '') { $parts[] = document_variant_label($variant); } $parts[] = (string) $booking['customer_name']; $parts[] = (string) $booking['start_date']; $name = implode(' ', $parts); $name = (string) preg_replace('/[^A-Za-z0-9äöüÄÖÜß ._-]+/u', '', $name); $name = trim((string) preg_replace('/\s+/', ' ', $name)); return mb_substr($name === '' ? $prefix : $name, 0, 120) . '.pdf'; } /* ------------------------------------------------------------ Erzeugen */ /** * Legt ein Dokument an bzw. erneuert es, wenn es dieselbe Art und Variante * bereits gibt (dann bleibt die Unterschrift erhalten). */ function document_create(array $booking, string $kind, string $variant, ?int $userId): array { if (!array_key_exists($kind, document_kinds()) || $kind === DOCUMENT_KIND_INVOICE) { throw new RuntimeException('Diese Unterlagen-Art wird nicht erzeugt.'); } if (!documents_schema_ready()) { throw new RuntimeException('Die Tabelle für Unterlagen fehlt noch. Bitte zuerst /migrate mit dem Cron-Token aufrufen.'); } if (!array_key_exists($variant, document_variants())) { $variant = document_variant_default($booking); } foreach (documents_for_booking((int) $booking['id']) as $doc) { if ($doc['kind'] === $kind && $doc['variant'] === $variant && $doc['source'] === 'generated') { return document_regenerate($booking, $doc); } } $dir = document_booking_dir((int) $booking['id'], true); $token = bin2hex(random_bytes(8)); $stored = $token . '.pdf'; $bytes = document_render($booking, $kind, $variant, null, null); if (@file_put_contents($dir . '/' . $stored, $bytes) === false) { throw new RuntimeException('Unterlage konnte nicht gespeichert werden.'); } $stmt = db()->prepare( 'INSERT INTO booking_documents (booking_id, kind, variant, file_name, stored_file, mime_type, size_bytes, source, created_at, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)' ); $stmt->execute([ (int) $booking['id'], $kind, $variant, document_file_name($kind, $variant, $booking), $stored, 'application/pdf', strlen($bytes), 'generated', utc_now(), $userId, ]); return document_find((int) db()->lastInsertId()) ?? []; } /** Erzeugt das PDF einer vorhandenen Unterlage neu (z. B. nach dem Unterschreiben). */ function document_regenerate(array $booking, array $doc): array { $kind = (string) $doc['kind']; if ($kind === DOCUMENT_KIND_INVOICE) { return $doc; } $variant = (string) ($doc['variant'] ?: document_variant_default($booking)); $bytes = document_render( $booking, $kind, $variant, document_signature_path($doc), $doc['signed_at'] !== null ? (string) $doc['signed_at'] : null, trim((string) ($doc['signed_via'] ?? '')) !== '' ? (string) $doc['signed_via'] : null ); $path = document_path($doc); document_booking_dir((int) $doc['booking_id'], true); if (@file_put_contents($path, $bytes) === false) { throw new RuntimeException('Unterlage konnte nicht gespeichert werden.'); } db()->prepare('UPDATE booking_documents SET size_bytes = ?, file_name = ? WHERE id = ?') ->execute([strlen($bytes), document_file_name($kind, $variant, $booking), (int) $doc['id']]); return document_find((int) $doc['id']) ?? $doc; } function document_render( array $booking, string $kind, string $variant, ?string $signatureFile, ?string $signedAt, ?string $signedVia = null ): string { return $kind === DOCUMENT_KIND_CONFIRMATION ? document_confirmation_pdf($booking, $variant) : document_contract_pdf($booking, $variant, $signatureFile, $signedAt, $signedVia); } /* ----------------------------------------------------------- PDF-Aufbau */ function document_pdf_footer(PdfDoc $pdf, string $label): void { $w = $pdf->pageWidth(); $h = $pdf->pageHeight(); $pdf->line(50, $h - 52, $w - 50, $h - 52, 0.5); $pdf->text(50, $h - 38, 7.5, $label); $pdf->text(50, $h - 38, 7.5, 'Seite ' . $pdf->pageNo(), false, 'right', $w - 100); } /** * Logo-Datei für die PDF-Kopfzeile (PNG mit Transparenz) oder null. * * Im Repository liegen die Assets unter web/assets/…, auf dem Hosting ist der * Inhalt von web/ der DocumentRoot – deshalb beide Pfade prüfen. */ function document_logo_path(): ?string { $candidates = [ '/web/assets/img/logo-drink-it-cold-480.png', '/assets/img/logo-drink-it-cold-480.png', '/web/assets/img/logo-drink-it-cold.png', '/assets/img/logo-drink-it-cold.png', ]; foreach ($candidates as $candidate) { if (is_file(DIC_ROOT . $candidate)) { return DIC_ROOT . $candidate; } } error_log('Dokument: Logo fehlt (gesucht in ' . implode(', ', $candidates) . ' unter ' . DIC_ROOT . ').'); return null; } /** Kopfzeile: Logo oben rechts, Titel links, Kennung rechts über der Linie. */ function document_pdf_title(PdfDoc $pdf, string $title, string $right): void { $w = $pdf->pageWidth(); $logo = document_logo_path(); if ($logo !== null) { // Seitenverhältnis des Logos 480:267 – Breite 54 pt, Höhe passend. $pdf->image($logo, $w - 50 - 54.0, 22.0, 54.0, 30.0); } $pdf->text(50, 66, 20, $title, true); $pdf->text(50, 66, 8.5, $right, false, 'right', $w - 100); $pdf->line(50, 76, $w - 50, 76, 1.0); } /** * Zwei Adressblöcke nebeneinander: links der Kunde (Mieter), rechts der Vermieter. */ function document_pdf_parties(PdfDoc $pdf, float $top, array $booking): float { $legal = legal_data(); $owner = trim((string) ($legal['owner'] ?? '')) !== '' ? (string) $legal['owner'] : (string) $legal['business_name']; $left = 50.0; $right = 310.0; $pdf->text($left, $top, 7.5, 'MIETER', true); $pdf->text($right, $top, 7.5, 'VERMIETER', true); $y = $top + 14; // Lange Firmennamen umbrechen, damit sie nicht in die rechte Spalte laufen. $nameLines = $pdf->wrap((string) $booking['customer_name'], 11, $right - $left - 24, true); $ownerLines = $pdf->wrap($owner, 11, $pdf->pageWidth() - 50 - $right, true); foreach ($nameLines as $i => $line) { $pdf->text($left, $y + $i * 13, 11, $line, true); } foreach ($ownerLines as $i => $line) { $pdf->text($right, $y + $i * 13, 11, $line, true); } $y += (max(count($nameLines), count($ownerLines)) - 1) * 13; $pdf->text($right, $y + 13, 9.5, (string) $legal['business_name']); $customer = array_values(array_filter([ (string) $booking['street'], (string) $booking['city'], trim((string) $booking['mobile']) !== '' ? 'Tel. ' . (string) $booking['mobile'] : '', (string) $booking['email'], ], static fn (string $v): bool => $v !== '')); $landlord = array_values(array_filter([ (string) $legal['street'], trim((string) $legal['postal_code'] . ' ' . $legal['city']), 'Tel. ' . (string) $legal['phone'], (string) $legal['email'], trim((string) ($legal['vat_id'] ?? '')) !== '' ? 'USt-IdNr. ' . (string) $legal['vat_id'] : '', ], static fn (string $v): bool => $v !== '')); $max = max(count($customer), count($landlord)); for ($i = 0; $i < $max; $i++) { if (isset($customer[$i])) { $pdf->text($left, $y + 29 + $i * 12.5, 9.5, $customer[$i]); } if (isset($landlord[$i])) { $pdf->text($right, $y + 29 + $i * 12.5, 9.5, $landlord[$i]); } } return $y + 29 + $max * 12.5 + 14; } /** Abschnittsüberschrift. */ function document_pdf_heading(PdfDoc $pdf, float $top, string $title): float { $pdf->text(50, $top + 10, 10, $title, true); return $top + 26; } /** * Label/Wert-Zeilen. $rows: Liste aus [label, value] oder [label, value, true] * (fett). Lange Labels und Werte brechen um. Liefert die nächste Grundlinie. */ function document_pdf_rows(PdfDoc $pdf, float $top, array $rows, float $valueX = 200.0): float { $right = $pdf->pageWidth() - 50; $y = $top; foreach ($rows as $row) { $bold = !empty($row[2]); $labelLines = $pdf->wrap((string) $row[0], 9, $valueX - 62, true); $valueLines = $pdf->wrap((string) $row[1], 10, $right - $valueX, $bold); foreach ($labelLines as $i => $line) { $pdf->text(50, $y + $i * 12, 9, $line, true); } foreach ($valueLines as $i => $line) { $pdf->text($valueX, $y + $i * 13, 10, $line, $bold); } $y += max(count($labelLines), count($valueLines)) * 13 + 3; } return $y; } /** * Anzahlungskonten (Verwaltung → Konten), sortiert. * * Der Stamm liegt in der Tabelle deposit_accounts und wird vom Administrator * gepflegt; die Auftragsbestätigung druckt das in der Buchung gewählte Konto. * * @return list */ function deposit_accounts(bool $refresh = false): array { static $cache = null; if ($refresh) { $cache = null; } if (is_array($cache)) { return $cache; } $cache = []; try { $rows = db()->query('SELECT id, label, holder, bank, iban, sort_order FROM deposit_accounts ORDER BY sort_order, id') ->fetchAll(); } catch (Throwable) { return $cache; // Tabelle fehlt noch (Migration ausstehend) } foreach ($rows as $row) { $cache[] = [ 'id' => (int) $row['id'], 'label' => (string) $row['label'], 'holder' => (string) $row['holder'], 'bank' => (string) $row['bank'], 'iban' => (string) $row['iban'], 'sort_order' => (int) $row['sort_order'], ]; } return $cache; } /** Einzelnes Konto; ohne gültige Kennung null. */ function deposit_account(int $id): ?array { foreach (deposit_accounts() as $account) { if ((int) $account['id'] === $id) { return $account; } } return null; } /** Anzeigename inklusive IBAN-Ende, damit zwei Konten unterscheidbar sind. */ function deposit_account_label(array $account): string { $iban = preg_replace('/\s+/', '', (string) $account['iban']) ?? ''; return (string) $account['label'] . ($iban !== '' ? ' (…' . substr($iban, -4) . ')' : ''); } /** Verzeichnis für die hinterlegte Unterschrift des Vermieters. */ function owner_signature_dir(): string { $storage = rtrim((string) config('app.storage_path', DIC_ROOT . '/storage'), '/'); return $storage . '/signature'; } /** Pfad der hinterlegten Unterschrift (JPEG) oder null. */ function owner_signature_path(): ?string { $file = owner_signature_dir() . '/unterschrift-vermieter.jpg'; return is_file($file) ? $file : null; } function owner_signature_time(): ?string { $file = owner_signature_path(); if ($file === null) { return null; } return gmdate('Y-m-d H:i:s', (int) filemtime($file)); } /** * Speichert die im Browser gezeichnete Unterschrift (data:image/jpeg;base64,…). * Gilt für alle neu erzeugten Auftragsbestätigungen. */ function owner_signature_save(string $dataUrl): void { if (!preg_match('#^data:image/jpeg;base64,([A-Za-z0-9+/=\s]+)$#', trim($dataUrl), $match)) { throw new RuntimeException('Die Unterschrift konnte nicht gelesen werden.'); } $binary = base64_decode((string) preg_replace('/\s+/', '', $match[1]), true); if (!is_string($binary) || strlen($binary) < 500 || strncmp($binary, "\xFF\xD8", 2) !== 0) { throw new RuntimeException('Bitte zuerst unterschreiben.'); } if (strlen($binary) > 1500000) { throw new RuntimeException('Die Unterschrift ist zu groß.'); } $dir = owner_signature_dir(); if (!is_dir($dir) && !@mkdir($dir, 0700, true) && !is_dir($dir)) { throw new RuntimeException('Das Verzeichnis für die Unterschrift fehlt.'); } $file = $dir . '/unterschrift-vermieter.jpg'; if (@file_put_contents($file, $binary) === false) { throw new RuntimeException('Die Unterschrift konnte nicht gespeichert werden.'); } @chmod($file, 0600); } function owner_signature_delete(): bool { $file = owner_signature_path(); return $file !== null && @unlink($file); } /** Eingabewerte eines Anzahlungskontos normalisieren. */ function deposit_account_input(array $source): array { return [ 'label' => trim((string) ($source['label'] ?? '')), 'holder' => trim((string) ($source['holder'] ?? '')), 'bank' => trim((string) ($source['bank'] ?? '')), 'iban' => mb_strtoupper(trim((string) ($source['iban'] ?? ''))), 'sort_order' => (int) ($source['sort_order'] ?? 0), ]; } /** @return array */ function deposit_account_validate(array $data): array { $errors = []; if ($data['label'] === '') { $errors['label'] = 'Bitte eine Bezeichnung angeben (z. B. „Postbank – Michael Schmitz“).'; } elseif (mb_strlen($data['label']) > 80) { $errors['label'] = 'Die Bezeichnung ist zu lang (max. 80 Zeichen).'; } if ($data['holder'] === '') { $errors['holder'] = 'Bitte den Kontoinhaber angeben.'; } elseif (mb_strlen($data['holder']) > 120) { $errors['holder'] = 'Der Kontoinhaber ist zu lang (max. 120 Zeichen).'; } if (mb_strlen($data['bank']) > 80) { $errors['bank'] = 'Der Bankname ist zu lang (max. 80 Zeichen).'; } $iban = preg_replace('/\s+/', '', $data['iban']) ?? ''; if ($iban === '') { $errors['iban'] = 'Bitte die IBAN angeben.'; } elseif (mb_strlen($iban) < 15 || mb_strlen($iban) > 34 || preg_match('/^[A-Z]{2}[0-9A-Z]+$/', $iban) !== 1) { $errors['iban'] = 'Die IBAN sieht nicht gültig aus (z. B. DE12 1001 0010 0464 1261 30).'; } return $errors; } function deposit_account_create(array $data): int { $errors = deposit_account_validate($data); if ($errors !== []) { throw new InvalidArgumentException((string) json_encode($errors, JSON_UNESCAPED_UNICODE)); } $stmt = db()->prepare( 'INSERT INTO deposit_accounts (label, holder, bank, iban, sort_order, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)' ); $stmt->execute([ $data['label'], $data['holder'], $data['bank'], $data['iban'], $data['sort_order'], utc_now(), utc_now(), ]); $id = (int) db()->lastInsertId(); // vor dem Neuladen der Liste lesen deposit_accounts(true); return $id; } function deposit_account_update(int $id, array $data): void { $errors = deposit_account_validate($data); if ($errors !== []) { throw new InvalidArgumentException((string) json_encode($errors, JSON_UNESCAPED_UNICODE)); } db()->prepare( 'UPDATE deposit_accounts SET label = ?, holder = ?, bank = ?, iban = ?, sort_order = ?, updated_at = ? WHERE id = ?' )->execute([ $data['label'], $data['holder'], $data['bank'], $data['iban'], $data['sort_order'], utc_now(), $id, ]); deposit_accounts(true); } /** Anzahl der Buchungen, die dieses Konto verwenden. */ function deposit_account_usage(int $id): int { $stmt = db()->prepare('SELECT COUNT(*) FROM bookings WHERE deposit_account_id = ?'); $stmt->execute([$id]); return (int) $stmt->fetchColumn(); } /** Löscht ein Konto – nur solange keine Buchung darauf verweist. */ function deposit_account_delete(int $id): bool { if (deposit_account_usage($id) > 0) { return false; } db()->prepare('DELETE FROM deposit_accounts WHERE id = ?')->execute([$id]); deposit_accounts(true); return true; } /** Frist für die Anzahlung in Werktagen (Mo–Sa, ohne gesetzliche Feiertage). */ function deposit_due_working_days(): int { return max(1, min(60, (int) config('app.deposit_due_working_days', 7))); } /** * Fälligkeitsdatum der Anzahlung: n Werktage ab heute (Mo–Sa, NRW-Feiertage * zählen nicht mit). */ function deposit_due_date(?string $fromIso = null): string { $date = $fromIso !== null && valid_date($fromIso) ? $fromIso : today_iso(); $remaining = deposit_due_working_days(); $guard = 0; $cursor = date_obj($date); while ($remaining > 0 && $guard < 400) { $cursor = $cursor->modify('+1 day'); $guard++; $iso = $cursor->format('Y-m-d'); $weekday = $cursor->format('N'); if ($weekday === '7') { continue; // Sonntag ist kein Werktag } if (holiday_name($iso) !== null) { continue; } $remaining--; } return $cursor->format('Y-m-d'); } /** * Lieferadresse für die Auftragsbestätigung: abweichende Adresse, sonst die * Kundenanschrift (Straße, Ort). */ function document_delivery_address(array $booking): string { $address = trim( trim((string) ($booking['delivery_street'] ?? '')) . ', ' . trim((string) ($booking['delivery_city'] ?? '')), ', ' ); if ($address !== '') { return $address; } $address = trim((string) $booking['street'] . ', ' . (string) $booking['city'], ', '); return $address !== '' ? $address : (string) $booking['city']; } /** * Nur die Gattung des Mietgegenstandes – ohne Anhänger-/Truhennummer. * Für die Auftragsbestätigung: „Kühlanhänger“ oder „Truhe“. */ function document_subject_plain(array $booking): string { $label = (string) ($booking['trailer_label'] ?? ''); return mb_stripos($label, 'truhe') !== false ? 'Truhe' : 'Kühlanhänger'; } /** * Bezeichnung des Mietgegenstandes, ohne doppelte Wörter * ("Kühlanhänger 1", "Kühltruhe 1", "Kühlanhänger: WM Meyer"). */ function document_subject_line(array $booking, array $texts): string { $label = trim((string) ($booking['trailer_label'] ?? '')); $subject = (string) ($texts['subject'] ?? 'Mietgegenstand'); if ($label === '') { return $subject; } if (mb_stripos($label, $subject) !== false) { return $label; } if (mb_stripos($label, 'truhe') === 0) { return 'Kühltruhe' . mb_substr($label, 5); } if (mb_stripos($label, 'anhänger') !== false) { return $label; } return $subject . ': ' . $label; } /** Absatz mit fettem Vorspann in einem hellen Kasten. */ function document_pdf_note(PdfDoc $pdf, float $top, string $title, string $text): float { $w = $pdf->pageWidth() - 100; $lines = $pdf->wrap($text, 9, $w - 20); $height = count($lines) * 12 + 24; $pdf->rect(50, $top, $w, $height, true); $pdf->text(60, $top + 15, 8.5, $title, true); $y = $top + 29; foreach ($lines as $line) { $pdf->text(60, $y, 9, $line); $y += 12; } return $top + $height + 14; } /** * Unterschriftfelder für Mieter und Vermieter. * * $signedVia: tablet (vor Ort übergeben), link (Unterschriftslink des Kunden) * oder null, wenn noch nicht unterschrieben wurde. */ function document_pdf_signatures( PdfDoc $pdf, float $top, array $booking, ?string $signatureFile, ?string $signedAt, ?string $signedVia = null ): void { $legal = legal_data(); $owner = trim((string) ($legal['owner'] ?? '')) !== '' ? (string) $legal['owner'] : (string) $legal['business_name']; $lineLeft = 50.0; $lineRight = 310.0; $lineWidth = 235.0; if ($signatureFile !== null) { $pdf->image($signatureFile, $lineLeft, $top - 52, 150, 50); } $pdf->text($lineRight, $top - 10, 10, $owner . ' · ' . (string) $legal['business_name']); $pdf->line($lineLeft, $top, $lineLeft + $lineWidth, $top, 0.7); $pdf->line($lineRight, $top, $lineRight + $lineWidth, $top, 0.7); $pdf->text($lineLeft, $top + 13, 7.5, 'Datum, Unterschrift Mieter'); $pdf->text($lineRight, $top + 13, 7.5, 'Datum, Unterschrift Vermieter'); if ($signedAt !== null && $signatureFile !== null) { $label = match ($signedVia) { 'tablet' => 'vor Ort auf dem Tablet', 'link' => 'per Unterschriftslink', default => 'digitale Signatur', }; $pdf->text($lineLeft, $top - 6, 8.5, 'Unterschrieben am ' . fmt_datetime($signedAt) . ' (' . $label . ')'); } $pdf->text($lineLeft, $top + 30, 8.5, 'Gesamtbetrag bei Übergabe erhalten: ______________________ €'); $pdf->text($lineLeft, $top + 46, 8.5, 'Kaution bei Rücknahme zurück erhalten: _____________________ €'); } /** Mietvertrag als PDF (Variante Lieferung, Selbstabholer oder Truhe). */ function document_contract_pdf( array $booking, string $variant, ?string $signatureFile, ?string $signedAt, ?string $signedVia = null ): string { $legal = legal_data(); $owner = trim((string) ($legal['owner'] ?? '')) !== '' ? (string) $legal['owner'] : (string) $legal['business_name']; $texts = document_texts($variant); $deposit = max(0, (int) config('app.document_deposit_cents', 10000)); $rent = (int) ($booking['rent_cents'] ?? $booking['total_cents']); $delivery = (int) ($booking['delivery_cents'] ?? 0); $paid = (int) ($booking['deposit_cents'] ?? 0); $total = (int) $booking['total_cents']; $grand = $total + $deposit; $open = $grand - $paid; $pdf = new PdfDoc(); document_pdf_title($pdf, 'Mietvertrag', document_variant_label($variant) . ' · Buchung #' . (int) $booking['id']); $y = document_pdf_parties($pdf, 92, $booking); $period = 'von ' . fmt_date_with_time((string) $booking['start_date'], $booking['start_time'] ?? null) . ' bis ' . fmt_date_with_time((string) $booking['end_date'], $booking['end_time'] ?? null); $y = document_pdf_heading($pdf, $y, 'Mietgegenstand und Mietzeit'); $rows = [['Mietgegenstand', document_subject_line($booking, $texts)]]; if ($variant === 'delivery') { $rows[] = ['Lieferadresse', document_delivery_address($booking)]; } else { $rows[] = ['Abholung', 'Selbstabholung bei ' . $owner . ', ' . $legal['street'] . ', ' . trim((string) $legal['postal_code'] . ' ' . $legal['city'])]; } $rows[] = ['Mietzeitraum', $period]; $y = document_pdf_rows($pdf, $y, $rows); $y = document_pdf_heading($pdf, $y + 8, 'Mietzubehör'); foreach ((array) $texts['accessories'] as $item) { $pdf->text(60, $y, 10, '• ' . $item); $y += 13; } $y += 8; if (!empty($texts['pickup_fields'])) { $y = document_pdf_heading($pdf, $y, 'Angaben zur Abholung (bitte ausfüllen)'); foreach (['Name des Abholers', 'Fahrzeug / amtliches Kennzeichen', 'Personalausweis-Nr.', 'Führerschein-Nr.'] as $field) { $pdf->text(50, $y, 9, $field, true); $pdf->line(200, $y + 2, 545, $y + 2, 0.5); $y += 18; } $y += 4; } $y = document_pdf_heading($pdf, $y + 6, 'Mietpreis und Zahlung'); $priceRows = [['Miete', fmt_money($rent)]]; if ($delivery > 0) { $priceRows[] = ['Lieferung / Abholung', fmt_money($delivery)]; } if ($deposit > 0) { $priceRows[] = ['Kaution', fmt_money($deposit) . ' (Rückgabe: volle Erstattung)']; } if ($paid > 0) { $priceRows[] = ['Anzahlung', '− ' . fmt_money($paid)]; } $priceRows[] = ['Gesamtbetrag', fmt_money($grand), true]; $priceRows[] = ['Bei Übergabe zu zahlen', fmt_money(max(0, $open)), true]; $y = document_pdf_rows($pdf, $y, $priceRows); $y = document_pdf_note($pdf, $y + 8, 'Wichtig', (string) $texts['hint']); $explain = 'Der Mieter bestätigt, den Mietgegenstand nebst Zubehör in sauberem und funktionsfähigem ' . 'Zustand erhalten zu haben. Die Allgemeinen Geschäftsbedingungen des Vermieters (folgende Seiten ' . 'dieses Vertrages) sind Bestandteil dieses Mietvertrages und wurden dem Mieter ausgehändigt. ' . 'Bei Rückgabe ist der Mietgegenstand gereinigt und vollständig zurückzugeben.'; $y = $pdf->paragraph(50, $y + 4, $pdf->pageWidth() - 100, 9, $explain, false, 12.5); $signatureTop = $y + 58; if ($signatureTop > 720) { document_pdf_footer($pdf, 'Mietvertrag · Buchung #' . (int) $booking['id'] . ' · ' . (string) $booking['customer_name']); $pdf->newPage(); $signatureTop = 150; } document_pdf_signatures($pdf, $signatureTop, $booking, $signatureFile, $signedAt, $signedVia); document_pdf_footer($pdf, 'Mietvertrag · Buchung #' . (int) $booking['id'] . ' · ' . (string) $booking['customer_name']); // Seite 2: AGB (gleiche Fassung wie unter /agb). $pdf->newPage(); $y = 70.0; $width = $pdf->pageWidth() - 100; $pdf->text(50, $y, 13, 'Allgemeine Geschäftsbedingungen (AGB)', true); $y += 16; $y = $pdf->paragraph(50, $y, $width, 8.5, 'für die Vermietung von Kühlanhängern und Kühltrühen – ' . $owner . ' – „' . (string) $legal['business_name'] . '“ (nachfolgend „Vermieter“).', false, 11) + 4; foreach (agb_sections() as $index => $section) { if ($y > $pdf->pageHeight() - 80) { document_pdf_footer($pdf, 'Mietvertrag · Buchung #' . (int) $booking['id'] . ' · AGB'); $pdf->newPage(); $y = 70.0; } $pdf->text(50, $y, 9.5, agb_heading((int) $index, $section), true); $y += 13; foreach (agb_plain_blocks($section) as $block) { $indent = $block['type'] === 'li' ? 62.0 : 50.0; $prefix = $block['type'] === 'li' ? '– ' : ''; $text = $prefix . (string) $block['text']; foreach ($pdf->wrap($text, 8.5, $width - ($indent - 50)) as $line) { if ($y > $pdf->pageHeight() - 70) { document_pdf_footer($pdf, 'Mietvertrag · Buchung #' . (int) $booking['id'] . ' · AGB'); $pdf->newPage(); $y = 70.0; } $pdf->text($indent, $y, 8.5, $line); $y += 11; } $y += 2; } $y += 5; } document_pdf_footer($pdf, 'Mietvertrag · Buchung #' . (int) $booking['id'] . ' · AGB'); return $pdf->output(); } /** Auftragsbestätigung als PDF. */ function document_confirmation_pdf(array $booking, string $variant): string { $legal = legal_data(); $texts = document_texts($variant); $deposit = max(0, (int) config('app.document_deposit_cents', 10000)); $rent = (int) ($booking['rent_cents'] ?? $booking['total_cents']); $delivery = (int) ($booking['delivery_cents'] ?? 0); $paid = (int) ($booking['deposit_cents'] ?? 0); $total = (int) $booking['total_cents']; $grand = $total + $deposit; $pdf = new PdfDoc(); document_pdf_title($pdf, 'Auftragsbestätigung', 'Buchung #' . (int) $booking['id'] . ' · ' . fmt_date(today_iso())); $y = document_pdf_parties($pdf, 92, $booking); $y = document_pdf_heading($pdf, $y, 'Bestätigte Buchung'); $rows = [ ['Mietgegenstand', document_subject_plain($booking)], ['Art', document_variant_label($variant)], ['Mietzeitraum', 'von ' . fmt_date_with_time((string) $booking['start_date'], $booking['start_time'] ?? null) . ' bis ' . fmt_date_with_time((string) $booking['end_date'], $booking['end_time'] ?? null)], ['Übergabe durch', (string) $booking['employee_name']], ['Rücknahme durch', booking_return_employee_name($booking)], ]; if ($variant === 'delivery') { $rows[] = ['Lieferadresse', document_delivery_address($booking)]; } $y = document_pdf_rows($pdf, $y, $rows); $y = document_pdf_heading($pdf, $y + 6, 'Beträge'); $priceRows = [['Miete', fmt_money($rent)]]; if ($delivery > 0) { $priceRows[] = ['Lieferung / Abholung', fmt_money($delivery)]; } if ($deposit > 0) { $priceRows[] = ['Kaution', fmt_money($deposit) . ' (Rückgabe: volle Erstattung)']; } // Anzahlung: vereinbart (Häkchen in der Buchung) und Betrag > 0. $depositRequired = (int) ($booking['deposit_required'] ?? 0) === 1; $account = $depositRequired && $paid > 0 ? deposit_account((int) ($booking['deposit_account_id'] ?? 0)) : null; $dueDate = $account !== null ? deposit_due_date() : null; $workingDays = deposit_due_working_days(); if ($paid > 0) { $priceRows[] = [ $account !== null ? 'Anzahlung (bis ' . fmt_date((string) $dueDate) . ')' : 'Anzahlung', '− ' . fmt_money($paid), ]; } $priceRows[] = ['Gesamtbetrag', fmt_money($grand), true]; $priceRows[] = ['Bei Übergabe zu zahlen', fmt_money(max(0, $grand - $paid)), true]; $y = document_pdf_rows($pdf, $y, $priceRows); if ($account !== null) { $y = document_pdf_heading($pdf, $y + 6, 'Anzahlung und verbindliche Reservierung'); $intro = 'Zur verbindlichen Reservierung ist eine Anzahlung in Höhe von ' . fmt_money($paid) . ' innerhalb von ' . $workingDays . ' Werktagen nach Erhalt dieser Auftragsbestätigung – also bis ' . 'spätestens ' . fmt_date((string) $dueDate) . ' – auf folgendes Konto zu überweisen:'; $y = $pdf->paragraph(50, $y + 2, $pdf->pageWidth() - 100, 9.5, $intro, false, 13); $y = document_pdf_rows($pdf, $y + 4, [ ['Kontoinhaber', $account['holder']], ['Bank', $account['bank']], ['IBAN', $account['iban']], ['Verwendungszweck', document_subject_plain($booking) . ' ' . fmt_date((string) $booking['start_date']) . ' · ' . (string) $booking['customer_name']], ], 150.0); $warning = 'Bitte beachten: Erst nach Eingang der Anzahlung auf dem genannten Konto ist der Termin ' . 'verbindlich reserviert. Erfolgt innerhalb der Frist kein Zahlungseingang, behalten wir uns vor, ' . 'den Termin wieder freizugeben.'; $y = $pdf->paragraph(50, $y + 4, $pdf->pageWidth() - 100, 9.5, $warning, false, 13); } // Zahlungshinweis und Schlusstext in einem Block – hält die Seite einseitig. $payment = $account !== null ? 'Der Restbetrag von ' . fmt_money(max(0, $grand - $paid)) . ' ist bei der Übergabe fällig. ' . 'Die Kaution von ' . fmt_money($deposit) . ' wird bei ordnungsgemäßer Rückgabe vollständig erstattet. ' : 'Der Gesamtbetrag ist bei der Übergabe in bar zu zahlen; nach Absprache auch per Überweisung ' . '(Geld bis spätestens Montag der Terminwoche). Die Kaution wird bei ordnungsgemäßer Rückgabe ' . 'vollständig erstattet. '; $closing = 'Vielen Dank für die Buchung. Diese Auftragsbestätigung bestätigt den vereinbarten Termin und ' . 'die genannten Beträge. ' . $payment . 'Es gelten die Allgemeinen Geschäftsbedingungen des Vermieters. ' . 'Bitte prüfen Sie die Angaben und melden Sie sich bei Abweichungen.'; $y = $pdf->paragraph(50, $y + 8, $pdf->pageWidth() - 100, 9, $closing, false, 12.5); $owner = trim((string) ($legal['owner'] ?? '')) !== '' ? (string) $legal['owner'] : (string) $legal['business_name']; $signatureFile = owner_signature_path(); $signatureSpace = $signatureFile !== null ? 52 : 18; // Zusatzvereinbarungen (Freitext aus der Buchung), falls hinterlegt. $agreements = trim((string) ($booking['agreements'] ?? '')); if ($agreements !== '') { $textWidth = $pdf->pageWidth() - 100; $agreementLines = 0; $agreementText = []; foreach (preg_split('/\R/', $agreements) ?: [] as $line) { if (trim($line) === '') { continue; } $wrapped = $pdf->wrap(trim($line), 9, $textWidth); $agreementLines += count($wrapped); foreach ($wrapped as $wrappedLine) { $agreementText[] = $wrappedLine; } } // Nur umbrechen, wenn Vereinbarungen + Unterschrift sonst nicht mehr passen. $needed = 26 + $agreementLines * 12.5 + $signatureSpace + 12; if ($y + $needed > 762) { document_pdf_footer($pdf, 'Auftragsbestätigung · Buchung #' . (int) $booking['id']); $pdf->newPage(); $y = 90; } $y = document_pdf_heading($pdf, $y + 8, 'Zusatzvereinbarungen'); foreach ($agreementText as $line) { $pdf->text(50, $y, 9, $line); $y += 12.5; } } // Unterschriftenfelder: links Ort/Datum (vorbelegt), rechts die hinterlegte // Unterschrift des Vermieters. Nur bei Platzmangel auf eine neue Seite. $signatureTop = $y + $signatureSpace; if ($signatureTop > 762) { document_pdf_footer($pdf, 'Auftragsbestätigung · Buchung #' . (int) $booking['id']); $pdf->newPage(); $signatureTop = 190; } $place = trim((string) ($legal['city'] ?? '')); $pdf->text(50, $signatureTop - 7, 9.5, trim($place . ', ' . fmt_date(today_iso()), ', ')); $pdf->line(50, $signatureTop, 300, $signatureTop, 0.7); $pdf->text(50, $signatureTop + 13, 7.5, 'Ort, Datum'); if ($signatureFile !== null) { $pdf->image($signatureFile, 326, $signatureTop - 46, 130, 43.3); } $pdf->line(320, $signatureTop, 545, $signatureTop, 0.7); $pdf->text(320, $signatureTop + 13, 7.5, 'Unterschrift Vermieter – ' . $owner); document_pdf_footer($pdf, 'Auftragsbestätigung · Buchung #' . (int) $booking['id']); return $pdf->output(); } /* -------------------------------------------------------- Unterschrift */ /** * Speichert die Unterschrift (JPEG-Daten-URL) und erzeugt das Mietvertrags-PDF * neu, damit die Unterschrift im Dokument steht. * * $via: 'tablet' (Kunde unterschreibt auf dem Drink-it-cold-Tablet bei der * Lieferung) oder 'link' (Unterschriftslink auf dem eigenen Gerät des Kunden). */ function document_save_signature( array $booking, array $doc, string $dataUrl, ?int $userId, string $via = 'tablet' ): array { if ($doc['kind'] !== DOCUMENT_KIND_CONTRACT) { throw new RuntimeException('Nur der Mietvertrag wird unterschrieben.'); } if (!preg_match('#^data:image/jpeg;base64,([A-Za-z0-9+/=\s]+)$#', trim($dataUrl), $m)) { throw new RuntimeException('Die Unterschrift konnte nicht gelesen werden.'); } $binary = base64_decode((string) preg_replace('/\s+/', '', $m[1]), true); if (!is_string($binary) || strlen($binary) < 500 || strncmp($binary, "\xFF\xD8", 2) !== 0) { throw new RuntimeException('Die Unterschrift ist leer.'); } if (strlen($binary) > 1500000) { throw new RuntimeException('Die Unterschrift ist zu groß.'); } $dir = document_booking_dir((int) $doc['booking_id'], true); $file = 'unterschrift-' . (int) $doc['id'] . '.jpg'; if (@file_put_contents($dir . '/' . $file, $binary) === false) { throw new RuntimeException('Die Unterschrift konnte nicht gespeichert werden.'); } $via = in_array($via, ['tablet', 'link'], true) ? $via : 'tablet'; db()->prepare( 'UPDATE booking_documents SET signature_file = ?, signed_at = ?, signed_via = ?, sign_token = NULL WHERE id = ?' )->execute([$file, utc_now(), $via, (int) $doc['id']]); $doc = document_find((int) $doc['id']) ?? $doc; if (!empty($userId)) { db()->prepare('UPDATE booking_documents SET created_by = COALESCE(created_by, ?) WHERE id = ?') ->execute([$userId, (int) $doc['id']]); $doc = document_find((int) $doc['id']) ?? $doc; } return document_regenerate($booking, $doc); } /* ------------------------------------------- Digitale Unterschrift per Link */ /** Absolute URL für Links in E-Mails (config app.public_url, sonst Host). */ function document_absolute_url(string $path): string { $base = rtrim((string) config('app.public_url', ''), '/'); if ($base === '' && !empty($_SERVER['HTTP_HOST'])) { $base = (is_https() ? 'https://' : 'http://') . (string) $_SERVER['HTTP_HOST']; } return $base . url($path); } /** Unterschriftslink des Kunden (leer, solange keiner angefordert wurde). */ function document_sign_link(array $doc): string { $token = trim((string) ($doc['sign_token'] ?? '')); return $token === '' ? '' : document_absolute_url('/unterschrift/' . $token); } function document_find_by_sign_token(string $token): ?array { $token = trim($token); if (!preg_match('/^[a-f0-9]{64}$/', $token) || !documents_schema_ready()) { return null; } $stmt = db()->prepare('SELECT * FROM booking_documents WHERE sign_token = ? LIMIT 1'); $stmt->execute([$token]); $row = $stmt->fetch(); return $row ?: null; } /** * Erzeugt (oder erneuert) den persönlichen Unterschriftslink des Kunden. * Der Link bleibt gültig, bis der Kunde unterschreibt oder ein neuer erzeugt wird. */ function document_request_signature(array $doc, bool $renew = false): array { if ($doc['kind'] !== DOCUMENT_KIND_CONTRACT) { throw new RuntimeException('Nur der Mietvertrag wird unterschrieben.'); } if (!documents_schema_ready()) { throw new RuntimeException('Die Tabelle für Unterlagen fehlt noch. Bitte zuerst /migrate mit dem Cron-Token aufrufen.'); } $token = trim((string) ($doc['sign_token'] ?? '')); if ($token === '' || $renew) { $token = bin2hex(random_bytes(32)); db()->prepare('UPDATE booking_documents SET sign_token = ?, sign_requested_at = ? WHERE id = ?') ->execute([$token, utc_now(), (int) $doc['id']]); } return document_find((int) $doc['id']) ?? $doc; } /** Verschickt den Unterschriftslink an den Kunden. */ function document_mail_signature_request(array $booking, array $doc): bool { if (!mail_is_enabled()) { throw new RuntimeException('Der E-Mail-Versand ist nicht aktiviert (app.mail_enabled).'); } $to = trim((string) $booking['email']); if ($to === '' || !filter_var($to, FILTER_VALIDATE_EMAIL)) { throw new RuntimeException('Für diese Buchung ist keine gültige E-Mail-Adresse hinterlegt.'); } $link = document_sign_link($doc); if ($link === '') { throw new RuntimeException('Es gibt noch keinen Unterschriftslink.'); } $legal = legal_data(); $owner = trim((string) ($legal['owner'] ?? '')) !== '' ? (string) $legal['owner'] : (string) $legal['business_name']; $subject = 'Mietvertrag zur Unterschrift · ' . (string) $booking['trailer_label'] . ' · ' . fmt_date_short((string) $booking['start_date']); $body = 'Guten Tag ' . (string) $booking['customer_name'] . ",\n\n" . 'bitte unterschreiben Sie den Mietvertrag zu Ihrer Buchung digital. Der Link ist persönlich für Sie ' . "bestimmt und bleibt gültig, bis Sie unterschrieben haben:\n\n" . $link . "\n\n" . 'Mietgegenstand: ' . (string) $booking['trailer_label'] . "\n" . 'Zeitraum: ' . fmt_date_short_with_time((string) $booking['start_date'], $booking['start_time'] ?? null) . ' bis ' . fmt_date_short_with_time((string) $booking['end_date'], $booking['end_time'] ?? null) . "\n\n" . 'Den Vertrag können Sie sich im Link vorab als PDF ansehen. Nach der Unterschrift erhalten Sie den ' . "unterschriebenen Vertrag automatisch per E-Mail.\n\n" . 'Freundliche Grüße' . "\n" . $owner . "\n" . (string) $legal['business_name'] . "\n" . (string) $legal['phone'] . ' · ' . (string) $legal['email']; if (!mail_send($to, $subject, $body)) { return false; } db()->prepare('UPDATE booking_documents SET sign_requested_at = COALESCE(sign_requested_at, ?) WHERE id = ?') ->execute([utc_now(), (int) $doc['id']]); return true; } /** Schickt dem Kunden den unterschriebenen Vertrag als PDF. */ function document_mail_signed_copy(array $booking, array $doc): bool { if (!mail_is_enabled()) { return false; } $path = document_path($doc); if (!is_file($path)) { return false; } return mail_send_attachment( trim((string) $booking['email']), 'Ihr unterschriebener Mietvertrag · ' . (string) $booking['trailer_label'] . ' · ' . fmt_date_short((string) $booking['start_date']), 'Guten Tag ' . (string) $booking['customer_name'] . ",\n\n" . "vielen Dank – Ihre Unterschrift ist eingegangen. Den unterschriebenen Mietvertrag finden Sie im " . "Anhang.\n\nMietgegenstand: " . (string) $booking['trailer_label'] . "\n" . 'Zeitraum: ' . fmt_date_short_with_time((string) $booking['start_date'], $booking['start_time'] ?? null) . ' bis ' . fmt_date_short_with_time((string) $booking['end_date'], $booking['end_time'] ?? null) . "\n\n" . "Bei Fragen einfach auf diese E-Mail antworten.\n\nFreundliche Grüße\n" . (string) legal_data()['business_name'], (string) $doc['file_name'], 'application/pdf', (string) file_get_contents($path) ); } /** * Unterschrift aus dem Kundenlink: speichert die Signatur, entwertet den Link * und schickt dem Kunden den unterschriebenen Vertrag. */ function document_sign_by_customer(array $booking, array $doc, string $dataUrl): array { $doc = document_save_signature($booking, $doc, $dataUrl, null, 'link'); $mailed = false; if (mail_is_enabled() && filter_var((string) $booking['email'], FILTER_VALIDATE_EMAIL) !== false) { $mailed = document_mail_signed_copy($booking, $doc); } return ['doc' => $doc, 'mailed' => $mailed]; } /* ------------------------------------------------------------ Rechnung */ /** * Nimmt eine Rechnung (PDF aus Lexware) entgegen und legt sie zur Buchung ab. * * @param array{name?: string, tmp_name?: string, error?: int, size?: int} $file */ function document_upload_invoice(array $booking, array $file, ?int $userId): array { if (!documents_schema_ready()) { throw new RuntimeException('Die Tabelle für Unterlagen fehlt noch. Bitte zuerst /migrate mit dem Cron-Token aufrufen.'); } $error = (int) ($file['error'] ?? UPLOAD_ERR_NO_FILE); if ($error === UPLOAD_ERR_NO_FILE) { throw new RuntimeException('Bitte eine PDF-Datei auswählen.'); } if ($error !== UPLOAD_ERR_OK) { throw new RuntimeException('Der Upload ist fehlgeschlagen (Code ' . $error . ').'); } $tmp = (string) ($file['tmp_name'] ?? ''); if ($tmp === '' || !is_uploaded_file($tmp)) { throw new RuntimeException('Der Upload ist unvollständig.'); } $maxMb = max(1, (int) config('app.document_max_mb', 10)); $size = (int) filesize($tmp); if ($size < 100) { throw new RuntimeException('Die Datei ist leer.'); } if ($size > $maxMb * 1024 * 1024) { throw new RuntimeException('Die Datei ist größer als ' . $maxMb . ' MB.'); } $head = (string) file_get_contents($tmp, false, null, 0, 5); if ($head !== '%PDF-') { throw new RuntimeException('Nur PDF-Dateien werden unterstützt.'); } $bytes = (string) file_get_contents($tmp); if ($bytes === '') { throw new RuntimeException('Die Datei konnte nicht gelesen werden.'); } $dir = document_booking_dir((int) $booking['id'], true); $stored = bin2hex(random_bytes(8)) . '.pdf'; if (@file_put_contents($dir . '/' . $stored, $bytes) === false) { throw new RuntimeException('Die Rechnung konnte nicht gespeichert werden.'); } $original = trim((string) ($file['name'] ?? '')); $original = (string) preg_replace('/[^A-Za-z0-9äöüÄÖÜß ._-]+/u', '', basename($original)); $name = trim((string) preg_replace('/\s+/', ' ', $original)); if ($name === '' || !str_ends_with(mb_strtolower($name), '.pdf')) { $name = 'Rechnung ' . (string) $booking['customer_name'] . '.pdf'; } db()->prepare( 'INSERT INTO booking_documents (booking_id, kind, variant, file_name, stored_file, mime_type, size_bytes, source, created_at, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)' )->execute([ (int) $booking['id'], DOCUMENT_KIND_INVOICE, '', mb_substr($name, 0, 120), $stored, 'application/pdf', strlen($bytes), 'upload', utc_now(), $userId, ]); return document_find((int) db()->lastInsertId()) ?? []; } /* ---------------------------------------------------------------- Versand */ /** Verschickt eine Unterlage als PDF-Anhang an den Kunden. */ function document_mail_to_customer(array $booking, array $doc): bool { if (!mail_is_enabled()) { throw new RuntimeException('Der E-Mail-Versand ist nicht aktiviert (app.mail_enabled).'); } $to = trim((string) $booking['email']); if ($to === '' || !filter_var($to, FILTER_VALIDATE_EMAIL)) { throw new RuntimeException('Für diese Buchung ist keine gültige E-Mail-Adresse hinterlegt.'); } $path = document_path($doc); if (!is_file($path)) { throw new RuntimeException('Die Datei fehlt.'); } $legal = legal_data(); $owner = trim((string) ($legal['owner'] ?? '')) !== '' ? (string) $legal['owner'] : (string) $legal['business_name']; $label = document_kind_label((string) $doc['kind']); $subject = $label . ' zur Buchung #' . (int) $booking['id'] . ' · ' . (string) $booking['trailer_label'] . ' · ' . fmt_date_short((string) $booking['start_date']); $body = 'Guten Tag ' . (string) $booking['customer_name'] . ",\n\n" . 'anbei erhalten Sie ' . ($doc['kind'] === DOCUMENT_KIND_CONTRACT ? 'den' : 'die') . ' ' . $label . ' zu Ihrer Buchung.' . "\n\n" . 'Mietgegenstand: ' . (string) $booking['trailer_label'] . "\n" . 'Zeitraum: ' . fmt_date_short_with_time((string) $booking['start_date'], $booking['start_time'] ?? null) . ' bis ' . fmt_date_short_with_time((string) $booking['end_date'], $booking['end_time'] ?? null) . "\n\n" . 'Bei Fragen einfach auf diese E-Mail antworten.' . "\n\n" . 'Freundliche Grüße' . "\n" . $owner . "\n" . (string) $legal['business_name'] . "\n" . (string) $legal['phone'] . ' · ' . (string) $legal['email']; $ok = mail_send_attachment($to, $subject, $body, (string) $doc['file_name'], 'application/pdf', (string) file_get_contents($path)); if ($ok) { db()->prepare('UPDATE booking_documents SET mailed_at = ? WHERE id = ?')->execute([utc_now(), (int) $doc['id']]); } return $ok; } /* -------------------------------------------------------------- Löschen */ function document_delete(int $id): void { $doc = document_find($id); if (!$doc) { return; } db()->prepare('DELETE FROM booking_documents WHERE id = ?')->execute([$id]); foreach ([document_path($doc), document_signature_path($doc)] as $path) { if ($path !== null && is_file($path)) { @unlink($path); } } } /** * Löscht Unterlagen einen Monat nach dem Mietende sowie verwaiste Dateien. * * @return array{rows: int, files: int} */ function documents_cleanup(): array { $days = max(0, (int) config('app.document_retention_days', 30)); $cutoff = add_days(today_iso(), -$days); $result = ['rows' => 0, 'files' => 0]; if (!documents_schema_ready()) { return $result; } $stmt = db()->prepare( 'SELECT d.* FROM booking_documents d JOIN bookings b ON b.id = d.booking_id WHERE b.end_date < ?' ); $stmt->execute([$cutoff]); foreach ($stmt->fetchAll() as $doc) { document_delete((int) $doc['id']); $result['rows']++; } // Dateien gelöschter Buchungen und verwaiste Ordner mit aufräumen. $root = document_store_root(); if (!is_dir($root)) { return $result; } $known = db()->query('SELECT DISTINCT booking_id FROM booking_documents')->fetchAll(PDO::FETCH_COLUMN); $known = array_map('intval', $known); foreach (scandir($root) ?: [] as $entry) { if ($entry === '.' || $entry === '..' || !ctype_digit($entry)) { continue; } if (in_array((int) $entry, $known, true)) { continue; } foreach (glob($root . '/' . $entry . '/*') ?: [] as $file) { if (is_file($file) && @unlink($file)) { $result['files']++; } } @rmdir($root . '/' . $entry); } return $result; }