<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Bidding Platform</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/glightbox/dist/css/glightbox.min.css">
<script src="https://cdn.jsdelivr.net/npm/glightbox/dist/js/glightbox.min.js"></script>

    
    <style>
                          body {
                            font-family: Arial, sans-serif;
                          }
                          .bid-item {
                            border: 2px solid #ddd;
                            padding: 20px;
                            margin-bottom: 20px;
                            border-radius: 8px;
                            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
                          }
                          .timer {
                            font-size: 18px;
                            font-weight: bold;
                            color: #1c1b1b;
                          }
                          .admin-area {
                            margin: 20px 0;
                            border: 2px solid #007bff;
                            padding: 15px;
                            border-radius: 8px;
                          }
                          .admin-button {
                            background-color: #007bff;
                            color: white;
                            border: none;
                            padding: 10px 15px;
                            border-radius: 5px;
                            cursor: pointer;
                          }
                          .admin-button:hover {
                            background-color: #0056b3;
                          }
                          .bid-controls {
                            margin-top: 15px;
                          }
                          button {
                            margin-right: 10px;
                          }
                          .delete-button {
                            background-color: #dc3545;
                            color: white;
                            border: none;
                            padding: 10px 15px;
                            border-radius: 5px;
                            cursor: pointer;
                          }
                          .delete-button:hover {
                            background-color: #c82333;
                          }
                          .edit-button {
                            background-color: #28a745;
                            color: white;
                            border: none;
                            padding: 10px 15px;
                            border-radius: 5px;
                            cursor: pointer;
                          }
                          .edit-button:hover {
                            background-color: #218838;
                          }
                          .bid-input {
                            padding: 8px;
                            width: 100%;
                            margin-top: 10px;
                            margin-bottom: 15px;
                            box-sizing: border-box;
                          }
                          #bid-items {
                            margin-top: 30px;
                          }

                          /* Style for the new bid form container */
                      #new-bid-form {
                        display: none; /* This will be changed to 'block' in JavaScript */
                        margin-top: 20px;
                        padding: 20px;
                        border: 1px solid #007bff;
                        border-radius: 8px;
                        background-color: #f9f9f9; /* Light background for contrast */
                        box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
                      }

                      /* Flexbox layout for form groups */
                      .form-group {
                        display: flex;
                        flex-direction: column;
                        margin-bottom: 15px; /* Space between form groups */
                      }

                      /* Label styles */
                      label {
                        font-weight: bold;
                        margin-bottom: 5px;
                      }

                      /* Input styles */
                      .admin-input {
                        padding: 12px;
                        border: 1px solid #ccc;
                        border-radius: 5px;
                        width: 100%;
                        box-sizing: border-box;
                        transition: border-color 0.3s;
                      }

                      .admin-input:focus {
                        border-color: #007bff;
                        outline: none;
                      }

                      /* Button styles */
                      .admin-button {
                        background-color: #007bff;
                        color: white;
                        border: none;
                        padding: 12px 15px;
                        border-radius: 5px;
                        cursor: pointer;
                        transition: background-color 0.3s;
                      }

                      .admin-button:hover {
                        background-color: #0056b3;
                      }

                      /* Style for the form's heading */
                      #new-bid-form h3 {
                        margin-bottom: 15px; /* Space below the heading */
                      }

                         .red {
                        color: red;
                      }
                      .bid-history {
                    max-height: 150px; /* Adjust the height as needed */
                    overflow-y: auto;
                    padding: 5px;
                    border: 1px solid #ccc; /* Optional for visual separation */
                    border-radius: 5px; /* Optional for rounded corners */
                }

            .bid-details {
          flex: 2; /* Occupies two-thirds of the container */
          min-width: 200px; /* Ensures a minimum width for smaller screens */
      }

            .bid-gallery {
          flex: 1; /* Occupies one-third of the container */
          display: flex; /* Enable Flexbox within the gallery */
          flex-wrap: wrap; /* Wrap images */
          gap: 10px; /* Space between images */
          justify-content: center; /* Center-align images */
      }

      .bid-gallery img {
          max-width: 100px; /* Constrain image width */
          max-height: 100px; /* Constrain image height */
          object-fit: cover; /* Maintain aspect ratio */
          border: 1px solid #ccc;
          border-radius: 5px;
      }



                  ul[id^="history-list-"] {
                max-height: 50px; /* Adjust as needed */
                overflow-y: auto; /* Add scroll for overflow */
                list-style-type: none; /* Optional: Removes bullets */
                padding: 0; /* Optional: Removes padding */
                margin: 0; /* Optional: Removes margin */
            }

            ul[id^="history-list-"] li {
                word-wrap: break-word; /* Wraps long text */
                padding: 5px 0; /* Adds spacing between items */
                border-bottom: 1px solid #ddd; /* Optional: Adds a separator */
            }

            ul[id^="history-list-"] li:last-child {
                border-bottom: none; /* Removes separator for last item */
            }
      
      .bid-container {
            border: 1px solid #ccc;
            border-radius: 8px;
            margin: 10px 0;
            padding: 10px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        .bid-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            cursor: pointer;
        }
        .bid-details {
            display: none;
            padding-top: 10px;
        }

    </style>
  </head>
  <body>
    <h1>Bidding Platform</h1>

    <!-- User Authentication -->
    <div class="user-info">
      <button id="google-sign-in" class="auth-button">
        Sign In with Google
      </button>
      <p id="user-name"></p>
    </div>

    <!-- Admin Area -->
    <div class="admin-area">
      <h2>Admin Area</h2>
      <button id="create-bid" class="admin-button">Create New Bid</button>
      <div id="new-bid-form" style="display: none;">
        <h3>Create New Bid Item</h3>
        <form id="bid-form">
          <div class="form-group">
            <label for="new-bid-title">Title</label>
            <input type="text" id="new-bid-title" class="admin-input" />
          </div>
          <div class="form-group">
            <label for="new-bid-description">Description</label>
            <textarea id="new-bid-description" class="admin-input"></textarea>
          </div>
          <div class="form-group">
            <label for="new-bid-starting-price">Opening Bid</label>
            <input
              type="number"
              id="new-bid-starting-price"
              class="admin-input"
            />
          </div>
          <div class="form-group">
            <label for="new-bid-timer">Duration (in hours)</label>
            <input type="number" id="new-bid-timer" class="admin-input" />
          </div>

          <div class="form-group">
            <label for="new-bid-images">Upload Images</label>
            <input
              type="file"
              id="new-bid-images"
              class="admin-input"
              multiple
            />
          </div>

          <button id="submit-new-bid" class="admin-button">
            Submit New Bid
          </button>
        </form>
      </div>
    </div>

    <div
      id="upload-progress"
      style="width: 100%; background-color: #f3f3f3; margin-top: 10px;"
    >
      <div
        id="upload-progress-bar"
        style="width: 0%; height: 20px; background-color: #4caf50; text-align: center; color: white;"
      ></div>
    </div>
    <!-- Bid Items for Regular Users -->
    <div id="bid-items"></div>
    <div id="bid-container"></div>
    <script type="module">
                      import { initializeApp, setLogLevel } from "https://www.gstatic.com/firebasejs/9.6.11/firebase-app.js";
                      import {
                          getFirestore,
                          collection,
                          getDocs,
                          doc,
                          getDoc,
                          updateDoc,
                          addDoc,
                          deleteDoc
                      } from "https://www.gstatic.com/firebasejs/9.6.11/firebase-firestore.js";
                      import {
                          getAuth,
                          GoogleAuthProvider,
                          signInWithPopup,
                          signOut,
                          onAuthStateChanged,
                      } from "https://www.gstatic.com/firebasejs/9.6.11/firebase-auth.js";
                    import { getStorage, ref, uploadBytesResumable, getDownloadURL } from "https://www.gstatic.com/firebasejs/9.6.11/firebase-storage.js";

                        // Firebase configuration
                        const firebaseConfig = {
                          apiKey: "AIzaSyBJ2BpYbr0_79aL5ZqFN-bjcG5VvxG_ees",
                          authDomain: "bidding-8cc5c.firebaseapp.com",
                          projectId: "bidding-8cc5c",
                          storageBucket: "bidding-8cc5c.firebasestorage.app",
                          messagingSenderId: "575864398723",
                          appId: "1:575864398723:web:edebce67abc6abcbd74cb6",
                          measurementId: "G-E1TV00RS1P"
                        };

                      const app = initializeApp(firebaseConfig);
                      const db = getFirestore(app);
                      const auth = getAuth(app);
                      const provider = new GoogleAuthProvider();
                    const storage = getStorage(app, "gs://bidding-8cc5c.firebasestorage.app");
            		// Enable debug logging
           
                      let currentUser = null;
                      let isAdmin = false;
                      const adminEmail = "noahkalirani@gmail.com";
            		console.log("Firebase initialized with debug logging enabled.");
                      // Authentication
                      onAuthStateChanged(auth, (user) => {
                          if (user) {
                              currentUser = user;
                              document.getElementById("user-name").textContent = `Signed in as ${user.displayName}`;
                              document.getElementById("google-sign-in").textContent = "Sign Out";
                              document.getElementById("google-sign-in").onclick = () => signOut(auth);
                              isAdmin = user.email === adminEmail;
                              document.querySelector(".admin-area").style.display = isAdmin ? "block" : "none";
                          } else {
                              currentUser = null;
                              document.getElementById("user-name").textContent = "Not signed in";
                              document.getElementById("google-sign-in").textContent = "Sign In with Google";
                              document.getElementById("google-sign-in").onclick = () => signInWithPopup(auth, provider);
                              isAdmin = false;
                              document.querySelector(".admin-area").style.display = "none";
                          }
                      });

                  // Format number with commas and MK symbol
                  function formatCurrency(amount) {
                      return `MK ${new Intl.NumberFormat('en-MW').format(amount)}`;
                  }

                  // Fetch Bids
                  async function fetchBids() {
                      const bidsSnapshot = await getDocs(collection(db, "bids"));
                      const bidItemsContainer = document.getElementById("bid-items");
                      bidItemsContainer.innerHTML = "";

                      bidsSnapshot.forEach((doc) => {
                          const bidData = doc.data();
                          const bidElement = document.createElement("div");
                          bidElement.classList.add("bid-item");

                          // Convert Firestore timestamp to Date object
                          const endTime = bidData.endTime.toDate();
                          const currentTime = new Date();
                          const timeLeft = endTime - currentTime;  // Calculate time left in milliseconds
                          const bidId = doc.id;

                          // Create the bid item element with formatted prices
                        const bidContainer = document.getElementById("bid-container");
                        
                        bidElement.classList.add("bid-container");
bidElement.innerHTML = `
  <div class="bid-header" onclick="toggleBidDetails(this)">
      <div>
          <h2>${bidData.title}</h2>
          <p>${bidData.description}</p>
          <div id="timer-${bidId}" class="timer"></div>
      </div>
  </div>
  <div class="bid-details" style="display: none;">
      <p>Starting Bid: ${formatCurrency(bidData.startingPrice)}</p>
      <p class="current-bid">Highest Bid: ${bidData.highestBid ? formatCurrency(bidData.highestBid) : "None Yet"}</p>
      <p>Highest Bidder: ${bidData.highestBidder || "None Yet"}</p>
      <div class="bid-gallery">
        ${Array.isArray(bidData.imageUrls) && bidData.imageUrls.length > 0
          ? bidData.imageUrls.map((url) => `
            <a href="${url}" class="glightbox" data-gallery="bid-${bidId}" data-title="${bidData.title}">
              <img src="${url}" alt="Bid Image" />
            </a>`).join("")
          : '<p>No images available</p>'}
      </div>
      <h3>Bid History</h3>
      <ul id="history-list-${bidId}">
          ${Array.isArray(bidData.historyList) && bidData.historyList.length > 0
              ? bidData.historyList.map(bid => `<li>${bid.bidder}: ${formatCurrency(bid.amount)} (Placed on ${new Date(bid.timestamp).toLocaleString()})</li>`).join('')
              : '<li>No bids yet</li>'}
      </ul>
      ${timeLeft > 0
          ? `<input type="number" id="bid-input-${bidId}" placeholder="Place your bid" />
             <button onclick="placeBid('${bidId}')">Place Bid</button>`
          : `<input type="number" id="bid-input-${bidId}" disabled placeholder="Auction Ended" />
             <button disabled>Place Bid</button>`}
      ${isAdmin
          ? `<button onclick="editBid('${bidId}', '${bidData.title}', '${bidData.description}', ${bidData.startingPrice})">Edit</button>
             <button onclick="deleteBid('${bidId}')">Delete</button>`
          : ""}
  </div>
`;



                          // Append the bid item to the container
                          bidItemsContainer.appendChild(bidElement);
      				    // Enable image click functionality

                          // Update the timer for each bid
                          updateTimer(bidId, endTime);
                      });
 initializeGallery();
                  }
