<!DOCTYPE html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Thugil Creation</title>
  <!-- Bootstrap CSS (via CDN) -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <meta name="theme-color" content="#561C24">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Montserrat+Alternates&family=Montserrat:ital,wght@0,100..900;1,100..900&family=PT+Sans:ital,wght@0,400;0,700;1,400;1,700&family=Righteous&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="style.css">
  <link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Andika:ital,wght@0,400;0,700;1,400;1,700&family=Atomic+Age&family=Encode+Sans+SC:wght@100..900&family=Outfit:wght@100..900&family=Silkscreen:wght@400;700&display=swap" rel="stylesheet">
<link rel="icon" href="icons/logo.png" type="image/x-icon">
</head>
 <body>
  <div class="upper-nav">
   <div class="text-slider">
    <div class="text-item" id="text1">Where Silk Meets Style</div>
    <div class="text-item" id="text2">Crafting Silk, Creating Beauty</div>
    <div class="text-item" id="text3">Luxury in Every Thread</div>
   </div>
   <!-- Left and right navigation buttons using Font Awesome icons -->
   <button class="nav-button prev" onclick="moveSlide('prev')">
    <i class="fa fa-chevron-left"></i>
   </button>
   <button class="nav-button next" onclick="moveSlide('next')">
    <i class="fa fa-chevron-right"></i>
   </button>
  </div>
  <nav class="navbar navbar-expand-lg bg-body-tertiary sticky-top">
   <div class="container-fluid">
    <!-- Wrapper for Logo and Toggle Button -->
    <div class="navbar-header">
     <!-- Navbar Toggler for mobile responsiveness -->
     <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation" id="navbar-toggler">
        <i class="fa-solid fa-bars" style="color: #E8D8C4;"></i>
     </button>
     <!-- Company Logo and Name on the left -->
     <a class="navbar-brand" href="index.html">
      <img src="icons/logo.png" alt="Thugil Creation Logo" style="width: 40px; height: auto; margin-right: 10px;"> Thugil Creation </a>
    </div>
    <!-- Navbar Links and Dropdowns -->
    <div class="collapse navbar-collapse" id="navbarNavDropdown">
     <ul class="navbar-nav">
      <li class="nav-item">
       <a class="nav-link active" aria-current="page" href="index.html">Home</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="thugil-creation-membership.html">Membership</a>
      </li>
      <li class="nav-item">
       <a class="nav-link" href="#">Purchase</a>
      </li>
      <li class="nav-item">
       <a class="nav-link" href="contact.html">Contact</a>
      </li>
     </ul>
    </div>
   </div>
  </nav>
  <header>
   <h1>My Purchase History</h1>
  </header>
  <main class="container">
   <div id="order-list">
    <!-- Orders will be displayed here -->
   </div>
  </main>
  <div id="review-container">
   <!-- Image Section -->
   <div id="image-section">
    <img src="https://media.istockphoto.com/id/93355119/photo/indian-saris.jpg?s=612x612&w=0&k=20&c=afmfiTJg0VAmIY6P_TJ_JYsTfGhUdevv18WXQRUZ8NQ=" alt="Image Description" id="review-image">
   </div>
   <!-- Review Section -->
   <div id="review-section">
    <h3>Write a Review</h3>
    <!-- Star Rating -->
    <div id="star-rating">
     <span class="star" data-value="1">★</span>
     <span class="star" data-value="2">★</span>
     <span class="star" data-value="3">★</span>
     <span class="star" data-value="4">★</span>
     <span class="star" data-value="5">★</span>
    </div>
    <!-- Review Text Area -->
    <textarea id="review-text" placeholder="Write your review here..."></textarea>
    <!-- Submit Button -->
    <button id="submit-review">Submit Review</button>
   </div>
  </div>
  <div class="payment mt-0 mb-0">
    <div class="payment-marquee">
        <img src="icons/google-pay-icon.png" alt="Google Pay" class="payment-logo">
        <img src="icons/paytm-icon.png" alt="Paytm" class="payment-logo">
        <img src="icons/phonepe-icon.png" alt="PhonePe" class="payment-logo">
        <img src="icons/razorpay-icon.png" alt="Google Pay" class="payment-logo">
       </div>
  </div>
  <footer class="footer">
			<div class="footer-content">
				<div class="footer-column">
					<h3>About Us</h3>
					<p>At Thugil Creations, we specialize in creating exquisite, handwoven silk sarees that blend timeless tradition with modern elegance.</p>
				</div>
				<div class="footer-column">
					<h3>Quick Links</h3>
					<ul>
            <li><a href="index.html" class="nav-link">Home</a></li>
            <li><a href="#" class="nav-link">Purchases</a></li>
            <li><a href="contact.html" class="nav-link">Contact</a></li>
            <li><a href="privacy-policy.html" class="nav-link">Privacy Policy</a></li> <!-- Added link -->
            <li><a href="thugilcreation-Policy.html" class="nav-link">Terms & Conditions</a></li> <!-- Added link -->
							
						
					</ul>
				</div>
                <div class="footer-column mb-2">
                    <h3>Contact Information</h3>
                    <p>Email: thugilcreation@gmail.com</p>
                    <p>Phone: +91 8838008499 <span style="margin-left: 1%;"></span> +91 9994266271 </p>
                    <p>Address: Kondalampatty,Salem-Tamil Nadu</p>
                    <div class="social-links">
                        <a href="https://www.facebook.com/thugilcreation29" target="_blank">
                          <i class="fab fa-facebook-f" style="color: #6D2932;"></i>
                        </a>
                        <a href="https://www.youtube.com/@THUGILCREATION" target="_blank">
                          <i class="fa-brands fa-youtube" style="color: #6D2932;"></i>
                        </a>
                        <a href="https://www.instagram.com/thugil_creation29/?next=%2F" target="_blank">
                          <i class="fab fa-instagram" style="color: #6D2932;"></i>
                        </a>
                      </div>
                      
                  </div>
			</div>
			<div class="footer-bottom">
				<p>&copy; 2024 Thugil Creation. All Rights Reserved.</p>
			</div>
		</footer>
  <script type="module">
   // Import necessary Firebase SDK modules
   import {
    initializeApp
   } from "https://www.gstatic.com/firebasejs/9.6.1/firebase-app.js";
   import {
    getDatabase,
    ref,
    set,
    push,
    get,
    update
   } from 'https://www.gstatic.com/firebasejs/9.6.1/firebase-database.js';
   import {
    getAuth,
    onAuthStateChanged
   } from 'https://www.gstatic.com/firebasejs/9.10.0/firebase-auth.js';
   // Firebase configuration
   const firebaseConfig = {
    apiKey: "AIzaSyBa2JROkkVR6GWboFZJT2G5NMycYa9zRJ8",
    authDomain: "thugilcreations.firebaseapp.com",
    projectId: "thugilcreations",
    storageBucket: "thugilcreations.firebasestorage.app",
    messagingSenderId: "621636941555",
    appId: "1:621636941555:web:9648e3188471af8a2fe986"
   };
   // Initialize Firebase
   const app = initializeApp(firebaseConfig);
   const database = getDatabase(app);
   // Function to fetch and display purchase history
   function loadPurchaseHistory() {
    const userId = localStorage.getItem('userUID');
    if (!userId) {
     return;
    }
    const ordersRef = ref(database, `users/${userId}/orders`);
    // Fetch orders from Firebase
    get(ordersRef).then(snapshot => {
     const orders = snapshot.val();
     const orderListContainer = document.getElementById('order-list');
     orderListContainer.innerHTML = ''; // Clear the container before adding new data
     if (orders) {
      Object.values(orders).forEach((order, orderIndex) => {
       const orderElement = document.createElement('div');
       orderElement.classList.add('order-item');
       orderElement.id = `order-${orderIndex}`;
       // Extract purchase date
       const purchaseDate = new Date(order.purchaseDate); // Convert to Date object
       const formattedDate = purchaseDate.toLocaleString(); // Format the date and time
       // Create the HTML content for the order item
       orderElement.innerHTML = `
              
        <div class="order-header">
            <p>
                <strong>Order Date:</strong> ${formattedDate}
            </p>
        </div>
        <div class="item-card-container">
                ${order.items.map((item, itemIndex) => {
                  return `
                    
        <div class="item-card">
            <div class="item-image">
                <img src="${item.imageUrl}" alt="${item.name}">
                </div>
                <div class="item-details">
                    <p>
                        <strong>${item.name}</strong>
                    </p>
                    <p>
                        <strong>EPI:</strong> ${item.epi}
                    </p>
                    <p>
                        <strong>PPI:</strong> ${item.ppi}
                    </p>
                    <p>
                        <strong>Hooks:</strong> ${item.hooks}
                    </p>
                    <p>
                        <strong>Image Type:</strong> ${item.imageType}
                    </p>
                    <button class="download-btn" data-order-index="${orderIndex}" data-item-index="${itemIndex}">Download Image</button>
                </div>
            </div>
                  `;
                }).join('')}
              
                    </div>
                    <div class="nav-buttons left">
                        <i class="fas fa-chevron-left"></i>
                    </div>
                    <div class="nav-buttons right">
                        <i class="fas fa-chevron-right"></i>
                    </div>
            `;
       orderListContainer.appendChild(orderElement);
      });
     } else {
      orderListContainer.innerHTML = `
    
                    <div class="no-orders-container">
                        <img src="icons/undraw_shopping_re_hdd9.svg" alt="No Orders Image" class="no-orders-image">
                            <p>No orders found.</p>
                        </div>
`;
     }
    }).catch(error => {
     console.error('Error fetching purchase history:', error);
    });
   }
