- Clear output buffers before sending JSON - Set proper Content-Type: application/json header - Return clean JSON only (no extra output) - Fixes 'Unexpected end of JSON input' error - Download button should now work correctly
79 lines
2 KiB
PHP
79 lines
2 KiB
PHP
<?php
|
|
/**
|
|
* Simpler backend - waits for completion then returns result
|
|
* Better for MAMP which buffers output
|
|
*/
|
|
|
|
require_once __DIR__ . '/config.php';
|
|
require_once __DIR__ . '/AuthMiddleware.php';
|
|
|
|
$auth = new AuthMiddleware();
|
|
$user = $auth->requireAuth();
|
|
|
|
// Get POST data
|
|
$input = json_decode(file_get_contents('php://input'), true);
|
|
|
|
if (!$input || !isset($input['date'])) {
|
|
http_response_code(400);
|
|
echo json_encode(['success' => false, 'error' => 'Date is required']);
|
|
exit;
|
|
}
|
|
|
|
$date = trim($input['date']);
|
|
|
|
// Validate date format
|
|
if (!preg_match('/^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday),\s+\w+\s+\d+$/', $date)) {
|
|
http_response_code(400);
|
|
echo json_encode(['success' => false, 'error' => 'Invalid date format. Use: "Monday, January 6"']);
|
|
exit;
|
|
}
|
|
|
|
header('Content-Type: application/json');
|
|
|
|
// Change to project directory
|
|
chdir(PROJECT_ROOT);
|
|
|
|
// Build command with date argument
|
|
$pythonBin = PYTHON_VENV;
|
|
$scriptPath = PYTHON_SCRIPT;
|
|
$escapedDate = escapeshellarg($date);
|
|
$command = "{$pythonBin} {$scriptPath} {$escapedDate} 2>&1";
|
|
|
|
// Execute and capture all output
|
|
$output = [];
|
|
$returnCode = 0;
|
|
exec($command, $output, $returnCode);
|
|
|
|
// Join output
|
|
$fullOutput = implode("\n", $output);
|
|
|
|
// Parse output to find filename
|
|
$filename = null;
|
|
if (preg_match('/Report saved to:.*\/(Newsroom_Report_[\d-]+\.pdf)/', $fullOutput, $matches)) {
|
|
$filename = $matches[1];
|
|
}
|
|
|
|
// Clear any output buffers
|
|
while (ob_get_level()) {
|
|
ob_end_clean();
|
|
}
|
|
|
|
// Set proper headers
|
|
header('Content-Type: application/json');
|
|
|
|
// Return clean JSON only
|
|
if ($returnCode === 0 && $filename) {
|
|
echo json_encode([
|
|
'success' => true,
|
|
'filename' => $filename,
|
|
'message' => 'Report generated successfully'
|
|
], JSON_PRETTY_PRINT);
|
|
} else {
|
|
http_response_code(500);
|
|
echo json_encode([
|
|
'success' => false,
|
|
'error' => 'Report generation failed',
|
|
'output' => substr($fullOutput, -1000), // Last 1000 chars only
|
|
'returnCode' => $returnCode
|
|
], JSON_PRETTY_PRINT);
|
|
}
|