38348-vm/send_document.php
2026-02-11 01:46:33 +00:00

85 lines
3.2 KiB
PHP

<?php
require_once __DIR__ . '/db/config.php';
require_once __DIR__ . '/includes/DocumentService.php';
require_once __DIR__ . '/mail/MailService.php';
$type = $_GET['type'] ?? '';
$id = $_GET['id'] ?? '';
$is_reminder = isset($_GET['reminder']);
if (!in_array($type, ['quotation', 'invoice']) || !$id) {
die("Invalid request");
}
$db = db();
$customer = null;
$doc_number = '';
$pdf_content = '';
$doc = null;
if ($type === 'quotation') {
$stmt = $db->prepare("SELECT q.*, c.name as customer_name, c.email as customer_email
FROM quotations q
JOIN customers c ON q.customer_id = c.id
WHERE q.id = ?");
$stmt->execute([$id]);
$doc = $stmt->fetch();
if ($doc) {
$customer = ['name' => $doc['customer_name'], 'email' => $doc['customer_email']];
$doc_number = $doc['quotation_number'];
$pdf_content = DocumentService::generateQuotationPDF($id, 'S');
}
} else {
$stmt = $db->prepare("SELECT i.*, c.name as customer_name, c.email as customer_email
FROM invoices i
JOIN customers c ON i.customer_id = c.id
WHERE i.id = ?");
$stmt->execute([$id]);
$doc = $stmt->fetch();
if ($doc) {
$customer = ['name' => $doc['customer_name'], 'email' => $doc['customer_email']];
$doc_number = $doc['invoice_number'];
$pdf_content = DocumentService::generateInvoicePDF($id, 'S');
}
}
if (!$customer || !$pdf_content) {
die("Document not found");
}
if (!$customer['email']) {
header("Location: " . ($type === 'quotation' ? 'quotations.php' : 'invoices.php') . "?error=" . urlencode("Customer does not have an email address"));
exit;
}
if ($is_reminder) {
$subject = "REMINDER: " . ucfirst($type) . " " . $doc_number . " from CRM PRO";
$body = "Dear " . e($customer['name']) . ",<br><br>This is a friendly reminder regarding your " . $type . " " . e($doc_number) . ".<br><br>Please find it attached again for your reference.<br><br>Thank you!<br><br>Best regards,<br>CRM PRO Team";
} else {
$subject = ucfirst($type) . " " . $doc_number . " from CRM PRO";
$body = "Dear " . e($customer['name']) . ",<br><br>Please find attached your " . $type . " " . e($doc_number) . ".<br><br>Thank you for your business!<br><br>Best regards,<br>CRM PRO Team";
}
$opts = [
'attachments' => [
[
'data' => $pdf_content,
'name' => ucfirst($type) . "_" . $doc_number . ".pdf"
]
]
];
$result = MailService::sendMail($customer['email'], $subject, $body, null, $opts);
$redirect = ($type === 'quotation' ? 'quotations.php' : 'invoices.php');
if ($result['success']) {
// Update last reminded at
$table = ($type === 'quotation' ? 'quotations' : 'invoices');
$stmt = $db->prepare("UPDATE $table SET last_reminded_at = NOW() WHERE id = ?");
$stmt->execute([$id]);
header("Location: $redirect?msg=" . urlencode(($is_reminder ? "Reminder" : ucfirst($type)) . " emailed successfully to " . $customer['email']));
} else {
header("Location: $redirect?error=" . urlencode("Failed to send email: " . $result['error']));
}
exit;