<?php
include 'header.php';
include 'erpc_estados_toolbar.php';
include_once 'connect.php';

// Converte o arquivo CSV que o usuário selecionou para utf-8
function utf8_fopen_read($fileName) {
    $fc = iconv('windows-1250', 'utf-8', file_get_contents($fileName));
    $handle=fopen("php://memory", "rw");
    fwrite($handle, $fc);
    fseek($handle, 0);
    return $handle;
}

if (isset($_POST['submit'])) {

	if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
	$filename = explode(".", $_FILES['filename']['name']);
		echo "<h1>" . "Arquivo ". $_FILES['filename']['name'] ." transferido com sucesso para o servidor." . "</h1>";

		echo "<hr>";
		echo "Tipo de arquivo: " . $filename[1];
		echo "<hr>";

		//Verificando se o arquivo é CSV
		if ($filename[1]=='csv'){
			// Importar o arquivo para a base
			// Ignorando a primeira linha -> Cabeçalho
			// $handle = fopen($_FILES['filename']['tmp_name'], "r");
			$handle = utf8_fopen_read($_FILES['filename']['tmp_name']);
			$firstRow = true;

			while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
				if($firstRow)
				{
				$firstRow = false; //Ignorando a primeira linha
				} else {
				$import="insert into erpc_estados( id, ds_estados, id_usuario) values('$data[0]','$data[1]', 1)";

				/*
				$import="INSERT into teste (ds_teste) values('$data[0]')";
				echo "valor=$data[0]<br>";
				echo "$import<br>";*/

				$stmt = mysqli_prepare($conexao, $import) or die(mysqli_error($conexao) . '<br />' . $import);
						mysqli_stmt_execute($stmt) or die(mysqli_error($conexao));
				}
			}

			fclose($handle);

			print "estadoss atualizada(s) com sucesso!" . "<hr><br><br>";

			echo "<a href='erpc_estados_list.php'><button class='btn btn-default' type='button' value='Voltar'>Listas estadoss</button></a>";

			}
		}
	exit;
}

?>

<!-- Nav tabs -->
<ul class="nav nav-tabs" role="tablist">
  <li role="presentation" class="active"><a href="#form1" aria-controls="form1" role="tab" data-toggle="tab">Importar Arquivo CSV</a></li>
  <!--
  <li role="presentation"><a href="#form2" aria-controls="form2" role="tab" data-toggle="tab">Form #2</a></li>
  <li role="presentation"><a href="#form3" aria-controls="form3" role="tab" data-toggle="tab">Form #3</a></li>
  <li role="presentation"><a href="#form4" aria-controls="form4" role="tab" data-toggle="tab">Form #4</a></li>
  -->
</ul>

<!-- Tab panes -->
<div class="tab-content">
  <div role="tabpanel" class="tab-pane fade in active" id="form1">
<form enctype='multipart/form-data' id=validate_custom method=POST action="erpc_estados_importar.php">
  <div class=block>
    <div class=header>
      <h2>Importar estadoss para o ERP</h2>
      <div class="side pull-right"> <button class="btn btn-default btn-clean" onClick="clear_form('#validate_custom');" type=button>Clear form</button>          </div>
    </div>

    <div class="content controls">
      <div class=form-row>
        <div class=col-md-3>Escolha o arquivo:</div>
        <div class=col-md-9><input size='50' class="validate[required]" type='file' accept="application/csv" name='filename'> </div>
      </div>
    </div>
    <div class=footer>
      <div class="side pull-right">
        <div class=btn-group>
			<button class="btn btn-default" type="button" value="Voltar" onClick="window.history.go(-1)" >Voltar</button>
			<button class="btn btn-success" type="submit" value="submit" name="submit">Importar</button>
		</div>
      </div>
    </div>
  </div>
</form>

  </div>

</div>

<?php include 'footer.php';?>
