<?php
session_start();
require_once 'config.php';

// Get cart from session
$cart = $_SESSION['cart'] ?? [];
$cartItems = [];
$subtotal = 0;
foreach ($cart as $id => $item) {
    // Fetch product name from database (we need product name)
    if ($item['type'] == 'product') {
        $prod = $conn->query("SELECT name FROM products WHERE id = $id")->fetch_assoc();
        $name = $prod ? $prod['name'] : 'Unknown Product';
    } else {
        $serv = $conn->query("SELECT title FROM services WHERE id = $id")->fetch_assoc();
        $name = $serv ? $serv['title'] : 'Unknown Service';
    }
    $itemTotal = $item['quantity'] * $item['price'];
    $subtotal += $itemTotal;
    $cartItems[] = [
        'id' => $id,
        'type' => $item['type'],
        'name' => $name,
        'quantity' => $item['quantity'],
        'price' => $item['price'],
        'total' => $itemTotal
    ];
}

$delivery_charge = 50;
$total = $subtotal + $delivery_charge;
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>শপিং কার্ট | <?= htmlspecialchars($brand['name'] ?? 'ওয়ান হোমিওপ্যাথি') ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body { background: #f0f2f5; font-family: 'Hind Siliguri', sans-serif; }
        .cart-header { background: linear-gradient(135deg, #2d6a4f, #1b4332); color: #fff; padding: 80px 0 40px; margin-bottom: 40px; }
        .cart-card { background: #fff; border-radius: 20px; box-shadow: 0 5px 15px rgba(0,0,0,0.08); padding: 20px; margin-bottom: 20px; }
        .cart-item-img { width: 80px; height: 80px; object-fit: cover; border-radius: 12px; }
        .quantity-input { width: 70px; text-align: center; }
        .btn-checkout { background: #2d6a4f; color: #fff; border-radius: 50px; padding: 12px 30px; font-weight: bold; }
        .btn-checkout:hover { background: #1b4332; }
        footer { background: #0a0a0a; color: #aaa; padding: 30px 0 20px; margin-top: 50px; text-align: center; }
    </style>
</head>
<body>

<!-- Navbar (same as index.php but minimal) -->
<nav class="navbar navbar-expand-lg bg-dark fixed-top">
    <div class="container">
        <a class="navbar-brand text-white" href="index.php"><i class="fas fa-clinic-medical"></i> <?= htmlspecialchars($brand['name'] ?? 'ওয়ান হোমিওপ্যাথি') ?></a>
        <a href="cart.php" class="btn btn-warning position-relative">
            <i class="fas fa-shopping-cart"></i> কার্ট
            <span id="cartCountBadge" class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger">0</span>
        </a>
    </div>
</nav>

<div class="cart-header text-center">
    <div class="container">
        <h1><i class="fas fa-shopping-cart"></i> আপনার শপিং কার্ট</h1>
        <p>পণ্য যুক্ত করুন, পরিমাণ পরিবর্তন করুন এবং অর্ডার সম্পন্ন করুন</p>
    </div>
</div>

<div class="container">
    <div class="row">
        <div class="col-lg-8">
            <div id="cartItemsContainer">
                <?php if (empty($cartItems)): ?>
                    <div class="cart-card text-center py-5">
                        <i class="fas fa-shopping-cart fa-3x text-muted mb-3"></i>
                        <h5>আপনার কার্ট খালি</h5>
                        <a href="index.php#products" class="btn btn-primary mt-3">পণ্য দেখুন</a>
                    </div>
                <?php else: ?>
                    <?php foreach ($cartItems as $item): ?>
                    <div class="cart-card d-flex flex-wrap align-items-center gap-3" id="cart-item-<?= $item['id'] ?>">
                        <div class="flex-grow-1">
                            <h5><?= htmlspecialchars($item['name']) ?></h5>
                            <p class="text-muted"><?= ucfirst($item['type']) ?> | দাম: ৳<?= number_format($item['price'], 2) ?></p>
                        </div>
                        <div class="d-flex align-items-center gap-2">
                            <button class="btn btn-sm btn-outline-secondary qty-minus" data-id="<?= $item['id'] ?>">-</button>
                            <input type="number" class="form-control quantity-input text-center" value="<?= $item['quantity'] ?>" min="1" data-id="<?= $item['id'] ?>" data-price="<?= $item['price'] ?>">
                            <button class="btn btn-sm btn-outline-secondary qty-plus" data-id="<?= $item['id'] ?>">+</button>
                        </div>
                        <div>
                            <strong>৳<span class="item-total" data-id="<?= $item['id'] ?>"><?= number_format($item['total'], 2) ?></span></strong>
                        </div>
                        <div>
                            <button class="btn btn-sm btn-danger remove-item" data-id="<?= $item['id'] ?>"><i class="fas fa-trash"></i></button>
                        </div>
                    </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
        <div class="col-lg-4">
            <div class="cart-card">
                <h5>অর্ডার সামারি</h5>
                <hr>
                <div class="d-flex justify-content-between mb-2">
                    <span>সাবটোটাল:</span>
                    <span>৳<span id="subtotal"><?= number_format($subtotal, 2) ?></span></span>
                </div>
                <div class="d-flex justify-content-between mb-2">
                    <span>ডেলিভারি চার্জ:</span>
                    <span>৳<span id="deliveryCharge"><?= number_format($delivery_charge, 2) ?></span></span>
                </div>
                <hr>
                <div class="d-flex justify-content-between mb-3">
                    <strong>মোট:</strong>
                    <strong>৳<span id="total"><?= number_format($total, 2) ?></span></strong>
                </div>
                <?php if (!empty($cartItems)): ?>
                <a href="checkout.php" class="btn btn-checkout w-100">চেকআউট <i class="fas fa-arrow-right"></i></a>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<footer>
    <div class="container">
        <p>&copy; <?= date('Y') ?> <?= htmlspecialchars($brand['name'] ?? 'ওয়ান হোমিওপ্যাথি') ?>। সর্বস্বত্ব সংরক্ষিত।</p>
    </div>
</footer>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
function updateCartSummary() {
    let subtotal = 0;
    $('.item-total').each(function() {
        subtotal += parseFloat($(this).text().replace(/,/g, ''));
    });
    let delivery = 50;
    let total = subtotal + delivery;
    $('#subtotal').text(subtotal.toFixed(2));
    $('#total').text(total.toFixed(2));
}

function updateCartCount() {
    $.get('cart_handler.php?action=get', function(res) {
        if (res.success) $('#cartCountBadge').text(res.cartCount);
    }, 'json');
}

// Update quantity
function updateQuantity(id, quantity) {
    $.post('cart_handler.php', { action: 'update', product_id: id, quantity: quantity }, function(res) {
        if (res.success) {
            let newTotal = (quantity * $(`#cart-item-${id} .qty-input`).data('price')).toFixed(2);
            $(`#cart-item-${id} .item-total`).text(newTotal);
            updateCartSummary();
            updateCartCount();
        }
    }, 'json');
}

// Remove item
$('.remove-item').click(function() {
    let id = $(this).data('id');
    $.post('cart_handler.php', { action: 'remove', product_id: id }, function(res) {
        if (res.success) {
            $(`#cart-item-${id}`).remove();
            if ($('.cart-card').length === 1) location.reload();
            updateCartSummary();
            updateCartCount();
        }
    }, 'json');
});

// Quantity buttons
$('.qty-minus').click(function() {
    let id = $(this).data('id');
    let input = $(`#cart-item-${id} .quantity-input`);
    let val = parseInt(input.val());
    if (val > 1) {
        input.val(val - 1);
        updateQuantity(id, val - 1);
    }
});
$('.qty-plus').click(function() {
    let id = $(this).data('id');
    let input = $(`#cart-item-${id} .quantity-input`);
    let val = parseInt(input.val());
    input.val(val + 1);
    updateQuantity(id, val + 1);
});
$('.quantity-input').change(function() {
    let id = $(this).data('id');
    let val = parseInt($(this).val());
    if (isNaN(val) || val < 1) val = 1;
    $(this).val(val);
    updateQuantity(id, val);
});

updateCartCount();
</script>
</body>
</html>