<?php
require_once __DIR__ . '/lib/functions.php';
require_once __DIR__ . '/lib/document-templates.php';
mdw_require_login();
$documents = mdw_saved_documents();
$invoices = array_values(array_filter($documents, fn($d) => ($d['template'] ?? '') === 'invoice'));

if (isset($_GET['download']) && $_GET['download'] === 'csv') {
    $csvName = 'mdw-invoices-' . date('Y-m-d') . '.csv';
    mdw_ensure_storage();
    $exportPath = mdw_storage_path('exports') . '/' . $csvName;
    $out = fopen($exportPath, 'w');
    fputcsv($out, ['Source System','Source Reference','Invoice Number','Invoice Date','Client','Project','Subtotal','Tax','Total Due','Due Date','Status','Document ID']);
    foreach ($invoices as $doc) {
        $f = $doc['fields'] ?? [];
        fputcsv($out, [$doc['source_system'] ?? 'MDW Admin', $doc['source_reference'] ?? ($f['invoice_number'] ?? ''), $f['invoice_number'] ?? '', $f['invoice_date'] ?? '', $f['client_name'] ?? ($doc['client_name'] ?? ''), $f['project_name'] ?? '', $f['subtotal'] ?? '', $f['tax'] ?? '', $f['total_due'] ?? '', $f['due_date'] ?? '', $f['payment_status'] ?? ($doc['status'] ?? ''), $doc['id'] ?? '']);
    }
    fclose($out);
    @file_put_contents(mdw_storage_path('exports') . '/latest-invoice-export.txt', 'Last invoice CSV export: ' . date('Y-m-d H:i:s') . ' | File: ' . $csvName . PHP_EOL, FILE_APPEND);
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . $csvName . '"');
    readfile($exportPath);
    exit;
}
mdw_render_header('Invoice CSV Export');
?>
<section class="panel">
  <h2>Invoice CSV Export</h2>
  <p class="muted">Export saved invoice documents to CSV for your accounting program later. MDW-created invoices use MDW-INV-YYYY-#### source references so they stay separate from ECT orders and Accounting-created invoices.</p>
  <p><a class="button" href="invoices-export.php?download=csv">Download Invoice CSV</a> <a class="button ghost" href="documents.php">Back to Documents</a></p>
</section>
<section class="panel" style="margin-top:20px">
  <h2>Saved Invoices</h2>
  <?php if (!$invoices): ?><p class="muted">No saved invoices yet.</p><?php else: ?>
  <table><thead><tr><th>Invoice</th><th>Client</th><th>Project</th><th>Total</th><th>Status</th><th>Actions</th></tr></thead><tbody>
  <?php foreach(array_reverse($invoices) as $doc): $f=$doc['fields']??[]; ?>
    <tr><td><?php echo mdw_h($f['invoice_number'] ?? ''); ?><br><span class="muted"><?php echo mdw_h($doc['source_system'] ?? 'MDW Admin'); ?></span><br><span class="muted"><?php echo mdw_h($f['invoice_date'] ?? ''); ?></span></td><td><?php echo mdw_h($f['client_name'] ?? ($doc['client_name'] ?? '')); ?></td><td><?php echo mdw_h($f['project_name'] ?? ''); ?></td><td><?php echo mdw_h($f['total_due'] ?? ''); ?></td><td><?php echo mdw_h($f['payment_status'] ?? ($doc['status'] ?? '')); ?></td><td><a class="button ghost" href="document-view.php?id=<?php echo urlencode($doc['id'] ?? ''); ?>">View</a></td></tr>
  <?php endforeach; ?>
  </tbody></table><?php endif; ?>
</section>
<?php mdw_render_footer(); ?>
