<?php
namespace Traits\ExportTo;

use Helpers\Fichier\Fichier;
use Helpers\Log\LogSysteme;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;

trait Excel
{
    
    /**
     * @param array<mixed> $input_array
     * @param string $output_file_name
     * @param mixed $keyColonne
     * @param mixed $noKeyColonne
     */
    // phpcs:ignore
    public function convert_to_excel($input_array, $output_file_name, $keyColonne = [], $noKeyColonne = false, bool $timestamp = true) :string
    {

        $obj = new Spreadsheet();
        $obj->getProperties()->setTitle("export")->setDescription("none");
        
        $obj->setActiveSheetIndex(0);
        // Récupération des noms de champs dans un tableau
        
        if (!$noKeyColonne) {
            if ($keyColonne) {
                $keys = $keyColonne;
            } else {
                if (count($input_array) > 0) {
                    $keys=array_keys($input_array[0]);
                } else {
                    $keys = [];
                }
            }
            // Insertion de la ligne d'entête du tableau
            $col = 1;
            foreach ($keys as &$key) {
                $obj->getActiveSheet()->setCellValueByColumnAndRow($col, 1, $key);
                $col++;
            }
            $row = 2;
        } else {
            $row = 1;
        }
        
        // Insertion des Datas
      
        foreach ($input_array as &$data) {
            $col = 1;
            foreach ($data as &$field) {
                $obj->getActiveSheet()->setCellValueByColumnAndRow($col, $row, trim($field));
                $col++;
            }
            $row++;
        }
        
        $obj->setActiveSheetIndex(0);

        if (getenv('TYPEENVIRONNEMENT')=='recette_auto') {
            $timerCreationFichier = "";
        } else {
            $timerCreationFichier = "_".date('Ymd')."_".date('His');
        }
        
        $nomFichier = $_SESSION['NomFichier'] = $output_file_name.(($timestamp)?$timerCreationFichier:'').'.xlsx';
        
        // @phpstan-ignore-next-line
        $this->urlExcel = Fichier::URLDownload($nomFichier);
        
        $objWriter = IOFactory::createWriter($obj, 'Xlsx');
        $objWriter->save($this->urlExcel);
      
        return $nomFichier;
    }
}
