<?php
require_once 'includes/db.php';

if (!isset($_SESSION['cart'])) { $_SESSION['cart'] = []; }
if (isset($_POST['add_to_cart']) && isset($_POST['product_id'])) {
    $pid = (int)$_POST['product_id'];
    if (!in_array($pid, $_SESSION['cart'])) { $_SESSION['cart'][] = $pid; }
}
if (isset($_GET['remove'])) {
    $pid = (int)$_GET['remove'];
    $_SESSION['cart'] = array_diff($_SESSION['cart'], [$pid]);
    $_SESSION['cart'] = array_values($_SESSION['cart']);
}

$cart_products = [];
$total_amount = 0;
if (count($_SESSION['cart']) > 0) {
    $placeholders = implode(',', array_fill(0, count($_SESSION['cart']), '?'));
    $stmt = $pdo->prepare("SELECT * FROM products WHERE id IN ($placeholders)");
    $stmt->execute(array_values($_SESSION['cart']));
    $cart_products = $stmt->fetchAll();
    foreach ($cart_products as $cp) { $total_amount += $cp['price']; }
}

$checkout_error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['proceed_to_pay'])) {
    if (!isset($_SESSION['user_id'])) { 
        header("Location: login"); 
        exit; 
    }
    
    if (empty($_POST['selected_items'])) {
        $checkout_error = "Please select at least one item to proceed to checkout.";
    } else {
        $_SESSION['checkout_items'] = $_POST['selected_items'];
        header("Location: checkout");
        exit;
    }
}

$currency = defined('CURRENCY_SYMBOL') ? CURRENCY_SYMBOL : '৳';
if (is_numeric($currency)) {
    $currency = '৳';
}

$page_title = 'Shopping Cart';
require_once 'includes/header.php';
?>

