<?php
require_once '../includes/config.php';
$pageTitle = "Keranjang Belanja";
include '../includes/header.php';

// Initialize cart if not exists
if (!isset($_SESSION['cart'])) {
    $_SESSION['cart'] = array();
}

$cart = $_SESSION['cart'];
$cartItems = array();
$totalAmount = 0;

// Fetch cart items from database if cart is not empty
if (!empty($cart)) {
    try {
        $conn = connectDB();
        $productIds = array_keys($cart);
        $placeholders = implode(',', array_fill(0, count($productIds), '?'));
        
        $stmt = $conn->prepare("SELECT * FROM products WHERE product_id IN ($placeholders)");
        $stmt->execute($productIds);
        $products = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Build cart items with product details
        foreach ($products as $product) {
            $productId = $product['product_id'];
            if (isset($cart[$productId])) {
                $quantity = $cart[$productId];
                $subtotal = $quantity * $product['price'];
                
                $cartItems[] = array(
                    'product_id' => $productId,
                    'name' => $product['name'],
                    'price' => $product['price'],
                    'quantity' => $quantity,
                    'subtotal' => $subtotal,
                    'stock' => $product['stock'],
                    'image_path' => $product['image_path']
                );
                
                $totalAmount += $subtotal;
            }
        }
    } catch (PDOException $e) {
        $error = "Error: " . $e->getMessage();
    }
}

// Check for messages
$message = '';
if (isset($_SESSION['cart_message'])) {
    $message = $_SESSION['cart_message'];
    unset($_SESSION['cart_message']);
}
?>

<div class="container">
    <div class="cart-page">
        <div class="page-header">
            <h1><i class="fas fa-shopping-cart"></i> Keranjang Belanja</h1>
        </div>
    
        <?php if (!empty($message)): ?>
            <div class="message"><?php echo $message; ?></div>
        <?php endif; ?>
    
        <?php if (isset($error)): ?>
            <p class="error"><?php echo $error; ?></p>
        <?php elseif (empty($cartItems)): ?>
            <div class="empty-cart">
                <i class="fas fa-shopping-cart fa-5x"></i>
                <p>Keranjang belanja Anda kosong.</p>
                <a href="<?php echo SITE_URL; ?>products/" class="btn">Belanja Sekarang</a>
            </div>
        <?php else: ?>
            <div class="cart-content">
                <div class="cart-table-container">
                    <div class="table-responsive">
                        <table class="cart-table">
                            <thead>
                                <tr>
                                    <th class="product-col">Produk</th>
                                    <th class="price-col">Harga</th>
                                    <th class="qty-col">Jumlah</th>
                                    <th class="subtotal-col">Subtotal</th>
                                    <th class="action-col">Aksi</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($cartItems as $item): ?>
                                    <tr class="cart-item" data-id="<?php echo $item['product_id']; ?>">
                                        <td class="product-info">
                                            <div class="product-img-small">
                                                <?php if ($item['image_path']): ?>
                                                    <img src="<?php echo SITE_URL . $item['image_path']; ?>" alt="<?php echo $item['name']; ?>">
                                                <?php else: ?>
                                                    <img src="<?php echo SITE_URL; ?>assets/img/no-image.jpg" alt="No Image">
                                                <?php endif; ?>
                                            </div>
                                            <div class="product-name">
                                                <a href="<?php echo SITE_URL; ?>products/detail.php?id=<?php echo $item['product_id']; ?>">
                                                    <?php echo $item['name']; ?>
                                                </a>
                                            </div>
                                        </td>
                                        <td class="price">Rp <?php echo number_format($item['price'], 0, ',', '.'); ?></td>
                                        <td class="quantity">
                                            <div class="quantity-control">
                                                <button type="button" class="quantity-btn minus" data-id="<?php echo $item['product_id']; ?>">
                                                    <i class="fas fa-minus"></i>
                                                </button>
                                                <input type="number" class="quantity-input" data-id="<?php echo $item['product_id']; ?>" value="<?php echo $item['quantity']; ?>" min="1" max="<?php echo $item['stock']; ?>">
                                                <button type="button" class="quantity-btn plus" data-id="<?php echo $item['product_id']; ?>">
                                                    <i class="fas fa-plus"></i>
                                                </button>
                                            </div>
                                        </td>
                                        <td class="subtotal">Rp <?php echo number_format($item['subtotal'], 0, ',', '.'); ?></td>
                                        <td class="actions">
                                            <button type="button" class="remove-from-cart" data-id="<?php echo $item['product_id']; ?>" title="Hapus">
                                                <i class="fas fa-trash-alt"></i>
                                            </button>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            
                <div class="cart-summary">
                    <h3>Ringkasan Belanja</h3>
                    <div class="cart-total">
                        <span class="label">Total Belanja:</span>
                        <span class="amount" id="cart-total">Rp <?php echo number_format($totalAmount, 0, ',', '.'); ?></span>
                    </div>
                
                    <div class="cart-actions">
                        <a href="<?php echo SITE_URL; ?>products/" class="btn secondary-btn">
                            <i class="fas fa-arrow-left"></i> Lanjutkan Belanja
                        </a>
                        <?php if (isUserLoggedIn()): ?>
                            <a href="<?php echo SITE_URL; ?>checkout/" class="btn primary-btn">
                                <i class="fas fa-shopping-bag"></i> Checkout
                            </a>
                        <?php else: ?>
                            <a href="<?php echo SITE_URL; ?>user/login.php?redirect=checkout" class="btn primary-btn">
                                <i class="fas fa-sign-in-alt"></i> Login untuk Checkout
                            </a>
                        <?php endif; ?>
                        <button type="button" class="btn danger-btn" id="clearCartBtn">
                            <i class="fas fa-trash"></i> Hapus Semua
                        </button>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>
