<?php
  require 'autoload_qr.php';

  use Zxing\QrReader;

  $archivo = "";
  $texto = "";
  $error = "";

  if(isset($_FILES["imagenQR"])){
    if($_FILES["imagenQR"]["error"] != UPLOAD_ERR_OK){
      $error = "No se pudo subir la imagen";
    } else {
      $info = @getimagesize($_FILES["imagenQR"]["tmp_name"]);
      if($info === false){
        $error = "El archivo no es una imagen valida";
      } else {
        if(!file_exists("uploads")){
          mkdir("uploads", 0777);
        }
        $archivo = "uploads/qr_" . uniqid() . ".png";
        $mime = strtolower($info["mime"]);
        if(in_array($mime, array("image/avif", "image/heic", "image/heif"))){
          exec("convert " . escapeshellarg($_FILES["imagenQR"]["tmp_name"]) . " " . escapeshellarg($archivo));
        } else {
          move_uploaded_file($_FILES["imagenQR"]["tmp_name"], $archivo);
        }

        if(!file_exists($archivo)){
          $error = "No se pudo guardar la imagen en uploads/";
        } else {
          try {
            $qr = new QrReader($archivo);
            $resultado = $qr->text();
          } catch (Throwable $e) {
            $resultado = false;
            $error = htmlspecialchars($e->getMessage());
          }

          if(is_string($resultado) && $resultado != ""){
            $texto = $resultado;
          } else if($error == ""){
            $error = "La imagen no contiene un codigo QR legible";
          }
        }
      }
    }
  }
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Leer QR</title>
</head>
<body>
    <h3>2. LEER CODIGO QR</h3>
    <form action="leer.php" method="post" enctype="multipart/form-data">
        Imagen con QR: <input type="file" name="imagenQR" accept="image/*" required>
        <input type="submit" value="LEER QR">
    </form>

    <?php
      if($archivo != ""){
        echo "<p><img src='" . $archivo . "' width='220'></p>";
      }
      if($texto != ""){
        echo "<p>Contenido del QR: <b>" . htmlspecialchars($texto) . "</b></p>";
      }
      if($error != ""){
        echo "<p>" . $error . "</p>";
      }
      echo "<p><a href='indice.php'>Volver al inicio</a></p>";
    ?>
</body>
</html>
