<?php
session_start();
if(!isset($_SESSION['emailadd'])){
 header("Location: index.php");
}

include 'connect.php';
include("header.php");
include("footer.php");
include("nav.php");

// Get a list of available document numbers
$query = "SELECT pvno AS docno FROM tbl_bankout
          ORDER BY docno ASC";
$result = mysqli_query($conn, $query);

// Initialize an array to store the document numbers
$docnos = array();
while ($row = mysqli_fetch_assoc($result)) {
    $docnos[] = $row['docno'];
}


if (isset($_FILES["file"]) && $_FILES["file"]["error"] == 0 && in_array($_POST['docno'], $docnos)) {
    $target_dir = "/var/www/shared_folder/";
    $target_file = $target_dir . basename($_FILES["file"]["name"]);

    // Check if file already exists
    if (file_exists($target_file)) {
        echo "Error: File already exists";
        $upload_ok = false;
    }

    // Check file size
    if ($_FILES["file"]["size"] > 5000000) { // 5MB limit
        echo "Error: File size too large";
        $upload_ok = false;
    }

    // Allow only certain file types
    $allowed_types = array("pdf", "doc", "docx", "txt");
    $file_type = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
    if (!in_array($file_type, $allowed_types)) {
        echo "Error: Invalid file type";
        $upload_ok = false;
    }

    if ($upload_ok) {
        // File uploaded successfully, insert file information into the sup_supdoc table
        $docno = $_POST['docno'];
        $filename = basename($_FILES["file"]["name"]);
        $uploaddate = date('Y-m-d H:i:s'); // Assuming uploaddate is the current date/time

        // Get the highest sequence number for the current document number
        $query = "SELECT MAX(seqno) AS max_seqno FROM bankout_supdoc WHERE docno = '$docno'";
        $result = mysqli_query($conn, $query);
        $row = mysqli_fetch_assoc($result);
        $seqno = $row['max_seqno'] + 1; // Increment the sequence number by 1

        // Insert file information into the sup_supdoc table
        $sql = "INSERT INTO bankout_supdoc (docno, seqno, filename, uploaddate) VALUES ('$docno', '$seqno', '$filename', '$uploaddate')";
        if (mysqli_query($conn, $sql)) {
            echo "The file " . htmlspecialchars($filename) . " has been uploaded and its information has been added to the sup_supdoc table.";
        } else {
            echo "Sorry, there was an error uploading your file.";
        }

        // Close the database connection
        mysqli_close($conn);

        header("Location: uploadbank.php"); // Redirect back to upload.php
        exit; // Exit the script to prevent any further output
    } else {
        // Error while uploading file
        echo "Sorry, there was an error uploading your file.";
    }
}

?>
<html>
<head>
  <title>Upload Document - Perbelanjaan</title>
  <link rel="stylesheet" type="text/css" href="style.css">
</head>
<main>
  <div class="container">
    <h2>Upload Document - Perbelanjaan tunai / bank</h2>
    <form method="post" action="" enctype="multipart/form-data">
      <div class="form-group">
        <div>
          <label for="docno">Document Number:</label>
          <select id="docno" name="docno" required>
            <option value="">-- Select a document number --</option>
            <?php
              // Display a list of available document numbers
              foreach ($docnos as $docno) {
                echo "<option value='" . $docno . "'>" . $docno . "</option>";
              }
            ?>
          </select>
        </div>
      </div>
      <div class="form-group">
        <div>
          <label for="file">File:</label>
          <input type="file" name="file" required>
        </div>
      </div>
      <div>
        <input type="submit" value="Upload">
      </div>
    </form>
  </div>
</main>
</html>
