<?php
final class ExportService {
    private array $columns;
    public function __construct(private ReportService $reports) { $this->columns = ReportService::ORDER_COLUMNS; }
    public function rows(array $filters): array { return $this->reports->reportRows($filters + ['limit'=>($filters['limit'] ?? 5000)]); }
    public function totals(array $filters): array { return $this->reports->reportTotals($filters); }
    public function selectedColumns(array $filters): array {
        $requested = $filters['columns'] ?? '';
        if (is_array($requested)) $keys = $requested; else $keys = array_filter(array_map('trim', explode(',', (string)$requested)));
        if (!$keys) $keys = ['pedido','data','status','cliente','produto','tipo_certidao','modalidade','entrega','frete','total'];
        return array_values(array_filter($keys, fn($k)=>isset($this->columns[$k])));
    }
    public function log(string $type, array $filters, int $rows): void {
        $uid = $_SESSION['user']['id'] ?? null;
        $st=Database::pdo()->prepare('INSERT INTO export_logs (user_id, export_type, filters_json, rows_count, created_at) VALUES (?, ?, ?, ?, NOW())');
        $st->execute([$uid, $type, json_encode($filters, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES), $rows]);
    }
    public function csv(array $filters): void {
        $rows=$this->rows($filters); $cols=$this->selectedColumns($filters); $totals=$this->totals($filters); $this->log('csv',$filters,count($rows));
        header('Content-Type: text/csv; charset=utf-8'); header('Content-Disposition: attachment; filename="flowreports-pedidos-'.date('Ymd-His').'.csv"');
        $out=fopen('php://output','w'); fprintf($out, chr(0xEF).chr(0xBB).chr(0xBF));
        fputcsv($out, ['FlowReports - resumo'], ';');
        fputcsv($out, ['Pedidos/entrega', $totals['pedidos'], 'Frete', br_money($totals['frete']), 'Total geral', br_money($totals['total_geral'])], ';');
        fputcsv($out, [], ';');
        fputcsv($out, array_map(fn($c)=>$this->columns[$c], $cols), ';');
        foreach($rows as $r) fputcsv($out, array_map(fn($c)=>$r[$c] ?? '', $cols), ';'); exit;
    }
    public function xls(array $filters): void {
        $rows=$this->rows($filters); $cols=$this->selectedColumns($filters); $totals=$this->totals($filters); $this->log('xls',$filters,count($rows));
        header('Content-Type: application/vnd.ms-excel; charset=utf-8'); header('Content-Disposition: attachment; filename="flowreports-pedidos-'.date('Ymd-His').'.xls"');
        echo "\xEF\xBB\xBF"; echo '<html><meta charset="utf-8"><body><h2>FlowReports</h2><table border="1"><tr><th>Pedidos/entrega</th><th>Frete</th><th>Total geral</th></tr><tr><td>'.(int)$totals['pedidos'].'</td><td>'.h(br_money($totals['frete'])).'</td><td>'.h(br_money($totals['total_geral'])).'</td></tr></table><br><table border="1"><tr>';
        foreach($cols as $c) echo '<th>'.h($this->columns[$c]).'</th>'; echo '</tr>';
        foreach($rows as $r){ echo '<tr>'; foreach($cols as $c) echo '<td>'.h($r[$c] ?? '').'</td>'; echo '</tr>'; } echo '</table></body></html>'; exit;
    }
    public function html(array $filters): void {
        $rows=$this->rows($filters); $cols=$this->selectedColumns($filters); $totals=$this->totals($filters); $this->log('html_pdf',$filters,count($rows));
        header('Content-Type: text/html; charset=utf-8');
        $title = $filters['title'] ?? 'Relatório de Pedidos';
        echo '<!doctype html><html lang="pt-BR"><meta charset="utf-8"><title>'.h($title).'</title><style>body{font-family:Arial,sans-serif;margin:28px;color:#172033}.toolbar{margin-bottom:20px}.brand{font-weight:800;font-size:20px}.muted{color:#64748b}.totals{display:grid;grid-template-columns:repeat(3,1fr);gap:12px;margin:18px 0}.total-card{border:1px solid #dbe3ef;border-radius:14px;padding:14px;background:#f8fafc}.total-card span{display:block;color:#64748b;font-size:12px;text-transform:uppercase;font-weight:700}.total-card strong{font-size:24px}table{width:100%;border-collapse:collapse;font-size:11px}th,td{border:1px solid #dbe3ef;padding:6px;vertical-align:top}th{background:#f1f5f9;text-align:left}.right{text-align:right}@media print{.toolbar{display:none}body{margin:12mm}.totals{break-inside:avoid}}</style><body><div class="toolbar"><button onclick="window.print()">Imprimir / salvar PDF</button></div><div class="brand">FlowReports Cartório</div><h1>'.h($title).'</h1><p class="muted">Gerado em '.date('d/m/Y H:i').' • '.count($rows).' registro(s) exibido(s)</p>';
        echo '<div class="totals"><div class="total-card"><span>Pedidos / entrega</span><strong>'.(int)$totals['pedidos'].'</strong></div><div class="total-card"><span>Total de frete</span><strong>'.h(br_money($totals['frete'])).'</strong></div><div class="total-card"><span>Total geral</span><strong>'.h(br_money($totals['total_geral'])).'</strong></div></div><table><thead><tr>';
        foreach($cols as $c) echo '<th>'.h($this->columns[$c]).'</th>'; echo '</tr></thead><tbody>';
        foreach($rows as $r){ echo '<tr>'; foreach($cols as $c){ $v=$r[$c] ?? ''; $class=in_array($c,['frete','total','subtotal_itens'],true)?' class="right"':''; if(in_array($c,['frete','total','subtotal_itens'],true)) $v=br_money($v); echo '<td'.$class.'>'.h($v).'</td>'; } echo '</tr>'; }
        echo '</tbody></table><script>setTimeout(()=>window.print(),700)</script></body></html>'; exit;
    }
    public function docx(array $filters): void {
        if (!class_exists('ZipArchive')) throw new RuntimeException('A extensão ZipArchive não está disponível no PHP. Ative zip no cPanel ou use a exportação HTML/PDF.');
        $rows=$this->rows($filters); $cols=$this->selectedColumns($filters); $totals=$this->totals($filters); $this->log('docx',$filters,count($rows));
        $title=$filters['title'] ?? 'Relatório de Pedidos'; $tmp=tempnam(sys_get_temp_dir(),'docx_'); @unlink($tmp); $zip=new ZipArchive(); $zip->open($tmp, ZipArchive::CREATE);
        $zip->addFromString('[Content_Types].xml','<?xml version="1.0" encoding="UTF-8"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>');
        $zip->addFromString('_rels/.rels','<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>');
        $xml='<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>';
        $xml.=$this->p('FlowReports Cartório', true).$this->p($title, true).$this->p('Gerado em '.date('d/m/Y H:i').' • '.count($rows).' registro(s) exibido(s)');
        $xml.=$this->p('Pedidos/entrega: '.(int)$totals['pedidos'].' | Frete: '.br_money($totals['frete']).' | Total geral: '.br_money($totals['total_geral']), true);
        $xml.='<w:tbl><w:tblPr><w:tblW w:w="0" w:type="auto"/><w:tblBorders><w:top w:val="single"/><w:left w:val="single"/><w:bottom w:val="single"/><w:right w:val="single"/><w:insideH w:val="single"/><w:insideV w:val="single"/></w:tblBorders></w:tblPr><w:tr>';
        foreach($cols as $c) $xml.=$this->tc($this->columns[$c], true); $xml.='</w:tr>';
        foreach($rows as $r){ $xml.='<w:tr>'; foreach($cols as $c){ $v=$r[$c] ?? ''; if(in_array($c,['frete','total','subtotal_itens'],true)) $v=br_money($v); $xml.=$this->tc((string)$v); } $xml.='</w:tr>'; }
        $xml.='</w:tbl><w:sectPr><w:pgSz w:w="16838" w:h="11906" w:orient="landscape"/><w:pgMar w:top="720" w:right="720" w:bottom="720" w:left="720"/></w:sectPr></w:body></w:document>';
        $zip->addFromString('word/document.xml',$xml); $zip->close();
        header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document'); header('Content-Disposition: attachment; filename="flowreports-pedidos-'.date('Ymd-His').'.docx"'); header('Content-Length: '.filesize($tmp)); readfile($tmp); @unlink($tmp); exit;
    }
    private function p(string $text, bool $bold=false): string { return '<w:p><w:r>'.($bold?'<w:rPr><w:b/></w:rPr>':'').'<w:t>'.h($text).'</w:t></w:r></w:p>'; }
    private function tc(string $text, bool $bold=false): string { return '<w:tc><w:p><w:r>'.($bold?'<w:rPr><w:b/></w:rPr>':'').'<w:t>'.h($text).'</w:t></w:r></w:p></w:tc>'; }
}
