<?php

include "catchAuthors.php";

header ('Content-type: text/html; charset=UTF-8');

$server = "localhost";
$user = "area_root";
$pass = "Legiao123*";
$db = "area_poisson";
$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; */
  
    mysqli_query($connect, "SET character_set_results = 'utf8', character_set_client = 'utf8', character_set_connection = 'utf8', character_set_database = 'utf8', character_set_server = 'utf8'");

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

  if($result == true) {
    ?>
            <script>
                window.location.href = "https://area.editorapoisson.com.br/area-clientes/pages/articleSuccess.php";
            </script>
            <?php
    mysqli_close($connect);
  } else {
    echo (mysqli_error($connect));
    mysqli_close($connect);
  }  
}
?>