<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

/**
 * XLSX generation via PhpSpreadsheet, already bundled by Moodle core
 * (lib/phpspreadsheet) — no new dependency needed for this format.
 *
 * @package    local_kid
 */

namespace local_kid\local;

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

defined('MOODLE_INTERNAL') || die();

class xlsx_service {

    /**
     * Generic tabular export shared by future dashboard sub-views and CAPP —
     * the exact same row set an HTML table was built from, never a
     * separately-derived query, so the export always matches what was
     * actually on screen for the active filters.
     *
     * @param string[] $headers
     * @param array<int, array<string, mixed>> $rows each row's values used
     *        in their original array order (associative keys are only for
     *        the HTML template's readability).
     * @param bool $freezeheader freeze row 1 so it stays visible while
     *        scrolling — optional, off by default so every existing caller
     *        keeps its current output unchanged.
     * @param bool $autofilter add an Excel autofilter over the full range —
     *        same rationale, optional and off by default.
     */
    public static function generic_table(
        array $headers,
        array $rows,
        bool $freezeheader = false,
        bool $autofilter = false
    ): Spreadsheet {
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $sheet->fromArray($headers, null, 'A1');

        $rownum = 2;
        foreach ($rows as $row) {
            $sheet->fromArray(array_values($row), null, 'A' . $rownum);
            $rownum++;
        }

        $lastcol = chr(ord('A') + count($headers) - 1);
        foreach (range('A', $lastcol) as $col) {
            $sheet->getColumnDimension($col)->setAutoSize(true);
        }

        if ($freezeheader) {
            $sheet->freezePane('A2');
        }
        if ($autofilter) {
            $lastrow = max(1, $rownum - 1);
            $sheet->setAutoFilter("A1:{$lastcol}{$lastrow}");
        }

        return $spreadsheet;
    }

    /**
     * Streams a spreadsheet as an XLSX download and ends the request — the
     * calling page must not have already emitted output ($OUTPUT->header()
     * etc.), same convention as any other Moodle file-download script.
     */
    public static function send(Spreadsheet $spreadsheet, string $filename): void {
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $filename . '"');
        header('Cache-Control: max-age=0');

        $writer = new Xlsx($spreadsheet);
        $writer->save('php://output');
        exit;
    }
}
