<?php
session_start();
if (!isset($_SESSION['user_email'])) { // Or any other session variable that indicates a logged-in user
    header("Location: index.php"); // Redirect to login page
    exit();
}
require_once '../../model/users.php'; // Contains User class with product methods
$userModel = new User();
$productsResult = $userModel->getAllProducts();
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PharmaEase</title>
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="navbar_styles.css">
    <link rel="stylesheet" href="home_styles.css">
    <style>
        .stock {
            font-size: 14px;
            color: #555;
            margin-bottom: 6px;
            font-weight: 500;
        }
        
        /* Style for low stock warning */
        .low-stock {
            color: #e74c3c;
        }
        
        /* Stock badge styling */
        .stock-badge {
            position: absolute;
            top: 10px;
            right: 10px;
            padding: 4px 8px;
            border-radius: 12px;
            background-color: rgba(255, 255, 255, 0.85);
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            font-size: 13px;
            font-weight: 600;
            z-index: 1;
        }
        
        .stock-badge.low-stock {
            background-color: rgba(231, 76, 60, 0.15);
            color: #e74c3c;
            border: 1px solid #e74c3c;
        }
        
        .stock-badge.in-stock {
            background-color: rgba(46, 204, 113, 0.15);
            color: #27ae60;
            border: 1px solid #27ae60;
        }
        
        /* Position relative for the medicine list to contain absolute positioned badge */
        .medicine-list {
            position: relative;
        }
        
        /* Modal stock badge styling adjustments */
        .modal-content .stock-badge {
            position: static;
            display: inline-block;
            margin-top: 5px;
            margin-bottom: 10px;
        }
        
        .product-details {
            text-align: center;
        }
        
        /* Disabled add button for out of stock items */
        .add-button.disabled {
            opacity: 0.5;
            cursor: not-allowed;
            background-color: #f0f0f0;
        }
    </style>
</head>

