<?php
session_start();
require_once __DIR__ . '/config/config.php';
header('Content-Type: application/json');
if (!isset($_SESSION['user_id'])) { http_response_code(401); echo json_encode(['success'=>false,'message'=>'Unauthorized']); exit; }
try {
    $userId = (int) $_SESSION['user_id'];
    $stmt = $conn->prepare('SELECT i.id,i.package_name,i.amount,i.roi_percent,i.expected_return,i.start_date,i.end_date,i.status,p.credited_amount,p.processed_at FROM investments i LEFT JOIN investment_payouts p ON p.investment_id=i.id WHERE i.user_id=? ORDER BY i.created_at DESC');
    $stmt->bind_param('i', $userId); $stmt->execute();
    $investments = $stmt->get_result()->fetch_all(MYSQLI_ASSOC); $stmt->close();

    $payments = $conn->prepare('SELECT investment_id,period_number,rate_percent,amount,due_date,status,paid_at FROM investment_return_payments WHERE user_id=? ORDER BY investment_id,period_number');
    $payments->bind_param('i', $userId); $payments->execute();
    $paymentResult = $payments->get_result(); $byInvestment = [];
    while ($row = $paymentResult->fetch_assoc()) { $byInvestment[(int)$row['investment_id']][] = $row; }
    $payments->close();
    foreach ($investments as &$investment) { $investment['return_payments'] = $byInvestment[(int)$investment['id']] ?? []; }
    unset($investment);
    echo json_encode(['success'=>true,'currency'=>'GBP','investments'=>$investments]);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['success'=>false,'message'=>'Unable to load investment records.']);
}