<?php
require_once 'config.php';

if (!isset($_SESSION['cart'])) $_SESSION['cart'] = [];

// Remove item
if (isset($_GET['remove'])) {
    unset($_SESSION['cart'][$_GET['remove']]);
    $_SESSION['cart'] = array_values($_SESSION['cart']);
    header("Location: cart.php");
    exit;
}

// Calculate total
$total = 0;
foreach ($_SESSION['cart'] as $item) {
    if ($item['type'] === 'single') {
        $total += $item['price'] * $item['quantity'];
    } else {
        $total += $item['package_price'] * $item['quantity'];
    }
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Cart – HomoeoCare</title>
    <link rel="stylesheet" href="style.css">
    <style>
        .two-buttons {
            display: flex;
            gap: 20px;
            margin: 20px 0;
            flex-wrap: wrap;
        }
        .btn-whatsapp {
            background: #25D366;
            color: white;
            border: none;
            padding: 14px 24px;
            border-radius: 60px;
            font-size: 1rem;
            font-weight: bold;
            cursor: pointer;
            flex: 1;
        }
        .btn-local {
            background: #2c5e2e;
            color: white;
            border: none;
            padding: 14px 24px;
            border-radius: 60px;
            font-size: 1rem;
            font-weight: bold;
            cursor: pointer;
            flex: 1;
        }
        .payment-options {
            margin: 20px 0;
            padding: 20px;
            background: #f9fff9;
            border-radius: 24px;
            border: 1px solid #cde0cd;
        }
        .payment-methods {
            display: flex;
            gap: 20px;
            flex-wrap: wrap;
            margin-bottom: 15px;
        }
        .payment-methods label {
            cursor: pointer;
            padding: 8px 16px;
            background: #eef5ea;
            border-radius: 40px;
        }
        .payment-details {
            margin-top: 15px;
            padding: 15px;
            background: #fff8e7;
            border-radius: 16px;
            border-left: 4px solid #ff9800;
        }
        .transaction-field {
            margin-top: 12px;
        }
        .transaction-field input {
            width: 100%;
            padding: 10px;
            border-radius: 40px;
            border: 1px solid #cde0cd;
        }
        .instruction {
            font-size: 0.85rem;
            color: #5a5a5a;
            margin-top: 5px;
        }
        .hidden {
            display: none;
        }
    </style>
</head>
<body>
<div class="container">
    <header>
        <h1>🛒 Your Cart</h1>
        <nav>
            <a href="shop.php">← Continue Shopping</a>
            <a href="admin.php">Admin</a>
            <a href="track.php">Track Order</a>
        </nav>
    </header>

    <?php if (empty($_SESSION['cart'])): ?>
        <div class="empty-cart">Cart is empty. <a href="shop.php">Browse medicines</a></div>
    <?php else: ?>
        <table class="cart-table">
            <thead>
                <tr><th>Medicine</th><th>Details</th><th>Qty</th><th>Unit price</th><th>Total</th><th></th></tr>
            </thead>
            <tbody>
            <?php foreach ($_SESSION['cart'] as $idx => $item): ?>
                <tr>
                    <td><?= htmlspecialchars($item['medicine_name']) ?></td>
                    <td>
                        <?php if ($item['type'] === 'single'): ?>
                            M/<?= $item['potency'] ?>
                        <?php else: ?>
                            Combo M/<?= $item['potency_start'] ?>–M/<?= $item['potency_end'] ?>
                        <?php endif; ?>
                    </td>
                    <td><?= $item['quantity'] ?></td>
                    <td><?= number_format($item['type']==='single' ? $item['price'] : $item['package_price'], 2) ?> BDT</td>
                    <td><?= number_format($item['type']==='single' ? $item['price']*$item['quantity'] : $item['package_price']*$item['quantity'], 2) ?> BDT</td>
                    <td><a href="?remove=<?= $idx ?>" class="remove-link">🗑️</a></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
            <tfoot>
                <tr><td colspan="4" align="right"><strong>Total:</strong></td>
                <td colspan="2"><strong><?= number_format($total,2) ?> BDT</strong></td>
            </tr>
            </tfoot>
        </table>

        <div class="checkout-section">
            <h2>Checkout</h2>
            <form id="order-form">
                <div class="form-group"><label>Full Name *</label><input type="text" id="customer_name" required></div>
                <div class="form-group"><label>Phone Number *</label><input type="tel" id="customer_phone" required></div>
                <div class="form-group"><label>Delivery Address *</label><textarea id="customer_address" rows="2" required></textarea></div>
                
                <!-- Local Payment Options (Always Visible) -->
                <div class="payment-options">
                    <h3>💳 Local Payment Methods</h3>
                    <div class="payment-methods">
                        <label><input type="radio" name="local_payment" value="Cash on Delivery" checked> Cash on Delivery</label>
                        <label><input type="radio" name="local_payment" value="bKash"> bKash (01775121112)</label>
                        <label><input type="radio" name="local_payment" value="Nagad"> Nagad (01681519799)</label>
                    </div>
                    
                    <!-- Dynamic Payment Instructions -->
                    <div id="bkashInfo" class="payment-details hidden">
                        <strong>📱 bKash Payment Instructions:</strong><br>
                        Send the exact amount <strong><?= number_format($total,2) ?> BDT</strong> to bKash number <strong>01775121112</strong> (Merchant).<br>
                        After successful payment, enter the Transaction ID (TrxID) below.
                    </div>
                    <div id="nagadInfo" class="payment-details hidden">
                        <strong>📱 Nagad Payment Instructions:</strong><br>
                        Send the exact amount <strong><?= number_format($total,2) ?> BDT</strong> to Nagad number <strong>01681519799</strong> (Merchant).<br>
                        After successful payment, enter the Transaction ID below.
                    </div>
                    
                    <div class="transaction-field" id="transactionField" style="display: none;">
                        <label>Transaction ID (TrxID):</label>
                        <input type="text" id="transaction_id" placeholder="e.g., 8N7A2K5M9P">
                        <div class="instruction">*Required for bKash/Nagad orders. Your order will be confirmed after admin verifies payment.</div>
                    </div>
                </div>

                <div class="two-buttons">
                    <button type="button" id="whatsappBtn" class="btn-whatsapp">📲 Order via WhatsApp (No Payment)</button>
                    <button type="button" id="localPaymentBtn" class="btn-local">✅ Place Order with Local Payment</button>
                </div>
            </form>
            <div id="orderMessage"></div>
        </div>
    <?php endif; ?>
</div>

<script>
// Get elements
const bkashInfo = document.getElementById('bkashInfo');
const nagadInfo = document.getElementById('nagadInfo');
const transactionField = document.getElementById('transactionField');
const transactionIdInput = document.getElementById('transaction_id');
const radioButtons = document.querySelectorAll('input[name="local_payment"]');

// Show/hide payment instructions based on selection
function updatePaymentUI() {
    const selected = document.querySelector('input[name="local_payment"]:checked').value;
    // Hide both instruction divs first
    bkashInfo.classList.add('hidden');
    nagadInfo.classList.add('hidden');
    
    if (selected === 'bKash') {
        bkashInfo.classList.remove('hidden');
        transactionField.style.display = 'block';
    } else if (selected === 'Nagad') {
        nagadInfo.classList.remove('hidden');
        transactionField.style.display = 'block';
    } else {
        transactionField.style.display = 'none';
    }
}

radioButtons.forEach(radio => {
    radio.addEventListener('change', updatePaymentUI);
});
// Initialize
updatePaymentUI();

// WhatsApp Order
document.getElementById('whatsappBtn').addEventListener('click', function() {
    const name = document.getElementById('customer_name').value.trim();
    const phone = document.getElementById('customer_phone').value.trim();
    const address = document.getElementById('customer_address').value.trim();
    if (!name || !phone || !address) return alert("Please fill all fields");
    
    this.disabled = true;
    this.textContent = "Processing...";
    
    fetch('order.php', {
        method: 'POST',
        headers: {'Content-Type':'application/json'},
        body: JSON.stringify({
            name: name,
            phone: phone,
            address: address,
            payment_method: 'WhatsApp Order',
            order_type: 'whatsapp',
            transaction_id: ''
        })
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            document.getElementById('orderMessage').innerHTML = `<div class="alert success">✅ Order placed! Opening WhatsApp...</div>`;
            window.open(data.whatsapp_url, '_blank');
            setTimeout(() => window.location.href = 'shop.php?order=placed', 2000);
        } else alert("Error: "+data.error);
        this.disabled = false;
        this.textContent = "📲 Order via WhatsApp (No Payment)";
    })
    .catch(err => { alert(err.message); this.disabled=false; this.textContent="📲 Order via WhatsApp (No Payment)"; });
});