<style>
    @import url('https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&family=Noto+Serif+Bengali:wght@300;400;500;600;700&display=swap');

    .details-wrapper { 
        font-family: 'Roboto', 'Noto Serif Bengali', sans-serif;
        margin: 30px auto 100px; 
        max-width: 1200px;
        padding: 0 15px;
        box-sizing: border-box;
        overflow-x: hidden;
    }
    
    .breadcrumb { font-size: 0.9rem; font-weight: 600; color: #64748b; margin-bottom: 25px; }
    .breadcrumb a { color: #00059E; text-decoration: none; }

    .details-grid { display: grid; grid-template-columns: 1fr; gap: 30px; align-items: start; }
    @media (min-width: 992px) { .details-grid { grid-template-columns: 1.8fr 1fr; gap: 40px; } }

    .desc-card { background: #ffffff; border: 1px solid #e2e8f0; border-radius: 8px; padding: 25px; width: 100%; box-sizing: border-box; overflow: hidden; }
    .desc-title { font-size: 1.2rem; font-weight: 700; color: #0f172a; margin-bottom: 20px; border-bottom: 2px solid #f1f5f9; padding-bottom: 12px; display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 10px; }
    
    .cart-item { display: flex; align-items: center; justify-content: space-between; padding: 15px 0; border-bottom: 1px solid #f1f5f9; flex-wrap: wrap; gap: 15px; }
    .cart-item:last-child { border-bottom: none; padding-bottom: 0; }
    .cart-item-left { display: flex; align-items: center; gap: 15px; flex: 1; min-width: 0; }
    .cart-item-img { width: 70px; height: 70px; object-fit: contain; border-radius: 6px; background: #f8fafc; border: 1px solid #e2e8f0; padding: 5px; flex-shrink: 0; }
    
    .cart-item-title { font-size: 1.05rem; font-weight: 700; color: #0f172a; margin-bottom: 5px; white-space: normal; word-break: break-word; }
    .cart-item-price { font-size: 1.15rem; font-weight: 700; color: #00059E; white-space: nowrap; }
    
    .btn-remove { color: #94a3b8; background: none; border: none; cursor: pointer; transition: 0.3s; display: flex; align-items: center; justify-content: center; }
    .btn-remove:hover { color: #ef4444; }

    .info-sidebar { position: sticky; top: 90px; }
    .info-card { background: #ffffff; border: 1px solid #e2e8f0; border-radius: 8px; padding: 25px; box-sizing: border-box; width: 100%; }
    
    .info-title { font-size: 1.3rem; font-weight: 700; color: #0f172a; margin-bottom: 20px; border-bottom: 2px solid #f1f5f9; padding-bottom: 12px; }
    .sum-row { display: flex; justify-content: space-between; font-size: 1rem; color: #64748b; font-weight: 600; margin-bottom: 15px; flex-wrap: wrap; gap: 10px; }
    
    .info-price-box { margin-top: 10px; margin-bottom: 25px; padding-top: 20px; border-top: 1px dashed #e2e8f0; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px; }
    .info-price { font-size: 1.8rem; font-weight: 700; color: #00059E !important; word-break: break-all; }

    .btn-add { display: flex; align-items: center; justify-content: center; gap: 8px; width: 100%; background: #00059E; color: white; padding: 16px; border-radius: 6px; font-size: 1.1rem; font-weight: 500; border: none; cursor: pointer; font-family: 'Roboto', sans-serif; text-transform: uppercase; letter-spacing: 0.5px; box-sizing: border-box; }
    .btn-add:hover { background: #00037a; }

    .alert-danger { background: #fee2e2; border: 1px solid #f87171; color: #ef4444; padding: 15px; border-radius: 4px; margin-bottom: 25px; font-family: 'Roboto', sans-serif; word-break: break-word; }

    .custom-checkbox {
        width: 20px;
        height: 20px;
        cursor: pointer;
        accent-color: #00059E;
        flex-shrink: 0;
    }
</style>

<div class="details-wrapper">
    
    <div class="breadcrumb">
        <a href="index">Home</a> / <a href="products">Store</a> / <span style="color: #0f172a;">Shopping Cart</span>
    </div>

    <?php if($checkout_error): ?>
        <div class="alert-danger"><?php echo htmlspecialchars($checkout_error); ?></div>
    <?php endif; ?>

    <?php if(empty($cart_products)): ?>
        <div class="desc-card" style="text-align: center; padding: 80px 20px;">
            <svg style="width: 60px; height: 60px; color: #cbd5e1; margin-bottom: 15px;" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z" /></svg>
            <h2 style="color: #0f172a; margin-bottom: 10px; font-size: 1.5rem; font-weight: 700;">Your Cart is Empty</h2>
            <p style="color: #64748b; margin-bottom: 25px;">You have not added any items to your cart yet.</p>
            <a href="index" style="display: inline-block; background: #00059E; color: white; padding: 12px 30px; border-radius: 4px; font-weight: 500; text-decoration: none;">Continue Shopping</a>
        </div>
    <?php else: ?>

        <form action="" method="POST" id="cart-form">
            <div class="details-grid">
                <div style="min-width: 0;">
                    <div class="desc-card">
                        <div class="desc-title">
                            <div style="display: flex; align-items: center; gap: 12px;">
                                <input type="checkbox" id="select-all" class="custom-checkbox" checked title="Select All">
                                <div style="display: flex; align-items: center; gap: 8px;">
                                    <svg width="22" height="22" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z" /></svg>
                                    Review Order
                                </div>
                            </div>
                            <span style="font-size: 0.9rem; color: #64748b; font-weight: 600;"><span id="selected-count"><?php echo count($cart_products); ?></span> Item(s) Selected</span>
                        </div>
                        
                        <?php foreach($cart_products as $cp): ?>
                            <div class="cart-item">
                                <div class="cart-item-left">
                                    <input type="checkbox" name="selected_items[]" value="<?php echo $cp['id']; ?>" data-price="<?php echo $cp['price']; ?>" class="custom-checkbox item-checkbox" checked>
                                    <img src="<?php echo get_image_url('products/images', $cp['main_image']); ?>" alt="Product" class="cart-item-img">
                                    <div style="min-width: 0;">
                                        <div class="cart-item-title"><?php echo htmlspecialchars($cp['title']); ?></div>
                                        <div style="display: flex; align-items: center; gap: 2px;">
                                            <?php for($i=0; $i<5; $i++): ?>
                                                <svg width="12" height="12" fill="#00059E" viewBox="0 0 24 24"><path d="M12 17.27L18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z"/></svg>
                                            <?php endfor; ?>
                                        </div>
                                    </div>
                                </div>
                                <div style="display: flex; align-items: center; gap: 15px; margin-left: auto;">
                                    <div class="cart-item-price"><?php echo $currency . number_format($cp['price'], 2); ?></div>
                                    <a href="cart?remove=<?php echo $cp['id']; ?>" class="btn-remove" title="Remove Item">
                                        <svg width="22" height="22" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" /></svg>
                                    </a>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>

                <div style="min-width: 0;">
                    <div class="info-sidebar">
                        <div class="info-card">
                            <h2 class="info-title">Order Summary</h2>
                            <div class="sum-row">
                                <span>Subtotal</span>
                                <span id="subtotal-amount"><?php echo $currency . number_format($total_amount, 2); ?></span>
                            </div>
                            <div class="info-price-box">
                                <span style="font-weight: 700; color: #0f172a;">Total</span>
                                <span class="info-price" id="total-amount"><?php echo $currency . number_format($total_amount, 2); ?></span>
                            </div>
                            <button type="submit" name="proceed_to_pay" class="btn-add" id="checkout-btn">
                                <svg width="24" height="24" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.5"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>
                                Proceed to Checkout
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </form>

        <script>
            document.addEventListener('DOMContentLoaded', function() {
                const selectAllCb = document.getElementById('select-all');
                const itemCheckboxes = document.querySelectorAll('.item-checkbox');
                const subtotalEl = document.getElementById('subtotal-amount');
                const totalEl = document.getElementById('total-amount');
                const countEl = document.getElementById('selected-count');
                const checkoutBtn = document.getElementById('checkout-btn');
                const currencySymbol = '<?php echo $currency; ?>';

                function updateCartTotals() {
                    let total = 0;
                    let count = 0;

                    itemCheckboxes.forEach(cb => {
                        if (cb.checked) {
                            total += parseFloat(cb.getAttribute('data-price'));
                            count++;
                        }
                    });

                    const formattedTotal = total.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
                    
                    subtotalEl.innerText = currencySymbol + formattedTotal;
                    totalEl.innerText = currencySymbol + formattedTotal;
                    countEl.innerText = count;

                    if (count === itemCheckboxes.length && count > 0) {
                        selectAllCb.checked = true;
                    } else {
                        selectAllCb.checked = false;
                    }

                    if (count === 0) {
                        checkoutBtn.style.opacity = '0.5';
                        checkoutBtn.style.cursor = 'not-allowed';
                    } else {
                        checkoutBtn.style.opacity = '1';
                        checkoutBtn.style.cursor = 'pointer';
                    }
                }

                selectAllCb.addEventListener('change', function() {
                    itemCheckboxes.forEach(cb => {
                        cb.checked = this.checked;
                    });
                    updateCartTotals();
                });

                itemCheckboxes.forEach(cb => {
                    cb.addEventListener('change', updateCartTotals);
                });

                document.getElementById('cart-form').addEventListener('submit', function(e) {
                    let selectedCount = document.querySelectorAll('.item-checkbox:checked').length;
                    if (selectedCount === 0) {
                        e.preventDefault();
                        alert('Please select at least one item to proceed to checkout.');
                    }
                });

                updateCartTotals();
            });
        </script>
    <?php endif; ?>
</div>

<?php require_once 'includes/footer.php'; ?>
<?php require_once 'includes/mobile-nav.php'; ?>
