<?php
declare(strict_types=1);

/**
 * Grava uma planilha .xlsx simples (uma aba, cabeçalho em negrito e congelado), sem bibliotecas
 * externas. Números vão como números; o resto como texto.
 */
final class XlsxGravador
{
    /**
     * @param list<string> $cabecalho
     * @param iterable<list<int|float|string|bool|null>> $linhas
     */
    public static function grava(string $destino, string $nomeAba, array $cabecalho, iterable $linhas): void
    {
        $nomeAba = self::nomeDeAba($nomeAba);
        $nCols = max(1, count($cabecalho));
        $larguras = array_map(static fn ($c) => min(60, max(8, mb_strlen((string) $c) + 2)), $cabecalho);

        // a aba é montada num arquivo temporário (os dados podem ter dezenas de milhares de linhas)
        $tmp = tempnam(sys_get_temp_dir(), 'xl');
        if ($tmp === false) {
            throw new RuntimeException('Sem pasta temporária para gravar a planilha.');
        }
        $f = fopen($tmp, 'wb');
        $nLinhas = 1;
        $corpo = self::linhaXml(1, $cabecalho, 1);
        fwrite($f, $corpo);
        foreach ($linhas as $linha) {
            $nLinhas++;
            foreach ($linha as $i => $v) {
                if ($i < $nCols && is_string($v)) {
                    $larguras[$i] = min(60, max($larguras[$i] ?? 8, mb_strlen($v) + 2));
                }
            }
            fwrite($f, self::linhaXml($nLinhas, $linha, 0));
        }
        fclose($f);

        $ultima = XlsxLeitor::letraDaColuna($nCols - 1) . $nLinhas;
        $cols = '';
        foreach ($larguras as $i => $w) {
            $cols .= '<col min="' . ($i + 1) . '" max="' . ($i + 1) . '" width="' . $w . '" customWidth="1"/>';
        }
        $inicioAba = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
            . '<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" '
            . 'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">'
            . '<dimension ref="A1:' . $ultima . '"/>'
            . '<sheetViews><sheetView workbookViewId="0"><pane ySplit="1" topLeftCell="A2" activePane="bottomLeft" state="frozen"/>'
            . '<selection pane="bottomLeft" activeCell="A2" sqref="A2"/></sheetView></sheetViews>'
            . '<sheetFormatPr defaultRowHeight="15"/>'
            . ($cols !== '' ? '<cols>' . $cols . '</cols>' : '')
            . '<sheetData>';
        $fimAba = '</sheetData><pageMargins left="0.7" right="0.7" top="0.75" bottom="0.75" header="0.3" footer="0.3"/></worksheet>';

        $agora = gmdate('Y-m-d\TH:i:s\Z');
        $zip = new ZipArchive();
        if (file_exists($destino)) {
            unlink($destino);
        }
        if ($zip->open($destino, ZipArchive::CREATE) !== true) {
            @unlink($tmp);
            throw new RuntimeException('Não consegui criar a planilha.');
        }
        $zip->addFromString('[Content_Types].xml',
            '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
            . '<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="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>'
            . '<Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>'
            . '<Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>'
            . '<Override PartName="/docProps/core.xml" ContentType="application/vnd.openxmlformats-package.core-properties+xml"/>'
            . '<Override PartName="/docProps/app.xml" ContentType="application/vnd.openxmlformats-officedocument.extended-properties+xml"/>'
            . '</Types>');
        $zip->addFromString('_rels/.rels',
            '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
            . '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
            . '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>'
            . '<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/>'
            . '<Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties" Target="docProps/app.xml"/>'
            . '</Relationships>');
        $zip->addFromString('docProps/core.xml',
            '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
            . '<cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" '
            . 'xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" '
            . 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">'
            . '<dc:creator>Sellout LATAM</dc:creator>'
            . '<dcterms:created xsi:type="dcterms:W3CDTF">' . $agora . '</dcterms:created>'
            . '<dcterms:modified xsi:type="dcterms:W3CDTF">' . $agora . '</dcterms:modified>'
            . '</cp:coreProperties>');
        $zip->addFromString('docProps/app.xml',
            '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
            . '<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/extended-properties">'
            . '<Application>Sellout LATAM</Application></Properties>');
        $zip->addFromString('xl/_rels/workbook.xml.rels',
            '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
            . '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
            . '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/>'
            . '<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>'
            . '</Relationships>');
        $zip->addFromString('xl/workbook.xml',
            '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
            . '<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" '
            . 'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">'
            . '<bookViews><workbookView/></bookViews>'
            . '<sheets><sheet name="' . self::esc($nomeAba) . '" sheetId="1" r:id="rId1"/></sheets>'
            . '</workbook>');
        $zip->addFromString('xl/styles.xml',
            '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
            . '<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">'
            . '<fonts count="2"><font><sz val="11"/><name val="Calibri"/></font>'
            . '<font><b/><sz val="11"/><name val="Calibri"/></font></fonts>'
            . '<fills count="2"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill></fills>'
            . '<borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders>'
            . '<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>'
            . '<cellXfs count="2"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>'
            . '<xf numFmtId="0" fontId="1" fillId="0" borderId="0" xfId="0" applyFont="1"/></cellXfs>'
            . '<cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles>'
            . '</styleSheet>');
        // a aba: começo + corpo (do arquivo temporário) + fim, montados num segundo temporário
        $tmpAba = tempnam(sys_get_temp_dir(), 'xs');
        $fa = fopen($tmpAba, 'wb');
        fwrite($fa, $inicioAba);
        $fc = fopen($tmp, 'rb');
        stream_copy_to_stream($fc, $fa);
        fclose($fc);
        fwrite($fa, $fimAba);
        fclose($fa);
        $zip->addFile($tmpAba, 'xl/worksheets/sheet1.xml');
        $ok = $zip->close();
        @unlink($tmp);
        @unlink($tmpAba);
        if (!$ok) {
            throw new RuntimeException('Não consegui gravar a planilha.');
        }
    }

