prepare("SELECT * FROM projects WHERE id = :id"); $stmt->execute([':id' => $project_id]); $project = $stmt->fetch(PDO::FETCH_ASSOC); if ($project) { function get_month_range($start_date_str, $end_date_str) { $months = []; if (empty($start_date_str) || empty($end_date_str)) return $months; $start = new DateTime($start_date_str); $end = new DateTime($end_date_str); $current = clone $start; $current->modify('first day of this month'); while ($current <= $end) { $months[] = $current->format('Y-m-01'); $current->modify('+1 month'); } return $months; } $months = get_month_range($project['startDate'], $project['endDate']); foreach ($metrics as $metric) { foreach ($months as $month) { $financial_data[$metric][$month] = 0; } } $forecast_stmt = $pdo->prepare("SELECT id FROM forecasting WHERE projectId = :pid ORDER BY versionNumber DESC LIMIT 1"); $forecast_stmt->execute([':pid' => $project_id]); $latest_forecast = $forecast_stmt->fetch(PDO::FETCH_ASSOC); if ($latest_forecast) { $cost_sql = " SELECT fa.month, SUM(fa.allocatedDays * r.totalMonthlyCost) as totalCost FROM forecastAllocation fa JOIN roster r ON fa.rosterId = r.id WHERE fa.forecastingId = :fid GROUP BY fa.month "; $cost_stmt = $pdo->prepare($cost_sql); $cost_stmt->execute([':fid' => $latest_forecast['id']]); $monthly_costs = $cost_stmt->fetchAll(PDO::FETCH_KEY_PAIR); foreach ($monthly_costs as $month => $cost) { $formatted_month = date('Y-m-01', strtotime($month)); if (isset($financial_data['Cost'][$formatted_month])) { $financial_data['Cost'][$formatted_month] = $cost; } } } } } catch (PDOException $e) { header("HTTP/1.0 500 Internal Server Error"); echo "Database error: " . $e->getMessage(); exit; } if (!$project) { header("HTTP/1.0 404 Not Found"); echo "Project not found."; exit; } // --- CSV EXPORT --- $filename = "project_finance_" . preg_replace('/[^a-zA-Z0-9_]/', '_', $project['name']) . ".csv"; header('Content-Type: text/csv'); header('Content-Disposition: attachment; filename="' . $filename . '"'); $output = fopen('php://output', 'w'); // Header row $header = ['Metric']; foreach ($months as $month) { $header[] = date('M Y', strtotime($month)); } fputcsv($output, $header); // Data rows foreach ($metrics as $metric) { $row = [$metric]; foreach ($months as $month) { $row[] = number_format($financial_data[$metric][$month] ?? 0, 2); } fputcsv($output, $row); } fclose($output); exit;