// Function to handle image download
function downloadImage(orderIndex, itemIndex) {
  const userId = localStorage.getItem('userUID');
  if (!userId) {
    return;
  }
  const ordersRef = ref(database, `users/${userId}/orders`);
  // Fetch orders from Firebase
  get(ordersRef).then(snapshot => {
    const orders = snapshot.val();
    if (orders) {
      const order = orders[Object.keys(orders)[orderIndex]];
      const item = order.items[itemIndex];
      const originalImageUrl = item.originalImageUrl;
      const imageType = item.imageType;  // Get the image type from data
      const downloadCount = item.downloadCount || 0;
      console.log('Attempting to download:', {
        orderIndex,
        itemIndex,
        originalImageUrl,
        imageType
      });

      // Check if the download count exceeds the limit
      if (downloadCount >= 50) {
        alert('This image has reached the maximum download limit.');
        return;
      }

      if (originalImageUrl) {
        // Alternative download method with fetch
        fetch(originalImageUrl).then(response => {
          if (!response.ok) {
            throw new Error('Network response was not ok');
          }
          return response.blob(); // Convert image to Blob
        }).then(blob => {
          // Create a download link
          const link = document.createElement('a');
          
          // Use the image type stored in the data to set the file extension
          const fileExtension = getFileExtensionFromImageType(imageType); 
          const fileName = `${item.name}_${Date.now()}.${fileExtension}`;  // Set the file name with the correct extension
          link.href = window.URL.createObjectURL(blob);
          link.download = fileName; // Set the file name with the correct extension
          
          document.body.appendChild(link);
          link.click();
          // Clean up
          document.body.removeChild(link);
          window.URL.revokeObjectURL(link.href);
          
          // Update download count in Firebase
          const itemRef = ref(database, `users/${userId}/orders/${Object.keys(orders)[orderIndex]}/items/${itemIndex}`);
          update(itemRef, {
            downloadCount: downloadCount + 1
          });
        }).catch(error => {
          console.error('Download error:', error);
          alert('Failed to download image: ' + error.message);
        });
      } else {
        console.error('No original image URL found');
      }
    } else {
      console.error('No orders found');
    }
  }).catch(error => {
    console.error('Error fetching order data:', error);
  });
}