</div>

<script>
// Get site URL from PHP
const SITE_URL = '<?php echo SITE_URL; ?>';

// Custom confirmation dialog (moved here for simplicity if main.js is not used or edited often)
function showConfirmationDialog(message, callback) {
    const modalHtml = `
        <div class="confirmation-modal-overlay">
            <div class="confirmation-modal-content">
                <p>${message}</p>
                <div class="confirmation-modal-actions">
                    <button class="btn secondary-btn" id="cancelConfirm">Batal</button>
                    <button class="btn danger-btn" id="confirmAction">Hapus</button>
                </div>
            </div>
        </div>
    `;

    document.body.insertAdjacentHTML('beforeend', modalHtml);

    const modalOverlay = document.querySelector('.confirmation-modal-overlay');
    const cancelBtn = document.getElementById('cancelConfirm');
    const confirmBtn = document.getElementById('confirmAction');

    // Show the modal with transition
    setTimeout(() => {
        modalOverlay.classList.add('show');
    }, 10);

    const close = () => {
        modalOverlay.classList.remove('show');
        setTimeout(() => {
            modalOverlay.remove();
        }, 300); // Allow time for fade-out transition
    };

    cancelBtn.addEventListener('click', () => {
        close();
    });

    confirmBtn.addEventListener('click', () => {
        callback();
        close();
    });

    // Close on overlay click
    modalOverlay.addEventListener('click', (e) => {
        if (e.target === modalOverlay) {
            close();
        }
    });
}