function initializeGallery() {
  GLightbox({
    selector: '.glightbox',
  });
}
         
window.toggleBidDetails = function (header) {
    const details = header.nextElementSibling;
    const isHidden = details.style.display === 'none' || details.style.display === '';
    details.style.display = isHidden ? 'block' : 'none';
};
    
                      // Update Timer
                      function updateTimer(bidId, endTime) {
                          const timerElement = document.getElementById(`timer-${bidId}`);
                          const interval = setInterval(() => {
                              const now = new Date();
                              const diff = endTime - now;

                              if (diff <= 0) {
                                  timerElement.textContent = "Auction Ended";
                                  clearInterval(interval);
                              } else {
                                  const hours = Math.floor(diff / (1000 * 60 * 60));
                                  const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
                                  const seconds = Math.floor((diff % (1000 * 60)) / 1000);
                                  let timeText = `${hours}h ${minutes}m ${seconds}s`;

                                  // If less than 1 minute, turn the timer red
                                  if (diff <= 60000) {
                                      timerElement.classList.add("red");
                                  }

                                  timerElement.textContent = timeText;
                              }
                          }, 1000);  // Update every second
                      }

                      // Place Bid
                      window.placeBid = async function (bidId) {
                          const bidInput = document.getElementById(`bid-input-${bidId}`);
                          const newBidAmount = parseFloat(bidInput.value);
                          if (isNaN(newBidAmount) || newBidAmount <= 0) {
                              alert("Please enter a valid bid amount");
                              return;
                          }

                          const bidRef = doc(db, "bids", bidId);
                          const bidDoc = await getDoc(bidRef);
                          const currentBid = bidDoc.data().startingPrice || 0;

                          const currentHighestBid = bidDoc.data().highestBid || 0;

                          if (newBidAmount <= currentBid) {
                              alert("Your bid must be higher than the Starting Price");
                              return;
                          }

                          if (newBidAmount <= currentHighestBid) {
                              alert("Your bid must be higher than the Current Highest Bid");
                              return;
                          }

                          const currentBidder = currentUser.displayName;

                          // Update the bid history
                          const historyList = bidDoc.data().historyList || [];
                          historyList.push({ bidder: currentBidder, amount: newBidAmount, timestamp: new Date().toISOString() });   // Add timestamp when the bid was placed

                          await updateDoc(bidRef, {
                              highestBid: newBidAmount,
                              highestBidder: currentBidder,
                              historyList: historyList
                          });

                          alert("Your bid has been placed!");
                          fetchBids();
                      };

                      // Admin Add New Bid
                      document.getElementById("create-bid").onclick = function () {
                          document.getElementById("new-bid-form").style.display = "block";
                      };

      // Handle bid creation
      document.getElementById("submit-new-bid").addEventListener("click", async (e) => {
          e.preventDefault();

          const title = document.getElementById("new-bid-title").value;
          const description = document.getElementById("new-bid-description").value;
          const startingPrice = parseFloat(document.getElementById("new-bid-starting-price").value);
          const duration = parseInt(document.getElementById("new-bid-timer").value, 10);
          const files = document.getElementById("new-bid-images").files;

          // Progress bar element
          const progressBar = document.getElementById("upload-progress-bar");
          progressBar.style.width = "0%"; // Reset progress bar

          if (!title || !description || isNaN(startingPrice) || isNaN(duration)) {
              alert("Please fill in all fields!");
              return;
          }

          const endTime = new Date();
          endTime.setHours(endTime.getHours() + duration);
          const imageUrls = [];

          try {
              if (files.length > 0) {
                  console.debug(`Uploading ${files.length} images...`);
                  for (const file of files) {
                      const storageRef = ref(storage, `bids/${Date.now()}_${file.name}`);
                      const uploadTask = uploadBytesResumable(storageRef, file);

                      // Track upload progress
                      uploadTask.on(
                          "state_changed",
                          (snapshot) => {
                              const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
                              console.debug(`Upload is ${progress.toFixed(2)}% done`);
                              progressBar.style.width = `${progress}%`;
                          },
                          (error) => {
                              console.error("Error during upload:", error);
                              alert(`Failed to upload image: ${error.message}`);
                          },
                          async () => {
                              const url = await getDownloadURL(uploadTask.snapshot.ref);
                              imageUrls.push(url);
                              console.debug("Uploaded Image URL:", url);

                              // Reset progress bar after each file upload
                              progressBar.style.width = "0%";
                          }
                      );

                      // Wait for the upload to complete
                      await uploadTask;
                  }
              } else {
                  console.warn("No files selected for upload.");
              }

              // Save bid to Firestore
              const newBid = {
                  title,
                  description,
                  startingPrice,
                  endTime,
                  imageUrls,
                  highestBid: null,
                  highestBidder: null,
                  historyList: []
              };

              const docRef = await addDoc(collection(db, "bids"), newBid);
              console.debug("New Bid Created:", docRef.id);

              alert("Bid created successfully!");
              fetchBids(); // Refresh the bids

              // Close the form
              const formModal = document.getElementById("new-bid-form");
              if (formModal) {
                  formModal.style.display = "none"; // Close the modal
              }
          } catch (error) {
              console.error("Error during bid creation:", error);
              alert(`Failed to create bid: ${error.message}`);
          }
      });


                      // Delete Bid
                      window.deleteBid = async function (bidId) {
                          const bidRef = doc(db, "bids", bidId);
                          await deleteDoc(bidRef);
                          fetchBids();
                      };

                      // Edit Bid
                      window.editBid = async function (bidId, title, description, startingPrice) {
                          const newTitle = prompt("Enter new title", title);
                          const newDescription = prompt("Enter new description", description);
                          const newStartingPrice = parseFloat(prompt("Enter new starting price", startingPrice));

                          if (!newTitle || !newDescription || isNaN(newStartingPrice)) {
                              alert("Invalid input");
                              return;
                          }

                          const bidRef = doc(db, "bids", bidId);
                          await updateDoc(bidRef, {
                              title: newTitle,
                              description: newDescription,
                              startingPrice: newStartingPrice
                          });

                          fetchBids();
                      };


                      // Fetch all bids on page load
                      fetchBids();
     
    </script>
    
  </body>
</html>
