<?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">
</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()) {
        ?>
            <div class="medicine-list">
                <img class="frame-13" src="<?php echo htmlspecialchars(isset($product['ImagePath']) ? $product['ImagePath'] : ''); ?>" 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($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" data-product-id="<?php echo isset($product['ID']) ? $product['ID'] : ''; ?>" data-product-name="<?php echo htmlspecialchars(isset($product['Name']) ? $product['Name'] : ''); ?>" data-product-price="<?php echo htmlspecialchars(isset($product['Price']) ? number_format($product['Price'], 2) : ''); ?>">
                    <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>
                    </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 () {
                    const productCard = this.closest('.medicine-list');
                    const imgSrc = productCard.querySelector('img') ? productCard.querySelector('img').getAttribute('src') : '';
                    const name = this.dataset.productName;
                    const price = this.dataset.productPrice;
                    const id = this.dataset.productId;

                    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 = price; // Store numeric price

                    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 quantity = parseInt(quantityInput.value);

                let cart = JSON.parse(localStorage.getItem('cart')) || [];
                const existingProductIndex = cart.findIndex(item => item.id === productId);

                if (existingProductIndex > -1) {
                    cart[existingProductIndex].quantity += quantity;
                } else {
                    cart.push({ 
                        id: productId, 
                        name: productName, 
                        price: productPrice, 
                        quantity: quantity 
                    });
                }

                localStorage.setItem('cart', JSON.stringify(cart));
                alert(`Added ${quantity} ${productName} to cart`);
                modal.style.display = 'none';
            });
            // ----- End: Corrected Modal Logic for addModal -----
        </script>
</body>

</html>