document.addEventListener('DOMContentLoaded', function() {
    // Quantity buttons functionality
    const minusButtons = document.querySelectorAll('.quantity-btn.minus');
    const plusButtons = document.querySelectorAll('.quantity-btn.plus');
    
    if (minusButtons.length > 0) {
        minusButtons.forEach(button => {
            button.addEventListener('click', function() {
                const productId = this.getAttribute('data-id');
                const input = document.querySelector(`.quantity-input[data-id="${productId}"]`);
                if (parseInt(input.value) > 1) {
                    input.value = parseInt(input.value) - 1;
                    updateCartItem(productId, input.value);
                }
            });
        });
    }
    
    if (plusButtons.length > 0) {
        plusButtons.forEach(button => {
            button.addEventListener('click', function() {
                const productId = this.getAttribute('data-id');
                const input = document.querySelector(`.quantity-input[data-id="${productId}"]`);
                if (parseInt(input.value) < parseInt(input.getAttribute('max'))) {
                    input.value = parseInt(input.value) + 1;
                    updateCartItem(productId, input.value);
                }
            });
        });
    }
    
    // Manually typed quantity update
    const quantityInputs = document.querySelectorAll('.quantity-input');
    if (quantityInputs.length > 0) {
        quantityInputs.forEach(input => {
            input.addEventListener('change', function() {
                const productId = this.getAttribute('data-id');
                const maxStock = parseInt(this.getAttribute('max'));
                let value = parseInt(this.value);
                
                if (isNaN(value) || value < 1) {
                    value = 1;
                } else if (value > maxStock) {
                    value = maxStock;
                }
                
                this.value = value;
                updateCartItem(productId, value);
            });
        });
    }
    
    // Remove from cart functionality
    const removeButtons = document.querySelectorAll('.remove-from-cart');

if (removeButtons.length > 0) {
    removeButtons.forEach(button => {
        button.addEventListener('click', function () {
            const productId = this.getAttribute('data-id');
            const row = document.querySelector(`.cart-item[data-id="${productId}"]`);

            // Ask for confirmation before proceeding
            if (confirm('Apakah Anda yakin ingin menghapus produk ini dari keranjang?')) {
                // Add animation for the row before removing
                row.classList.add('removing');

                // Send request to remove the item from the cart
                fetch(`${SITE_URL}cart/remove.php`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: `product_id=${productId}`
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // Wait for the animation to finish before removing
                        setTimeout(() => {
                            row.remove();
                            updateCartTotal();

                            // If the cart is empty, reload the page to refresh the state
                            if (document.querySelectorAll('.cart-item').length === 0) {
                                window.location.reload();
                            }
                        }, 300); // Matches the duration of the animation
                    } else {
                        alert('Gagal menghapus produk dari keranjang. Coba lagi.');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('Terjadi kesalahan saat menghapus produk. Coba lagi nanti.');
                });
            }
        });
    });
}

    // Clear cart functionality
    const clearCartBtn = document.getElementById('clearCartBtn');
    if (clearCartBtn) {
        clearCartBtn.addEventListener('click', function() {
            showConfirmationDialog('Apakah Anda yakin ingin mengosongkan keranjang belanja Anda?', function() {
                window.location.href = `${SITE_URL}cart/clear.php`;
            });
        });
    }

    
    function updateCartItem(productId, quantity) {
        // Send request to update item
        fetch(`${SITE_URL}cart/update.php`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: `product_id=${productId}&quantity=${quantity}`
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // Update subtotal
                const row = document.querySelector(`.cart-item[data-id="${productId}"]`);
                const subtotalCell = row.querySelector('.subtotal');
                subtotalCell.textContent = `Rp ${formatNumber(data.subtotal)}`;
                
                // Add flash effect to show update
                subtotalCell.classList.add('updated');
                setTimeout(() => {
                    subtotalCell.classList.remove('updated');
                }, 1000);
                
                updateCartTotal();
            } else {
                alert('Gagal memperbarui keranjang belanja.');
            }
        });
    }
    
    function updateCartTotal() {
        // Calculate total from all subtotals
        let total = 0;
        document.querySelectorAll('.cart-item').forEach(item => {
            const subtotalText = item.querySelector('.subtotal').textContent;
            const subtotal = parseInt(subtotalText.replace(/[^\d]/g, ''));
            total += subtotal;
        });
        
        // Update total display
        const totalElement = document.getElementById('cart-total');
        totalElement.textContent = `Rp ${formatNumber(total)}`;
        
        // Add flash effect to show update
        totalElement.classList.add('updated');
        setTimeout(() => {
            totalElement.classList.remove('updated');
        }, 1000);
    }
    
    function formatNumber(num) {
        return new Intl.NumberFormat('id-ID').format(num);
    }
});
</script>

<style>
/* Cart Page Styles */
.cart-page {
    padding: 30px 0;
}

.page-header {
    margin-bottom: 30px;
    position: relative;
}

.page-header h1 {
    font-size: 28px;
    color: var(--primary-color);
    margin-bottom: 10px;
    display: flex;
    align-items: center;
    gap: 10px;
}

.page-header h1 i {
    color: var(--accent-color);
}

.empty-cart {
    background-color: var(--white);
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    padding: 50px 20px;
    text-align: center;
    margin: 20px 0;
}

.empty-cart i {
    color: var(--accent-color);
    margin-bottom: 20px;
}

.empty-cart p {
    font-size: 18px;
    margin-bottom: 20px;
    color: var(--dark-gray);
}

.cart-content {
    display: grid;
    grid-template-columns: 1fr;
    gap: 20px;
}

@media (min-width: 992px) {
    .cart-content {
        grid-template-columns: 2fr 1fr;
        align-items: start;
    }
}

.cart-table-container {
    background-color: var(--white);
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    overflow: hidden;
}

