<?php
$target_dir = "files/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

// Check if file already exists
if (file_exists($target_file)) {
  echo "The file already exists.";

  // Display the URL of the existing file
  $fileUrl = $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . '/' . $target_file;
  echo "<br><br>Existing File URL: <a id='fileUrl' href='http://$fileUrl'>$fileUrl</a>";

  // Botón para copiar al portapapeles
  echo "<button onclick='copyToClipboard()'>Copy URL</button>";

  echo "<strong><h5><li><a href=\"vpn.php\" > Back to Panel</a></li></strong></h5>\n";

  // You may choose to exit the script here or continue with the rest of the checks
  // exit();
}

// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
  echo "Sorry, your file is too large.";
  $uploadOk = 0;
}

// Allow certain file formats
$allowedFormats = ["ovpn", "ovpn", "ovpn", "ovpn"]; // Add or remove allowed formats as needed
if (!in_array($imageFileType, $allowedFormats)) {
  echo "Sorry, only ovpn files are allowed.";
  $uploadOk = 0;
}

// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
  echo "Sorry, your file was not uploaded.";
} else {
  if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
    echo "The file " . htmlspecialchars(basename($_FILES["fileToUpload"]["name"])) . " has been uploaded.";

    // Display the URL of the uploaded file
    $fileUrl = $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . '/' . $target_file;
    echo "<br><br>File URL: <a id='fileUrl' href='http://$fileUrl'>$fileUrl</a>";

    // Botón para copiar al portapapeles
    echo "<button onclick='copyToClipboard()'>Copy URL</button>";

    echo "<strong><h5><li><a href=\"vpn.php\" > Back to Panel</a></li></strong></h5>\n";
  } else {
    echo "Sorry, there was an error uploading your file.";
  }
}
?>

<script>
  function copyToClipboard() {
    var urlElement = document.getElementById('fileUrl');
    var tempInput = document.createElement('input');
    tempInput.value = urlElement.href;
    document.body.appendChild(tempInput);
    tempInput.select();
    document.execCommand('copy');
    document.body.removeChild(tempInput);
    alert('URL copied to clipboard!');

    // Redirigir a la página "vpn.php"
    window.location.href = 'vpn.php';
  }
</script>
