<?php
namespace Traits\ExportTo;

use Helpers\Fichier\Fichier;
use Helpers\Log\LogSysteme;
use Helpers\Session\ParseBase1;

trait Csv
{

    public string $urlCsv;

    
    /**
     * @param array<mixed> $input_array
     */
    // phpcs:ignore
    public function convert_to_csv($input_array, string $output_file_name, string $delimiter) :void
    {
        
        if (getenv('TYPEENVIRONNEMENT')=='recette_auto') {
            $nomFichier = LogSysteme::getServerName().'.'.$output_file_name.'.csv';
        } else {
            $nomFichier = LogSysteme::getServerName().'.'.$output_file_name."_".date('Ymd')."_".date('His').'.csv';
        }
        
        header('Content-Type: text/csv');
        header('Content-Disposition: attachement; filename="'.$nomFichier.'"');
        header('Pragma: public');
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Cache-Control: private", false);
        header("Content-Transfer-Encoding: binary");
        header('Content-Encoding: UTF-8');
        header("Expires: 0");
        
        $temp_memory = Fichier::fopen('php://output', 'w');
        
        foreach ($input_array as &$line) {
            // use the default csv handler
            
            fprintf($temp_memory, chr(0xEF).chr(0xBB).chr(0xBF));
            
            fputcsv($temp_memory, (array)$line, $delimiter);
        }
        
        fclose($temp_memory);
        // modify the header to be CSV format
        // output the file to be downloaded
    }

    
    /**
     * @param mixed $input_array
     * @param mixed $output_file_name
     * @param mixed $delimiter
     * @param mixed $keyColonne
     */
    // phpcs:ignore
    public function convert_to_csv_V2($input_array, $output_file_name, $delimiter, $keyColonne = []) :string
    {
        if (getenv('TYPEENVIRONNEMENT')=='recette_auto') {
            $nomFichier = LogSysteme::getServerName().'.'.$output_file_name.'.csv';
        } else {
            $nomFichier = LogSysteme::getServerName().'.'.$output_file_name."_".date('Ymd')."_".date('His').'.csv';
        }

        $temp_memory = Fichier::fopen((new ParseBase1())->getRep()->tmp.$nomFichier, 'w');

        fprintf($temp_memory, chr(0xEF).chr(0xBB).chr(0xBF));
        
        if ($keyColonne) {
            fputcsv($temp_memory, (array)$keyColonne, $delimiter);
        }

        foreach ($input_array as &$line) {
            fputcsv($temp_memory, (array)$line, $delimiter);
        }
        
        fclose($temp_memory);
        
        
        $this->urlCsv =  Fichier::URLDownload($nomFichier);
        
        return $nomFichier;
        // modify the header to be CSV format
        // output the file to be downloaded
    }
}