/* Table styles */
.cart-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 14px;
}

.cart-table th {
    background-color: #f8f9fa;
    color: var(--dark-gray);
    font-weight: 600;
    text-align: left;
    padding: 15px;
    border-bottom: 1px solid #e9ecef;
}

.cart-table td {
    padding: 15px;
    border-bottom: 1px solid #e9ecef;
    vertical-align: middle;
}

.cart-table tr:last-child td {
    border-bottom: none;
}

/* Product info in cart */
.product-info {
    display: flex;
    align-items: center;
    gap: 15px;
}

.product-img-small {
    width: 80px;
    height: 80px;
    overflow: hidden;
    border-radius: 5px;
    border: 1px solid #e9ecef;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: var(--white);
}

.product-img-small img {
    width: 100%;
    height: 100%;
    object-fit: contain;
}

.product-name a {
    color: var(--text-color);
    font-weight: 500;
    text-decoration: none;
}

.product-name a:hover {
    color: var(--primary-color);
}

/* Quantity controls */
.quantity-control {
    display: flex;
    align-items: center;
    border: 1px solid #e9ecef;
    border-radius: 5px;
    overflow: hidden;
    width: fit-content;
}

.quantity-btn {
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f8f9fa;
    border: none;
    cursor: pointer;
    transition: all 0.2s;
    padding: 0;
    color: var(--text-color);
}

.quantity-btn:hover {
    background-color: #e9ecef;
}

.quantity-input {
    width: 40px;
    height: 32px;
    border: none;
    text-align: center;
    font-size: 14px;
    font-weight: 500;
    -moz-appearance: textfield;
}

.quantity-input::-webkit-outer-spin-button,
.quantity-input::-webkit-inner-spin-button {
    -webkit-appearance: none;
    margin: 0;
}

.quantity-input:focus {
    outline: none;
}

/* Price and subtotal */
.price, .subtotal {
    font-weight: 500;
}

.subtotal {
    color: var(--primary-color);
    transition: background-color 0.3s;
}

.subtotal.updated {
    background-color: rgba(76, 175, 80, 0.1);
}

/* Remove button */
.remove-from-cart {
    background: none;
    border: none;
    padding: 8px;
    cursor: pointer;
    color: #dc3545;
    border-radius: 50%;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s;
}

.remove-from-cart:hover {
    background-color: rgba(220, 53, 69, 0.1);
    transform: scale(1.1);
}

/* Cart summary */
.cart-summary {
    background-color: var(--white);
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    padding: 20px;
}

.cart-summary h3 {
    margin-bottom: 15px;
    font-size: 18px;
    color: var(--text-color);
    padding-bottom: 10px;
    border-bottom: 1px solid #e9ecef;
}

.cart-total {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #e9ecef;
}

.cart-total .label {
    font-size: 16px;
    color: var(--text-color);
}

.cart-total .amount {
    font-size: 20px;
    font-weight: bold;
    color: var(--primary-color);
    transition: background-color 0.3s;
}

.cart-total .amount.updated {
    background-color: rgba(76, 175, 80, 0.1);
}

.cart-actions {
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.cart-actions a {
    width: 100%;
    text-align: center;
    padding: 12px;
    font-weight: 500;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
}

.primary-btn {
    background-color: var(--primary-color);
    color: white;
}

.primary-btn:hover {
    background-color: var(--secondary-color);
}

/* Animation for row removal */
@keyframes fadeOut {
    0% {
        opacity: 1;
        transform: translateX(0);
    }
    100% {
        opacity: 0;
        transform: translateX(30px);
    }
}

.removing {
    animation: fadeOut 0.3s forwards;
}

/* Responsive adjustments */
@media (max-width: 768px) {
    .cart-table {
        font-size: 13px;
    }
    
    .product-img-small {
        width: 60px;
        height: 60px;
    }
    
    .cart-table th, .cart-table td {
        padding: 10px 8px;
    }
    
    .action-col {
        width: 40px;
    }
    
    .product-name a {
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
        max-width: 150px;
    }
}

@media (max-width: 576px) {
    .cart-table {
        display: block;
        width: 100%;
        overflow-x: auto;
    }
    
    .cart-actions {
        flex-direction: column;
    }
    
    .cart-actions a {
        width: 100%;
    }
    
    .product-img-small {
        width: 50px;
        height: 50px;
    }
}
</style>

<?php include '../includes/footer.php'; ?> 