<?php
namespace App;

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xls;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;

class Excel {
    public static function newSpreadsheet(): Spreadsheet {
        $spreadsheet = new Spreadsheet();
        $spreadsheet->getProperties()->setCreator('Ali Bot')->setTitle('Dataset');
        return $spreadsheet;
    }
    public static function saveXls(Spreadsheet $spreadsheet, string $path): void {
        $writer = new Xls($spreadsheet);
        $dir = dirname($path);
        if (!is_dir($dir)) mkdir($dir, 0775, true);
        $writer->save($path);
    }
    public static function load(string $path): \PhpOffice\PhpSpreadsheet\Spreadsheet {
        return IOFactory::load($path);
    }
    public static function setRowValues($sheet, int $row, array $values, string $startCol = 'A'): void {
        $colIndex = Coordinate::columnIndexFromString($startCol);
        foreach ($values as $v) {
            $sheet->setCellValueByColumnAndRow($colIndex, $row, $v);
            $colIndex++;
        }
    }
}