    /** @param list<int|float|string|bool|null> $valores */
    private static function linhaXml(int $n, array $valores, int $estilo): string
    {
        $s = '<row r="' . $n . '">';
        foreach (array_values($valores) as $i => $v) {
            if ($v === null || $v === '') {
                continue;
            }
            $ref = XlsxLeitor::letraDaColuna($i) . $n;
            $atrEstilo = $estilo ? ' s="' . $estilo . '"' : '';
            if (is_int($v) || (is_float($v) && is_finite($v))) {
                $num = is_int($v) ? (string) $v : json_encode($v);
                $s .= '<c r="' . $ref . '"' . $atrEstilo . '><v>' . $num . '</v></c>';
            } elseif (is_bool($v)) {
                $s .= '<c r="' . $ref . '"' . $atrEstilo . ' t="b"><v>' . ($v ? '1' : '0') . '</v></c>';
            } else {
                $s .= '<c r="' . $ref . '"' . $atrEstilo . ' t="inlineStr"><is><t xml:space="preserve">'
                    . self::esc((string) $v) . '</t></is></c>';
            }
        }
        return $s . '</row>';
    }

    private static function esc(string $s): string
    {
        if (function_exists('mb_scrub')) {
            $s = mb_scrub($s, 'UTF-8');
        }
        // caracteres de controle não são permitidos em XML
        $s = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/', '', $s) ?? '';
        return htmlspecialchars($s, ENT_XML1 | ENT_QUOTES, 'UTF-8');
    }

    private static function nomeDeAba(string $s): string
    {
        $s = preg_replace('/[\[\]:*?\/\\\\]/', ' ', $s) ?? 'Dados';
        $s = trim($s);
        return mb_substr($s === '' ? 'Dados' : $s, 0, 31);
    }
}