// Helper function to map image type to file extension
function getFileExtensionFromImageType(imageType) {
  const imageTypeMap = {
    'JPEG': 'jpg',  // JPEG
    'BMP': 'bmp',   // BMP
    'PNG': 'png'    // PNG
  };

  // Default to 'jpg' if image type is unknown
  return imageTypeMap[imageType.toUpperCase()] || 'jpg'; // Normalize to uppercase for consistency
}

   // Flag to track if the download is in progress
   let isDownloading = false;
   // Event listener for download button click
   document.addEventListener('click', function(event) {
    // Check if the clicked element is a download button and prevent multiple downloads
    if (event.target && event.target.matches('.download-btn') && !isDownloading) {
     const orderIndex = event.target.getAttribute('data-order-index');
     const itemIndex = event.target.getAttribute('data-item-index');
     // Set the flag to prevent multiple downloads
     isDownloading = true;
     // Call the downloadImage function
     downloadImage(orderIndex, itemIndex);
     // Prevent any default behavior (like opening a link or navigating)
     event.preventDefault();
     // Reset the flag after some time (optional)
     setTimeout(() => {
      isDownloading = false; // Reset flag after a short duration
     }, 1000); // Adjust the timeout duration based on download behavior
    }
   });
   // Call the function to load purchase history when the page loads
   loadPurchaseHistory();
   // Initialize variables
   const stars = document.querySelectorAll('.star');
   let rating = 0;
   // Handle star rating selection
   stars.forEach(star => {
    star.addEventListener('click', function() {
     rating = this.getAttribute('data-value');
     updateStarRating();
    });
   });

   function updateStarRating() {
    stars.forEach(star => {
     if (star.getAttribute('data-value') <= rating) {
      star.classList.add('selected');
     } else {
      star.classList.remove('selected');
     }
    });
   }
   // Handle review submission
   document.getElementById('submit-review').addEventListener('click', function() {
    const reviewText = document.getElementById('review-text').value;
    if (rating === 0 || reviewText.trim() === '') {
     alert("Please provide a rating and a review.");
     return;
    }
    // Get user UID from localStorage
    const userUID = localStorage.getItem('userUID'); // Get UID stored in localStorage
    if (!userUID) {

     return;
    }
    // Save to Firebase Realtime Database
    const reviewData = {
     rating: rating,
     reviewText: reviewText,
     userUID: userUID,
     timestamp: new Date().toISOString()
    };
    const reviewsRef = ref(database, 'reviews/' + userUID); // Save under user UID
    push(reviewsRef, reviewData) // Use `push` instead of `ref`
     .then(() => {
      displayReviews();
      clearForm();
     }).catch(error => {
      console.error("Error saving review: ", error);
     });
   });
   // Clear form
   function clearForm() {
    document.getElementById('review-text').value = '';
    rating = 0;
    updateStarRating();
   }
  </script>
  <script>
   // Disable zooming with JavaScript
   document.addEventListener('wheel', function(e) {
    if (e.ctrlKey || e.metaKey) {
     e.preventDefault();
    }
   }, {
    passive: false
   });
   // Disable pinch to zoom on touch devices
   document.addEventListener('touchstart', function(e) {
    if (e.touches.length > 1) {
     e.preventDefault();
    }
   }, {
    passive: false
   });
   // Get the toggle button and the icons container
   const toggleButton = document.getElementById('navbar-toggler');
   const navbarIcons = document.getElementById('navbar-icons');
   // Add event listener to the toggle button to hide/show the icons
   toggleButton.addEventListener('click', function() {
    navbarIcons.classList.toggle('d-none'); // Toggle the d-none class to hide/show
   });
   let currentSlide = 0;
   const slides = document.querySelectorAll('.text-item');
   const totalSlides = slides.length;

   function showSlide(index) {
    const slider = document.querySelector('.text-slider');
    slider.style.transform = `translateX(-${index * 100}%)`;
   }

   function moveSlide(direction) {
    if (direction === 'next') {
     currentSlide = (currentSlide + 1) % totalSlides; // Loop to first slide after last
    } else if (direction === 'prev') {
     currentSlide = (currentSlide - 1 + totalSlides) % totalSlides; // Loop to last slide before first
    }
    showSlide(currentSlide);
   }

   function autoSlide() {
    currentSlide = (currentSlide + 1) % totalSlides;
    showSlide(currentSlide);
   }
   // Auto slide every 3 seconds
   setInterval(autoSlide, 3000);
   // Initial display of first slide
  </script>
  <!-- Bootstrap JS (optional) -->
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
 </body>
</html>