<?php
require_once '../includes/auth.php';
require_once '../includes/functions.php';

if (!$auth->isLoggedIn()) {
    exit('Unauthorized');
}

$user_id = $auth->getCurrentUserId();
$investment_id = (int)($_GET['id'] ?? 0);
$db = Database::getInstance()->getConnection();

// Verify ownership
$stmt = $db->prepare("SELECT * FROM investments WHERE id = ? AND user_id = ?");
$stmt->execute([$investment_id, $user_id]);
$investment = $stmt->fetch();

if (!$investment) {
    exit('Investment not found');
}

// Get transactions related to this investment
$stmt = $db->prepare("SELECT * FROM transactions WHERE user_id = ? AND (description LIKE ? OR (details LIKE ?)) ORDER BY created_at DESC");
$search = "%investment #$investment_id%";
$json_search = '%"investment_id":' . $investment_id . '%';
$stmt->execute([$user_id, $search, $json_search]);
$transactions = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Set headers for CSV download
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="investment_' . $investment_id . '_statement.csv"');

$output = fopen('php://output', 'w');

// CSV Header
fputcsv($output, ['Date', 'Reference', 'Type', 'Amount', 'Status', 'Description']);

// CSV Data
foreach ($transactions as $row) {
    fputcsv($output, [
        $row['created_at'],
        $row['reference'],
        ucfirst($row['type']),
        number_format($row['amount'], 2),
        ucfirst($row['status']),
        $row['description']
    ]);
}

fclose($output);
?>