<?php
include_once('../data/@data@.php');  // Your database connection

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $stall_name = mysqli_real_escape_string($conn, $_POST['stall_name']);
  $uuid = base64_encode((string)mt_rand(10000000, 99999999)); // Generate Base64 encoded UUID

  // File upload directory
  $targetDir = "../uploads/";  // Path to the uploads folder from the stall directory

  // Check if the upload directory exists
  if (!is_dir($targetDir)) {
    die("Error: Upload directory does not exist.");
  }

  // Retrieve file details
  $file = $_FILES['image'];
  $fileName = basename($file['name']);
  $fileTmpName = $file['tmp_name'];
  $fileSize = $file['size'];
  $fileError = $file['error'];
  $fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

  // Debugging info (optional)
  // echo "File Name: $fileName<br>";
  // echo "Temp Path: $fileTmpName<br>";
  // echo "File Size: $fileSize<br>";
  // echo "File Error: $fileError<br>";

  // Check if the file is a PNG image and its size is under 200KB
  if ($fileExt !== 'png' || $fileSize > 200 * 1024 || $fileError !== 0) {
    die("Error: Only PNG images under 200KB are allowed.");
  }

  // Generate a unique file name for the uploaded file
  $newFileName = uniqid('image_', true) . ".png";
  $targetFilePath = $targetDir . $newFileName;

  // Move the uploaded file to the target directory
  if (!move_uploaded_file($fileTmpName, $targetFilePath)) {
    die("Error: Unable to upload the file.");
  }

  // Show the uploaded image path
  // echo "File uploaded successfully!<br>";
  // echo "The image is saved at: $targetFilePath<br>";

  // Insert the form data (stall logo path, stall name, UUID) into the database
  $sql = "INSERT INTO `stall` (`stall_logo`, `stall_name`, `uuid`) VALUES ('$targetFilePath', '$stall_name', '$uuid')";
  if ($conn->query($sql) === TRUE) {
    echo "<script>alert('Success: Image and data inserted successfully!');</script>";
  } else {
    echo "<script>alert('Error: " . $conn->error . "');</script>";
  }



}
$sel = "SELECT * FROM `stall` ORDER BY `stall_id` DESC";
$res = mysqli_query($conn, $sel);

$actual_link = (empty($_SERVER['HTTPS']) ? 'http' : 'https') . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

$modified_link2 = str_replace('kljvhdk65854', 'mystalldata', $actual_link);
$modified_link = str_replace('ind98258!/kljvhdk65854.php', 'vendors/index.php', $actual_link);

$conn->close();
?>


<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Form</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
  <link rel="stylesheet" type="text/css" href="../style/index.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.3.0/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://cdn.datatables.net/2.1.8/css/dataTables.bootstrap5.css">

  <script src="https://code.jquery.com/jquery-3.7.1.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.3.0/js/bootstrap.bundle.min.js"></script>
  <script src="https://cdn.datatables.net/2.1.8/js/dataTables.js"></script>
  <script src="https://cdn.datatables.net/2.1.8/js/dataTables.bootstrap5.js"></script>


</head>

<body>
  <div class="container-fluid bg-image vh-100 d-flex justify-content-center align-items-center">
    <div class="container">
      <div class="row justify-content-center">
        <div class="col-12 col-md-6">
          <form class="row g-3 needs-validation border p-5 rounded bg-light" novalidate method="post" enctype="multipart/form-data">
            <img src="../image/logo.png" class="m-auto img-fluid mb-3 d-block">

            <div class="col-md-12">
              <label for="inputCompany" class="form-label">Company Name</label>
              <input type="text" class="form-control" name="stall_name" id="inputstall_name" placeholder="Enter Company Name" required>
              <div class="invalid-feedback">Please provide a valid Company Name.</div>
            </div>

            <div class="col-md-12">
              <label for="inputCity" class="form-label">Upload PNG Image (Max: 200KB):</label>
              <input type="file" name="image" class="form-control" id="image" placeholder="Upload logo" accept="image/png" required>
              <div class="invalid-feedback">Please provide image</div>
            </div>

            <div class="col-12">
              <button class="btn btn-danger m-auto d-block" type="submit">Submit</button>
            </div>
          </form>
        </div>
        <div class="col-12 col-md-6">
         
          <table id="example" class="table table-striped" style="width:100%">
            <thead>
              <tr>
                <th>Logo</th>
                <th>Stall Name</th>
                <th>Form URL</th>
                <th>Data URL</th>
             
              </tr>
            </thead>
            <tbody>
              <?php while($getstalllist = mysqli_fetch_assoc($res)){ ?>
              <tr>
                <td><img src="<?php echo $getstalllist['stall_logo'] ?>" style="width: 50px;"> </td>
                <td><?php echo $getstalllist['stall_name'] ?></td>
                <td><?php echo $modified_link.'?shopreg='.$getstalllist['uuid']?></td>
                <td><?php echo $modified_link2.'?shopreg='.$getstalllist['uuid']?></td>
              </tr>
              <?php } ?>
            
            </tbody>
            <tfoot>
              <tr>
              <th>Logo</th>
                <th>Stall Name</th>
                <th>Form URL</th>
                <th>Data URL</th>
              </tr>
            </tfoot>
          </table>
        </div>
      </div>
    </div>
  </div>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
  
  <script>
     new DataTable('#example');
  </script>

  
  <script type="text/javascript">
   
    // Example starter JavaScript for disabling form submissions if there are invalid fields
    (() => {
      'use strict'

      // Fetch all the forms we want to apply custom Bootstrap validation styles to
      const forms = document.querySelectorAll('.needs-validation')

      // Loop over them and prevent submission
      Array.from(forms).forEach(form => {
        form.addEventListener('submit', event => {
          if (!form.checkValidity()) {
            event.preventDefault()
            event.stopPropagation()
          }

          form.classList.add('was-validated')
        }, false)
      })
    })()
  </script>

</body>

</html>