<?php
error_reporting(E_ALL);
set_time_limit(0);
ini_set('memory_limit', '2048M');
ini_set('apc.ttl', '0');
ini_set('apc.shm_size', '2048M');


date_default_timezone_set('Europe/London');
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<title>Import Produktow z XLS</title>

</head>
<body>

<h1>Import Produktow z XLS</h1>
<form action="index.php" method="post" enctype="multipart/form-data">
    Wybierz plik XLS z produktami do importu:
    <input type="file" name="fileToUpload" id="fileToUpload"><br>
    <input type="hidden" value="EcmProducts" name="module">
    <input type="hidden" value="import" name="action">
    <input type="submit" value="Wyślij" name="submit">
    <input type="hidden" value="1" name="sended">
</form>
<?php

$uploaded=false;
if($_POST["sended"]=='1') {

$target_dir = "modules/EcmProducts/cards/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image




// Check if file already exists
if (file_exists($target_file)) {
    echo "Plik już istnieje!";
    $uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 50000000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}

// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
       // echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
        $uploaded=true;
    } else {
        echo "Nie można wrzucić pliku!";
    }
}
} else {
    echo 'nic@';
}
if($uploaded==true){
    /** Include path **/
    set_include_path(get_include_path() . PATH_SEPARATOR . '/cards/');
    /** PHPExcel_IOFactory */
    
    include 'modules/EcmProducts/cards/PHPExcel/IOFactory.php';
    $inputFileName =$target_file;
    echo 'Loading file ',pathinfo($inputFileName,PATHINFO_BASENAME),' using IOFactory to identify the format<br />';
    $objPHPExcel = PHPExcel_IOFactory::load($inputFileName);
    $i = 0;
    $files=array();
    foreach ($objPHPExcel->getActiveSheet()->getDrawingCollection() as $drawing) {
        if ($drawing instanceof PHPExcel_Worksheet_MemoryDrawing) {
            ob_start();
            call_user_func(
            $drawing->getRenderingFunction(),
            $drawing->getImageResource()
            );
            $imageContents = ob_get_contents();
            ob_end_clean();
            switch ($drawing->getMimeType()) {
                case PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_PNG :
                    $extension = 'png'; break;
                case PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_GIF:
                    $extension = 'gif'; break;
                case PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_JPEG :
                    $extension = 'jpg'; break;
            }
        } else {
            $zipReader = fopen($drawing->getPath(),'r');
            $imageContents = '';
            while (!feof($zipReader)) {
                $imageContents .= fread($zipReader,1024);
            }
            fclose($zipReader);
            $extension = $drawing->getExtension();
        }
        $path='modules/EcmProducts/cards/images/';
        $myFileName ='00_Image_'.create_guid().++$i.'.'.$extension;
       
        $files[$i]['path']=$path.''.$myFileName;
        $files[$i]['name']=$myFileName;
        $myFileName=$path.$myFileName;
        file_put_contents($myFileName,$imageContents);
    }
    
    echo '<hr />';
    $sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
    if(count($sheetData)>1){
        $i=1;
        foreach ($sheetData as $key=>$val){
            if($key==1 || $val['A']=='')continue;
            echo "raz";
           $p= new EcmProduct();
           $p->name=$val["C"];
           $p->code=$val["A"];
           $p->efficiency=$val["B"];
           $p->unit_id='3';
           $p->vat_id='28079566-b825-e38f-9993-4ccc7b781de5';
           if($val["E"]==1){
               $p->product_picture=$files[$i]['name'];
               $i++;
               move_uploaded_file($files[$i]['path'],'modules/EcmProducts/upload/images/'.$files[$i]['name']);
           }
           $id=$p->save();
           $db=$GLOBALS['db'];
           $db->query("insert into ecmprices_ecmproducts values ('".create_guid()."','44ac3ec1-d60f-195d-29d7-406defa32453','".$id."','".$val["D"]."')");
           echo '"'.$id.'",';
          
        }
    }
//   var_dump($sheetData);
   
}


?>
<body>
</html>