// Local Payment Order
document.getElementById('localPaymentBtn').addEventListener('click', function() {
    const name = document.getElementById('customer_name').value.trim();
    const phone = document.getElementById('customer_phone').value.trim();
    const address = document.getElementById('customer_address').value.trim();
    if (!name || !phone || !address) return alert("Please fill all fields");
    
    const paymentMethod = document.querySelector('input[name="local_payment"]:checked').value;
    let transactionId = '';
    
    if (paymentMethod !== 'Cash on Delivery') {
        transactionId = transactionIdInput.value.trim();
        if (!transactionId) {
            alert("Please enter the Transaction ID after sending money.");
            return;
        }
    }
    
    this.disabled = true;
    this.textContent = "Placing Order...";
    
    fetch('order.php', {
        method: 'POST',
        headers: {'Content-Type':'application/json'},
        body: JSON.stringify({
            name: name,
            phone: phone,
            address: address,
            payment_method: paymentMethod,
            order_type: 'local',
            transaction_id: transactionId
        })
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            let msg = `✅ Order #${data.order_id} placed successfully!<br>Payment method: ${paymentMethod}<br>`;
            if (paymentMethod !== 'Cash on Delivery') {
                msg += `Transaction ID: ${transactionId}<br>Admin will verify payment and confirm your order.<br>`;
            } else {
                msg += `Your order is pending. Admin will process it soon.<br>`;
            }
            msg += `You will receive SMS when order is confirmed.<br><a href="track.php">Click here to track your order</a>`;
            document.getElementById('orderMessage').innerHTML = `<div class="alert success">${msg}</div>`;
            setTimeout(() => window.location.href = 'shop.php?order=placed', 4000);
        } else alert("Error: "+data.error);
        this.disabled = false;
        this.textContent = "✅ Place Order with Local Payment";
    })
    .catch(err => { alert(err.message); this.disabled=false; this.textContent="✅ Place Order with Local Payment"; });
});
</script>
</body>
</html>