<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// Check if the form has been submitted
if (isset($_POST["submit"])) {

  $panel_id = $_POST['panel_id'];
  $folderName = $_POST['folderName'];
  $target_dir = "../front-end/panels/" . $folderName;

  if (!file_exists($target_dir)) {
    mkdir($target_dir, 0777, true);
  }

  $fi = new FilesystemIterator($target_dir, FilesystemIterator::SKIP_DOTS);
  $fileCount = basename(iterator_count($fi));
  $countfiles = count($_FILES['fileToUpload']['name']);
  $totalFileUploaded = 0;
  for ($i = 0; $i < $countfiles; $i++) {
    $fileName = $_FILES['fileToUpload']['name'][$i];
    $target_file = $target_dir . "/" . $fileName;
    ## extension
    $extension = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
    ## File upload allowed extensions
    $valid_extensions = array("jpg", "jpeg", "png");
    $fileCount++;
    $orderer = $target_dir . "/" . $fileCount . ".jpg";
    ## Check file extension
    if (in_array(strtolower($extension), $valid_extensions)) {
      ## Upload file
      if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'][$i], $orderer)) {

        // File upload succeeded, update the file count in the database
        $dbhost = "localhost";
        $dbname = "manga";
        $dbuser = "root";
        $dbpass = "";
        // Connect to the database
        $conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);

        // Check if the connection succeeded
        if ($conn->connect_error) {
          die("Connection failed: " . $conn->connect_error);
        }

        // Get the current file count from the database
        $sql = "SELECT panels FROM panels";
        $result = $conn->query($sql);
        if (!$result) {
          die("Error executing query: " . $conn->error);
        }
        $row = $result->fetch_assoc();
        $panels = $row["panels"];

        // Increment the file count and update the database
        $sql = "UPDATE panels SET panels=$fileCount WHERE id=$panel_id";
        $conn->query($sql);


        //Close the database connection
        $conn->close();
        // Redirect the user back to the main page
        $totalFileUploaded++;
      } else {
        // File upload failed, display an error message
        echo "File upload failed.";
      }
    } else {
      // uploaded file not allowed, display an error message
      echo "File not an image (jpg, jpeg, png allowed)";
    }
  }

  echo "Total File(s) uploaded : " . $totalFileUploaded;
  echo "Total Files in directory : " . $fileCount;

  header("Location: ../front-end/index.html");
  exit;
}

//if (isset($_POST["delete"])) {

//}