64 lines
2.0 KiB
PHP
64 lines
2.0 KiB
PHP
<?php
|
|
require_once __DIR__ . '/ReportGenerator.php';
|
|
|
|
header('Content-Type: application/json');
|
|
|
|
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
|
http_response_code(405); // Method Not Allowed
|
|
echo json_encode(['error' => 'Invalid request method.']);
|
|
exit;
|
|
}
|
|
|
|
$post_data = $_POST;
|
|
|
|
// Basic validation
|
|
if (!isset($post_data['email']) || !filter_var($post_data['email'], FILTER_VALIDATE_EMAIL)) {
|
|
http_response_code(400); // Bad Request
|
|
echo json_encode(['error' => 'Invalid or missing email address.']);
|
|
exit;
|
|
}
|
|
|
|
if (!isset($post_data['consent']) || $post_data['consent'] !== 'on') {
|
|
http_response_code(400); // Bad Request
|
|
echo json_encode(['error' => 'Consent is required.']);
|
|
exit;
|
|
}
|
|
|
|
// Generate the report
|
|
$generator = new ReportGenerator($post_data);
|
|
$report_data = $generator->generate();
|
|
|
|
// Check for mail configuration before attempting to send
|
|
$mailConfig = require __DIR__ . '/mail/config.php';
|
|
if (empty($mailConfig['smtp_host']) || empty($mailConfig['smtp_user']) || empty($mailConfig['smtp_pass'])) {
|
|
http_response_code(500);
|
|
echo json_encode([
|
|
'success' => false,
|
|
'error' => 'Mail service is not configured. Please set SMTP_HOST, SMTP_USER, and SMTP_PASS in your .env file.',
|
|
'details' => 'Mail service is not configured.'
|
|
]);
|
|
exit;
|
|
}
|
|
|
|
// Send the email
|
|
$email_result = $generator->sendEmail($post_data['email']);
|
|
|
|
if (!empty($email_result['success'])) {
|
|
echo json_encode([
|
|
'success' => true,
|
|
'message' => 'Report successfully sent to ' . $post_data['email'],
|
|
'report' => $report_data // Optionally return report data to the frontend
|
|
]);
|
|
} else {
|
|
http_response_code(500); // Internal Server Error
|
|
$error_detail = $email_result['error'] ?? 'Unknown error';
|
|
error_log('MailService Error: ' . $error_detail);
|
|
echo json_encode([
|
|
'success' => false,
|
|
'error' => 'Failed to send email. Please check your SMTP credentials in the .env file.',
|
|
'details' => $error_detail // for debugging
|
|
]);
|
|
}
|
|
|
|
?>
|