<?php
include('config/tampil_produk.php');
include('header.php');

foreach ($products as &$product) {
    $product['foto_produk'] = base64_encode($product['foto_produk']);
}
unset($product);
?>
<section class="hero-section" style=" background: linear-gradient(to right, #080808aa, #242124aa), url('img/pp.png') center/cover no-repeat;">
    <div class="container text-center">
        <h1 class="display-4 fw-bold mb-3">PRODUK FITNESS TERBAIK</h1>
        <p class="lead mb-4">Lengkapi kebutuhan fitness Anda dengan produk berkualitas tinggi</p>
    </div>
</section>

<div class="container">
    <div class="search-bar my-4">
        <input type="text" id="searchInput" class="form-control" placeholder="Cari produk..." onkeyup="searchProducts()">
    </div>

    <div class="row" id="productsContainer">
        <?php foreach ($products as $product): ?>
            <div class="col-lg-3 col-md-6 mb-4" >
                <div class="card product-card" onclick="showProductDetails(<?php echo $product['product_id']; ?>)">
                    <div class="position-relative">
                        <img src="data:image/jpeg;base64,<?php echo $product['foto_produk']; ?>" class="product-image" alt="<?php echo $product['nama_produk']; ?>">
                    </div>
                    <div class="card-body">
                        <h5 class="card-title"><?php echo $product['nama_produk']; ?></h5>
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <div>
                                <span class="price-tag">Rp <?php echo number_format($product['harga'], 0, ',', '.'); ?></span>
                                <div class="original-price">Rp <?php echo number_format($product['harga'] * 1.2, 0, ',', '.'); ?></div>
                            </div>
                            <small class="text-muted">Stok: <?php echo $product['stok']; ?></small>
                        </div>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
</div>

<div class="modal fade" id="detailModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modalProductName"></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body row">
                <div class="col-md-6">
                    <img id="modalProductImage" src="" class="img-fluid rounded" alt="Product Image">
                </div>
                <div class="col-md-6">
                    <h6>Deskripsi Produk:</h6>
                    <p id="modalProductDescription" class="mb-3"></p>

                    <h6>Harga:</h6>
                    <p class="fw-bold text-success" id="modalProductPrice"></p>
                    <p class="original-price" id="modalProductOriginalPrice"></p>

                    <h6>Stok Tersedia:</h6>
                    <p class="fw-bold" id="modalProductStock"></p>

                    <div class="mt-3">
                        <label for="productQuantity" class="form-label">Jumlah Pesanan:</label>
                        <div class="input-group mb-3">
                            <button class="btn btn-outline-secondary" type="button" onclick="decreaseQuantity()">-</button>
                            <input type="number" class="form-control text-center" id="productQuantity" value="1" min="1" readonly>
                            <button class="btn btn-outline-secondary" type="button" onclick="increaseQuantity()">+</button>
                        </div>
                        <small id="quantityNote" class="text-muted"></small>
                    </div>
                    <div class="mb-3 p-3 bg-light rounded">
                            <h6 class="fw-bold">Total Pembayaran:</h6>
                            <p class="h4 text-success fw-bold mb-0" id="totalPrice">Rp 0</p>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tutup</button>
                <button type="button" class="btn btn-primary" id="orderButton" onclick="orderProduct()">Pesan Sekarang</button>
            </div>
        </div>
    </div>
</div>


<script>
    let productsDatabase = <?php echo json_encode($products); ?>;
    let selectedProduct = null;

    function searchProducts() {
        const searchInput = document.getElementById('searchInput').value.toLowerCase();
        const filteredProducts = productsDatabase.filter(product =>
            product.nama_produk.toLowerCase().includes(searchInput)
        );

        const container = document.getElementById('productsContainer');
        container.innerHTML = '';

        filteredProducts.forEach(product => {
            const productCard = `
                <div class="col-lg-3 col-md-6 mb-4">
                    <div class="card product-card" onclick="showProductDetails(${product.product_id})">
                        <div class="position-relative">
                            <img src="data:image/jpeg;base64,${product.foto_produk}" class="product-image" alt="${product.nama_produk}">
 
                        </div>
                        <div class="card-body">
                            <h5 class="card-title">${product.nama_produk}</h5>
                            <div class="d-flex justify-content-between align-items-center mb-3">
                                <div>
                                    <span class="price-tag">Rp ${parseInt(product.harga).toLocaleString('id-ID')}</span>
                                    <div class="original-price">Rp ${parseInt(product.harga * 1.2).toLocaleString('id-ID')}</div>
                                </div>
                                <small class="text-muted">Stok: ${product.stok}</small>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            container.innerHTML += productCard;
        });
    }

    function showProductDetails(productId) {
        productId = parseInt(productId);
        selectedProduct = productsDatabase.find(p => parseInt(p.product_id) === productId);

        if (!selectedProduct) {
            console.error('Produk tidak ditemukan:', productId);
            return;
        }

        document.getElementById('modalProductName').innerText = selectedProduct.nama_produk;
        document.getElementById('modalProductDescription').innerText = selectedProduct.deskripsi || 'Tidak ada deskripsi';
        document.getElementById('modalProductPrice').innerText = `Rp ${parseInt(selectedProduct.harga).toLocaleString('id-ID')}`;
        const originalPrice = selectedProduct.harga * 1.2;
        document.getElementById('modalProductOriginalPrice').innerText = `Rp ${originalPrice.toLocaleString('id-ID')}`;
        document.getElementById('modalProductStock').innerText = selectedProduct.stok || '0';
        document.getElementById('productQuantity').value = 1;
        document.getElementById('productQuantity').max = selectedProduct.stok || 1;
        document.getElementById('quantityNote').innerText = `Maksimal pembelian: ${selectedProduct.stok} pcs`;

        document.getElementById('modalProductImage').src = `data:image/jpeg;base64,${selectedProduct.foto_produk}`;

        const modal = new bootstrap.Modal(document.getElementById('detailModal'));
        modal.show();
        updateTotalPrice();
    }

    function updateTotalPrice() {
    const quantity = parseInt(document.getElementById('productQuantity').value);
    const price = parseInt(selectedProduct.harga);
    const total = quantity * price;

    document.getElementById('totalPrice').innerText = `Rp ${total.toLocaleString('id-ID')}`;
    }


    function increaseQuantity() {
        const quantityInput = document.getElementById('productQuantity');
        if (parseInt(quantityInput.value) < parseInt(quantityInput.max)) {
            quantityInput.value = parseInt(quantityInput.value) + 1;
            updateTotalPrice();
        }
    }

    function decreaseQuantity() {
        const quantityInput = document.getElementById('productQuantity');
        if (parseInt(quantityInput.value) > 1) {
            quantityInput.value = parseInt(quantityInput.value) - 1;
            updateTotalPrice();
        }
    }

function orderProduct() {
    if (selectedProduct) {
        const quantity = parseInt(document.getElementById('productQuantity').value);
        if (quantity < 1 || quantity > parseInt(selectedProduct.stok)) {
            alert("Jumlah pesanan tidak valid.");
            return;
        }

        const checkoutUrl = `checkout_produk.php?product_id=${selectedProduct.product_id}&quantity=${quantity}`;
        window.location.href = checkoutUrl;
    }
}

</script>

<?php include('footer.php'); ?>
