<?php
// $data = $button->getCurrentRecord();  // this in code by button

// Delete all ile temporal
function deleteAllFilesToDirectory(string $directory){
    $dir = $directory;
    if(file_exists($dir)){
        $di = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS);
        $ri = new RecursiveIteratorIterator($di, RecursiveIteratorIterator::CHILD_FIRST);
        foreach ( $ri as $file ) {
            $file->isDir() ?  rmdir($file) : unlink($file);  
            // if ( $file->isDir()) {  echo "dir.: ".$file."\n"; } else { echo "file: ".$file."\n"; }
        }
    }   
}

$comment = '';

// Create temporal files and Dir.
$temp_directory = tempnam(sys_get_temp_dir(), 'imp');
unlink($temp_directory); // Elimino fichero temporal
$temp_directory =str_replace('.','_',$temp_directory);    // Quito "." en Windows

$temp_zip = str_replace('_tmp','',$temp_directory).".zip";   // Name file ZIP
mkdir($temp_directory,0700);  // directorio de exportación
$temp_directory_image = $temp_directory."/image";
$temp_csv = $temp_directory."/export.csv";                  // Name file CSV

// Create Zip file
$fpz = fopen($temp_zip, 'w');
fwrite($fpz,$data['archive']);
fclose($fpz);

// Extract ZIP file
$za = new ZipArchive();
$za->open($temp_zip);
$za->extractTo($temp_directory.'/');
$za->close();

// Load file csv
$data_arr = array();
$row = 1;
if (($handle = fopen($temp_csv , "r")) !== FALSE) {
    while (($data2 = fgetcsv($handle, 0, ",")) !== FALSE) {
        $num = count($data2);
        $commnet .= "  $num fields in line $row \n";
        if ($row == 1){  // Head
            $data_head = $data2;
        } else {
            for ($c=0; $c < $num; $c++) {
                $data_arr[$row][$data_head[$c]] = $data2[$c];
            }
        }
        $row++;
    }
    fclose($handle);
}

// Manager All new record by file CSV
foreach ($data_arr as &$new_record) {

    $image = Null;
    $name_file = $temp_directory_image."/image_".$new_record['id'];
    foreach (glob($name_file .".*") as $temp_file) {
        $image = file_get_contents($temp_file);  
    }

    // Prepare INSERT new Record
    // All fields: name, addDate, precio, image, filename

    $data3 = array();
    $data3["name"] = $new_record['name'];
    $date_aux = DateTime::createFromFormat('d/m/Y', $new_record['addDate']);
    $error = DateTime::getLastErrors();
    $data3["addDate"]  = date_format($date_aux,'Y-m-d');
    $data3["precio"] =  floatval(str_replace(',', '.', str_replace('.', '', $new_record['precio'])));
    $data3["image"] = $image;
    $data3["filename"] = $new_record['filename'];

    DB::Insert("zip_user", $data3);  // Insert new record in data base
    if (DB::LastError() <> ''){
        $comment .= DB::LastError()."in record with ID = ".$new_record['id']."\n";
    }
}

// Delete Temporal files
deleteAllFilesToDirectory($temp_directory);  // Delete All file temporal
rmdir($temp_directory);
unlink($temp_zip);  // delete file zip

// Update Archive
$data4 = array();
$keyvalues = array();
$data4["comment"] = $comment;
$data4["status"]  = "1";
$keyvalues["id"] = $data['id'];
DB::Update("zip_archive", $data4, $keyvalues );

