<?php
require_once('../config.php'); 
include_once('excel_read.php');
$mysqli = new mysqli(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
$hide = true;
if(isset($_POST["submit"])) {
  $target_dir = "fisiere/";
  $target_file = $target_dir . basename($_FILES["upload"]["name"]);
  if(move_uploaded_file($_FILES["upload"]["tmp_name"], $target_file)){
      echo 'Fisierul a fost incarcat, urmeaza sa fie procesat.<br />';
      
        $delimiter = "\t";
        $file = new \SplFileObject($target_file);
        while (!$file->eof()) {
            $data[] = $file->fgetcsv($delimiter);
        }
        unset($data[0]);;
        foreach($data as $product){
            if(is_numeric($product[0])){
                $product_id = $product[0];
                $pret = $product[3];
                $pret_special = $product[4];
                $cantitate = $product[2];
                
                //Update pret & stoc
                $update_pq = $mysqli->query(" UPDATE ".DB_PREFIX."product SET `price` = '".$pret."', `quantity` = '".$cantitate."' WHERE `product_id` = '".$product_id."' ");
                $verificare = $mysqli->query(" SELECT * FROM ".DB_PREFIX."product_special WHERE `product_id` = '".$product_id."' ");
                if($verificare->num_rows > 0){
                    $mysqli->query(" UPDATE ".DB_PREFIX."product_special SET `price` = '".$pret_special."' WHERE `product_id` = '".$product_id."' ");
                }else{
                    $mysqli->query(" INSERT INTO ".DB_PREFIX."product_special (`product_id`, `customer_group_id`, `priority`, `price`, `date_start`, `date_end`) VALUES ('".$product_id."', '1', '0', '".$pret_special."', NOW(), NOW() + interval 1 month) ");
                }
            }
        }
      
      $hide = false;
      
  }else{
      echo 'A aparut o eroare la incarcarea fisierului.';
      $hide = true;
  }
}

?>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<?php if($hide):?>
<h3>ATENTIE!</h3>
<p>La incarcarea fisierului se va rescrie urmatoarea informatie:</p>
<ul>
    <li>Pretul produsului</li>
    <li>Pretul special</li>
    <li>Stocul produsului</li>
</ul>
<p>Aceste informatii vor fi rescrise indiferent daca difera sau nu de cele actuale!</p>
<form method="post" enctype="multipart/form-data">
    <label for="upload">Alegeti fisierul</label>
    <input type="file" name="upload" id="upload">
    <input type="submit" value="Incarca fisierul" name="submit">
</form>
<?php endif;?>