<?php

include "catchAuthors.php";

$server = "localhost";
$user = "root";
$pass = "";
$db = "poisson_area";
$connect = mysqli_connect($server,$user,$pass,$db);

$mysqli = new mysqli($server, $user, $pass, $db);

$mysqli->set_charset("utf8");

if(mysqli_connect_errno()){
    die("Conexão falhou: ".mysqli_connect_errno());
}

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

  $idArt = $_POST['id']; /* id do artigo */

  $sql = "UPDATE myblob SET ";

  if(!empty($_POST['nomeArtigo'])){
    $sql .= "nome_artigo='".$_POST['nomeArtigo']."', ";
  }

  for($i=1; $i<=15;$i++) {
    if(!empty($autores[$i])){
      $sql .= "autor$i='$autores[$i]', ";
    }
    if(!empty($cpfAutores[$i])){
      $sql .= "cpfautor$i='$cpfAutores[$i]', ";
    }
    if(!empty($miniAutores[$i])){
      $sql .= "miniautor$i='$miniAutores[$i]', ";
    }
    if(!empty($emailAutores[$i])){
      $sql .= "emailautor$i='$emailAutores[$i]', ";
    }
  }

  if(!empty($_FILES['file'])){
    $fileNameToValidate = $_FILES['file']['name'];
    $fileExt = explode('.',$fileNameToValidate);
    $fileActualExt = strtolower(end($fileExt));
    $fileError = $_FILES['file']['error'];
    $fileSize = $_FILES['file']['size'];
    $allowed = array('doc','docx','pdf');

    if (in_array($fileActualExt,$allowed)) {
      if ($fileError === 0) {
        
        $file = $_FILES['file'];
        $filePath = "uploads/" . $file['name'];
        $fileName = $_FILES['file']['name'];
        $nomeArt = $_POST['nomeArtigo'];
        move_uploaded_file($file['tmp_name'], $filePath);

        $sql .= "nome_arquivo='$fileName', filepath='$filePath' ";
      }else {
        ?><script>window.alert("Verifique a extensão do arquivo.")</script><?php
      }
    }
  }
  
  $sql = rtrim($sql,", ");
  $sql .= " WHERE id='$idArt';";
  /* echo $sql; */

  $result = mysqli_query($connect,$sql);

  if($result == true) {
    header('Location: ./pages/alterarSuccess.php');
    mysqli_close($connect);
  } else {
    echo (mysqli_error($connect));
    mysqli_close($connect);
  }  
}
?>