<?php
// admin/accounts/export-report.php
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/functions.php';

if (!isAdmin()) {
    exit('Unauthorized');
}

$year = isset($_GET['year']) ? intval($_GET['year']) : date('Y');
$month = isset($_GET['month']) ? intval($_GET['month']) : date('m');

// Get data
$monthly_data = [];
$month_names = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

for ($m = 1; $m <= 12; $m++) {
    $stmt = $pdo->prepare("SELECT COALESCE(SUM(amount), 0) as total FROM income WHERE YEAR(payment_date) = ? AND MONTH(payment_date) = ?");
    $stmt->execute([$year, $m]);
    $income = $stmt->fetch()['total'];
    
    $stmt = $pdo->prepare("SELECT COALESCE(SUM(amount), 0) as total FROM expenses WHERE YEAR(expense_date) = ? AND MONTH(expense_date) = ?");
    $stmt->execute([$year, $m]);
    $expenses = $stmt->fetch()['total'];
    
    $monthly_data[] = [
        'month' => $month_names[$m - 1],
        'income' => $income,
        'expenses' => $expenses,
        'profit' => $income - $expenses
    ];
}

// Create CSV
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="financial_report_' . $year . '.csv"');

$output = fopen('php://output', 'w');
fputcsv($output, ['Month', 'Income (TK)', 'Expenses (TK)', 'Profit/Loss (TK)', 'Margin %']);

foreach ($monthly_data as $data) {
    $margin = $data['income'] > 0 ? ($data['profit'] / $data['income']) * 100 : 0;
    fputcsv($output, [
        $data['month'],
        $data['income'],
        $data['expenses'],
        $data['profit'],
        number_format($margin, 1) . '%'
    ]);
}

fclose($output);
exit;
?>