<?php
require_once __DIR__ . '/../inc/helpers.php';
require_once __DIR__ . '/../inc/docs.php';
require_login();
ensure_part2_tables();
if(!is_admin()){ http_response_code(403); exit('Solo admin'); }

$type = $_GET['type'] ?? 'quote';
if(!in_array($type, ['quote','invoice'], true)){ http_response_code(400); exit('type inválido'); }

$fn = $type==='invoice' ? 'facturas.csv' : 'presupuestos.csv';
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="'.$fn.'"');

$out = fopen('php://output', 'w');
fputcsv($out, ['id','doc_type','doc_code','client_id','issue_date','due_date','status','subtotal','tax_total','total','notes']);
$st = db()->prepare("SELECT id, doc_type, doc_code, client_id, issue_date, due_date, status, subtotal, tax_total, total, notes FROM documents WHERE doc_type=? ORDER BY id ASC");
$st->execute([$type]);
while($row = $st->fetch()){
  fputcsv($out, $row);
}
fclose($out);
exit;