<body>
    <section id="homebg">
        <nav class="navbar">
            <div class="navbar-container">
                <a href="#" class="navbar-brand">
                    <img src="Frame 6.png" alt="PharmaEase Logo">
                    <span>PharmaEase</span> </a>
                <ul class="navbar-nav">
                    <li class="nav-item">
                        <a href="#" class="nav-link">Home</a>
                    </li>
                    <li class="nav-item">
                        <a href="cart.php" class="nav-link">Cart</a>
                    </li>
                    <li class="nav-item">
                        <a href="users.php" class="nav-link">User</a>
                    </li>
                    <li class="nav-item">
                        <a href="../../controller/logout.php" class="nav-link">Logout</a>
                    </li>
                </ul>
            </div>
        </nav>
        <section id="welcome">
            <h1>Welcome to PharmaEase <br>
                A service you can trust</h1>
            <div class="frame-11">
                <button class="check-discount-offer" onclick="openPopup()">Check Discount Offer</button>

                <!-- Popup Form (hidden by default) -->
                <div id="phonePopup" class="popup">
                    <div class="popup-content">
                        <span class="close popup-close" onclick="closePopup()">&times;</span>
                        <h3>Enter Your 11-Digit Mobile Number</h3>
                        <form id="discountForm" method="post" action="../../controller/sms.php">
                            <input type="text" id="phoneInput" name="phoneNumber" placeholder="e.g. 09123456789"
                                maxlength="11" inputmode="numeric" required>
                            <p id="errorMsg">Please enter exactly 11 digits</p>
                            <button type="submit">Check Offers</button>
                        </form>
                    </div>
                </div>
            </div>
        </section>
        <section id="whitespace">
            <br><br><br><br><br><br><br><br>
            <br><br><br><br><br><br><br><br>
        </section>

    </section>
    <section id="navigation">
        <div class="navbox" id="navbox1">
            <h2>Over the Counter</h2>
            <p>No prescription needed, our over-the-counter medicines and health products help you handle common issues
                like headaches, allergies, colds, and more. Safe, trusted brands delivered right to your door.</p>

        </div>
        <div class="navbox" id="navbox2">
            <h2>Prescription Needed</h2>
            <p>Prescription required, our selection of trusted medications is here to support your health, from chronic
                conditions to specific treatments. Safe, reliable, and delivered to your door with care.
            </p>

        </div>
        <div class="navbox" id="navbox3">
            <h2>Herbal Medicines</h2>
            <p>Natural healing made easy, our herbal medicines are crafted from trusted plant-based ingredients to
                support your health and wellness, the natural way. Safe, effective, and delivered to your door.
            </p>

        </div>
    </section>
    <section id="pos">
        <h1 id="popular">Popular Medicine</h1>
    </section>
    <section id="list">
        <?php
        if ($productsResult && $productsResult->num_rows > 0) {
            while ($product = $productsResult->fetch_assoc()) {
                // Assuming image_path is a filename in the same directory as this script (view/user/)
                // If image_path is empty or null, use a placeholder filename also in this directory.
                $imageSrc = (!empty($product['image_path'])) ? htmlspecialchars($product['image_path']) : 'default_product.png'; // Updated placeholder path
        ?>
            <div class="medicine-list">
                <?php if (isset($product['stock'])): ?>
                    <?php 
                    $stockLevel = intval($product['stock']);
                    $stockClass = '';
                    $stockMessage = '';
                    
                    if ($stockLevel <= 0) {
                        $stockClass = 'low-stock';
                        $stockMessage = 'Out of Stock';
                    } elseif ($stockLevel < 5) {
                        $stockClass = 'low-stock';
                        $stockMessage = 'Low Stock: ' . $stockLevel;
                    } elseif ($stockLevel < 10) {
                        $stockClass = 'low-stock';
                        $stockMessage = 'Limited: ' . $stockLevel;
                    } else {
                        $stockClass = 'in-stock';
                        $stockMessage = 'In Stock: ' . $stockLevel;
                    }
                    ?>
                    <div class="stock-badge <?php echo $stockClass; ?>">
                        <?php echo htmlspecialchars($stockMessage); ?>
                    </div>
                <?php endif; ?>
                <img class="frame-13" src="<?php echo $imageSrc; ?>" alt="<?php echo htmlspecialchars(isset($product['name']) ? $product['name'] : 'Product Image'); ?>" />
                <div class="medtitle"><?php echo htmlspecialchars(isset($product['name']) ? $product['name'] : 'N/A'); ?></div>
                <div class="medprice">₱<?php echo htmlspecialchars(isset($product['price']) ? number_format((float)$product['price'], 2) : '0.00'); ?></div>
                <div class="meddesc"><?php echo htmlspecialchars(isset($product['description']) ? $product['description'] : ''); ?></div>
                <button title="Add New" class="add-button<?php echo ($stockLevel <= 0) ? ' disabled' : ''; ?>" 
                    data-product-id="<?php echo isset($product['product_id']) ? $product['product_id'] : ''; ?>" 
                    data-product-name="<?php echo htmlspecialchars(isset($product['name']) ? $product['name'] : ''); ?>" 
                    data-product-price="<?php echo htmlspecialchars(isset($product['price']) ? number_format((float)$product['price'], 2) : ''); ?>"
                    data-product-stock="<?php echo isset($product['stock']) ? intval($product['stock']) : 0; ?>"
                    <?php echo ($stockLevel <= 0) ? 'disabled' : ''; ?>>
                    <svg xmlns="http://www.w3.org/2000/svg" width="50px" height="50px" viewBox="0 0 24 24"
                        class="button-icon">
                        <path d="M12 22C17.5 22 22 17.5 22 12C22 6.5 17.5 2 12 2C6.5 2 2 6.5 2 12C2 17.5 6.5 22 12 22Z"
                            stroke-width="1.5"></path>
                        <path d="M8 12H16" stroke-width="1.5"></path>
                        <path d="M12 16V8" stroke-width="1.5"></path>
                    </svg>
                </button>
            </div>
        <?php
            }
        } else {
            echo "<p>No products found.</p>";
        }
        $userModel->closeConnection(); // Close database connection
        ?>
    </section>
    <div id="addModal" class="modal">
        <div class="modal-content">
            <span class="close modal-close">&larr;</span>
            <h2>Add to Cart</h2>
            <div class="modal-body">
                <div class="product-info">
                    <img id="modalImage" src="" alt="Medicine" class="modal-image">
                    <div class="product-details">
                        <h3 id="modalTitle"></h3>
                        <p id="modalPrice"></p>
                        <p id="modalStock" class="stock-badge"></p>
                    </div>
                    <div class="quantity-selector">
                        <div class="quantity-controls">
                            <button class="quantity-btn" onclick="decrementQuantity()">-</button>
                            <input type="number" id="quantity" value="1" min="1">
                            <button class="quantity-btn" onclick="incrementQuantity()">+</button>
                        </div>
                    </div>
                </div>
                <div class="modal-buttons">
                    <button class="add-to-cart-btn">Add to Cart</button>
                    <button class="view-cart-btn" onclick="location.href='cart.php'">View Cart</button>
                </div>
            </div>
        </div>
        <script>

            // Popup functionality
            function openPopup() {
                document.getElementById('phonePopup').style.display = 'flex';
                document.getElementById('errorMsg').style.display = 'none';
            }

            function closePopup() {
                document.getElementById('phonePopup').style.display = 'none';
            }

            function validatePhoneNumber(event) {
                event.preventDefault(); // Always prevent default initially
                const phoneNumber = document.getElementById('phoneInput').value;
                const errorElement = document.getElementById('errorMsg');

                // Check if input is exactly 11 digits
                if (/^\d{11}$/.test(phoneNumber)) {
                    errorElement.style.display = 'none'; // Hide error if previously shown
                    alert('Processing your request... Please check your phone for a message shortly!'); // Added alert
                    document.getElementById('discountForm').submit(); // Submit the form if valid
                } else {
                    // Show error message
                    errorElement.style.display = 'block';
                }
            }

            // Close popup when clicking outside of it
            window.onclick = function (event) {
                const popup = document.getElementById('phonePopup');
                if (event.target == popup) {
                    closePopup();
                }
            }

            // Restrict input to numbers only
            document.getElementById('phoneInput').addEventListener('input', function (e) {
                this.value = this.value.replace(/[^0-9]/g, '');
            });

            // Attach form submission handler
            document.getElementById('discountForm').addEventListener('submit', validatePhoneNumber);

            // ----- Start: Corrected Modal Logic for addModal -----
            const addButtons = document.querySelectorAll('.add-button');
            const modal = document.getElementById('addModal'); // Target the correct modal
            const modalImage = document.getElementById('modalImage');
            const modalTitle = document.getElementById('modalTitle');
            const modalPrice = document.getElementById('modalPrice');
            const quantityInput = document.getElementById('quantity');
            const modalCloseButton = modal.querySelector('.modal-close'); // Specific to addModal
            const modalAddToCartButton = modal.querySelector('.modal-buttons .add-to-cart-btn'); // Specific to addModal

            addButtons.forEach(button => {
                button.addEventListener('click', function () {
                    // Skip if button is disabled (out of stock)
                    if (this.classList.contains('disabled')) {
                        alert('Sorry, this product is out of stock.');
                        return;
                    }
                    
                    const productCard = this.closest('.medicine-list');
                    const imgSrc = productCard.querySelector('img') ? productCard.querySelector('img').getAttribute('src') : ''; // This will now pick up the image_path or placeholder
                    const name = this.dataset.productName;
                    const price = this.dataset.productPrice;
                    const id = this.dataset.productId;
                    const stockValue = parseInt(this.dataset.productStock);
                    
                    // Prepare stock badge
                    const stockBadge = document.getElementById('modalStock');
                    if (stockValue <= 0) {
                        stockBadge.textContent = 'Out of Stock';
                        stockBadge.className = 'stock-badge low-stock';
                    } else if (stockValue < 5) {
                        stockBadge.textContent = `Low Stock: ${stockValue}`;
                        stockBadge.className = 'stock-badge low-stock';
                    } else if (stockValue < 10) {
                        stockBadge.textContent = `Limited: ${stockValue}`;
                        stockBadge.className = 'stock-badge low-stock';
                    } else {
                        stockBadge.textContent = `In Stock: ${stockValue}`;
                        stockBadge.className = 'stock-badge in-stock';
                    }

                    modalImage.setAttribute('src', imgSrc);
                    modalTitle.textContent = name;
                    modalPrice.textContent = '₱' + price; // Assuming price from dataset is numeric
                    quantityInput.value = 1; // Reset quantity

                    // Store essential data on the modal's Add to Cart button
                    modalAddToCartButton.dataset.productId = id;
                    modalAddToCartButton.dataset.productName = name;
                    modalAddToCartButton.dataset.productPrice = parseFloat(price); // Store numeric price, ensure it's parsed correctly from string
                    modalAddToCartButton.dataset.productStock = stockValue;
                    
                    // Set max attribute on quantity input
                    if (stockValue > 0) {
                        quantityInput.setAttribute('max', stockValue);
                    } else {
                        quantityInput.setAttribute('max', '1'); // Default to 1 if stock is 0 or not set
                    }

                    modal.style.display = 'block';
                });
            });

            // Close modal when the close button (←) inside addModal is clicked
            modalCloseButton.addEventListener('click', () => {
                modal.style.display = 'none';
            });

            // Quantity Controls (these should remain as they are linked to #quantity input)
            function incrementQuantity() {
                quantityInput.value = parseInt(quantityInput.value) + 1;
            }

            function decrementQuantity() {
                if (parseInt(quantityInput.value) > 1) {
                    quantityInput.value = parseInt(quantityInput.value) - 1;
                }
            }

            // Optional: Close modal when clicking outside the modal content
            window.addEventListener('click', function (event) {
                if (event.target === modal) {
                    modal.style.display = 'none';
                }
            });

            // Add to cart button logic for the modal (addModal)
            modalAddToCartButton.addEventListener('click', () => {
                const productId = modalAddToCartButton.dataset.productId;
                const productName = modalAddToCartButton.dataset.productName;
                const productPrice = parseFloat(modalAddToCartButton.dataset.productPrice);
                const maxStock = parseInt(modalAddToCartButton.dataset.productStock);
                const quantity = parseInt(quantityInput.value);
                
                // Validate quantity against stock
                if (quantity > maxStock) {
                    alert(`Sorry, only ${maxStock} items are available in stock.`);
                    return;
                }

                // Create form data to submit
                const formData = new FormData();
                formData.append('product_id', productId);
                formData.append('quantity', quantity);
                formData.append('add_to_cart', '1');

                // Use fetch to send data to server
                fetch('../../controller/update_session_cart.php', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert(`Added ${quantity} ${productName} to cart`);
                    } else {
                        alert('Failed to add item to cart: ' + data.message);
                    }
                    modal.style.display = 'none';
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('An error occurred. Please try again.');
                });
            });
            // ----- End: Corrected Modal Logic for addModal -----
        </script>
</body>

</html>