<?php
namespace Traits\ExportTo;

use Helpers\Fichier\Fichier;
use Helpers\Log\LogSysteme;

trait Csv
{

    public $urlCsv;

    // phpcs:ignore
    public function convert_to_csv($input_array, $output_file_name, $delimiter)
    {
        
        
        $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 = 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
    }

    // phpcs:ignore
    public function convert_to_csv_V2($input_array, $output_file_name, $delimiter, $keyColonne = [])
    {
        
        $nomFichier = LogSysteme::getServerName().'.'.$output_file_name."_".date('Ymd')."_".date('His').'.csv';

        $temp_memory = fopen($_SESSION['dir_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
    }
}
