<?php
include('dbconect.php');
require_once('vendor/php-excel-reader/excel_reader2.php');
require_once('vendor/SpreadsheetReader.php');

if (isset($_POST["import"]))
{
    
$allowedFileType = ['application/vnd.ms-excel','text/xls','text/xlsx','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];
  
  if(in_array($_FILES["file"]["type"],$allowedFileType)){

        $targetPath = 'subidas/'.$_FILES['file']['name'];
        move_uploaded_file($_FILES['file']['tmp_name'], $targetPath);
        
        $Reader = new SpreadsheetReader($targetPath);
        
        $sheetCount = count($Reader->sheets());
        for($i=0;$i<$sheetCount;$i++)
        {
            
            $Reader->ChangeSheet($i);
            
            foreach ($Reader as $Row)
            {
                 
                $codigo = "";
                if(isset($Row[0])) {
                    $codigo = mysqli_real_escape_string($con,$Row[0]);
                }
                
                $nombre = "";
                if(isset($Row[1])) {
                    $nombre = mysqli_real_escape_string($con,$Row[1]);
                }
				 $precio_compra = "";
                if(isset($Row[2])) {
                    $precio_compra = mysqli_real_escape_string($con,$Row[2]);
                }
				
			     $precio_venta = "";
                if(isset($Row[3])) {
                    $precio_venta = mysqli_real_escape_string($con,$Row[3]);
                }
				
				  $unidad = "";
                if(isset($Row[4])) {
                    $unidad = mysqli_real_escape_string($con,$Row[4]);
                }
				
				  $stock = "";
                if(isset($Row[5])) {
                    $stock = mysqli_real_escape_string($con,$Row[5]);
                }
				
				  $created_user = "";
                if(isset($Row[6])) {
                    $created_user = mysqli_real_escape_string($con,$Row[6]);
                }
				
				  $created_date = "";
                if(isset($Row[7])) {
                    $created_date = mysqli_real_escape_string($con,$Row[7]);
                }
				
				  $updated_user = "";
                if(isset($Row[8])) {
                    $updated_user = mysqli_real_escape_string($con,$Row[8]);
                }
				
				  $updated_date = "";
                if(isset($Row[9])) {
                    $updated_date = mysqli_real_escape_string($con,$Row[9]);
                }
				
				  $precio_compra2 = "";
                if(isset($Row[10])) {
                    $precio_compra2 = mysqli_real_escape_string($con,$Row[10]);
                }
				/*
				CREATE TABLE `medicamentos2`
				(
				id int AUTO_INCREMENT,
				`codigo` varchar(10) NOT NULL,
				`nombre` varchar(50) NOT NULL,
				`unidad` varchar(20) NOT NULL,
				`stock` int(11) NOT NULL,
				`created_user` int(3) NOT NULL,
				`created_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
				`updated_user` int(3) NOT NULL,
				`updated_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
				`costo` varchar(11) NOT NULL,
				 PRIMARY KEY (id))
				 ENGINE=InnoDB DEFAULT CHARSET=latin1;
				 
				)*/
				
				
               
                
                if (!empty($codigo) || !empty($nombre) || !empty($precio_compra) || !empty($precio_venta) || !empty($unidad) || !empty($stock) || !empty($created_user) || !empty($created_date) || !empty($updated_user) || !empty($updated_date)|| !empty($precio_compra2) )                         
					{
                    $query = "insert into medicamentos (codigo,nombre,precio_compra,precio_venta,unidad,stock,created_user,created_date,updated_user,updated_date,precio_compra2) 
					          values('".$codigo."','".$nombre."','".$precio_compra."','".$precio_venta."','".$unidad."','".$stock."','".$created_user."','".$created_date."','".$updated_user."','".$updated_date."','".$precio_compra2."')";
                    $resultados = mysqli_query($con, $query);
                
                    if (!empty($resultados)) {
                        $type = "success";
                        $message = "Excel importado correctamente";
                    } else {
                        $type = "error";
                        $message = "Hubo un problema al importar registros";
                    }
                }
             }
        
         }
  }
  else
  { 
        $type = "error";
        $message = "El archivo enviado es invalido. Por favor vuelva a intentarlo";
  }
}
?>
<!doctype html>
<html lang="es">
<style type="text/css">
  .btn-primary-spacing {
    margin-right: 5px;    
  }
</style>

<section class="content-header">
  <h1>
    <i class="fa fa-sign-in icon-title"></i> Importar archivo de productos 
 
  </h1>
</section>

<!-- Begin page content -->

<div class="container">
 
  <hr>
  <div class="row">
    <div class="col-12 col-sm-12"> 
      <!-- Contenido -->
    
 
        <form action="" method="post"
            name="frmExcelImport" id="frmExcelImport" enctype="multipart/form-data">
            <div>
                <label>Elija Archivo Excel</label> <input type="file" name="file"
                    id="file" accept=".xls,.xlsx">
                <button type="submit" id="submit" name="import"
                    class="btn-submit">Importar Registros</button>
        
            </div>
        
        </form>
        
   
    <div id="response" class="<?php if(!empty($type)) { echo $type . " display-block"; } ?>"><?php if(!empty($message)) { echo $message; } ?></div>
    
         
<?php
    $sqlSelect = "SELECT * FROM medicamentos";
    $result = mysqli_query($con, $sqlSelect);

if (mysqli_num_rows($result) > 0)
{
?>
        
   <table id="dataTables" class="table table-bordered table-striped table-hover">
       <thead>
              <tr>
			 
                <th class="center">Codigo</th>
                <th class="center">Nombre</th>
				<th class="center">Unidad</th>
                <th class="center">Stock</th>
				<th class="center">Costo</th>
               
              </tr>
            </thead>
<?php
    while ($row = mysqli_fetch_array($result)) {
?>                  
        <tbody>
        <tr>
		   
            <td><?php  echo $row['codigo']; ?></td>
            <td><?php  echo $row['nombre']; ?></td>
			<td><?php  echo $row['unidad']; ?></td>
            <td><?php  echo $row['stock']; ?></td>
            <td><?php  echo $row['precio_compra2']; ?></td>
          
        </tr>
<?php
    }
?>
        </tbody>
    </table>
<?php 
} 
?>
      <!-- Fin Contenido --> 
    </div>
  </div>
  <!-- Fin row --> 

  
</div>


<!-- Bootstrap core JavaScript
    ================================================== --> 
<!-- Placed at the end of the document so the pages load faster --> 

<script src="dist/js/bootstrap.min.js"></script>
</body>
</html>