<?php
include'app/config.php';
$userId=$_SESSION["idUser"];

//Get avatar pic from userId
function getAvatar($userId, $db) {
  $getAvatar = $db->query("SELECT profile_pic FROM users WHERE id='$userId';");
  $resultGetAvatar = $getAvatar->fetchColumn();
  return $resultGetAvatar;
}

//Uppdate mysql
function updateMysqlTable($db, $sql, $userId){
  try {
    $count = $db->exec($sql);
    $db = null;        // Disconnect
  }
  catch(PDOException $e) {
    echo $e->getMessage();
  }
}

//show avatar
echo '<img src="assets/avatars/'.getAvatar($userId, $db).'" id="avatar" height="60" width="60" alt="" />';

//Show/hide answer depend on click
if (empty($_GET['ChangeProfilePic'])) {
  echo '<a href="loginsuccess.php?ChangeProfilePic=pic">Byt profilbild</a>';
} else {
  echo '<a href="loginsuccess.php">Uppdatera bild</a>';
}


//Uppload new avatar form
if (!empty($_GET['ChangeProfilePic'])) {
  echo '<form action="" id="addAvatar" method="post" enctype="multipart/form-data">';
  echo '  <input type="file" name="file[]" multiple accept=".jpg, .png"><br>';
  echo '  <input type="submit" value="Ladda upp bild">';
  echo '</form>';
}


//Process and upload new avatar
if (($_SERVER["REQUEST_METHOD"] === "POST") &&  (!empty($_GET['ChangeProfilePic']))){
print_r($_FILES["file"]);
  $prefix = "Inget";
  $imageData = $_FILES["file"];
  foreach ($imageData["name"] as $i => $imageName) {
    $tmp = $imageData["tmp_name"][$i];
    if ((exif_imagetype($tmp) === 2) || (exif_imagetype($tmp) === 3)) {
      $ext = strrchr($imageName, ".");
      $newName = rand(1,10000) . $ext;
      move_uploaded_file($tmp, "assets/avatars/$newName");
      $sql = "UPDATE `users` SET profile_pic='$newName' WHERE id=$userId;";
      updateMysqlTable($db, $sql, $userId);
      print "Din fil är uppladdad";

    } else {
      print "Bilden måste vara .jpg eller .png.";
    }
  }
}
