<?php
require_once 'config.php';

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

// Handle single potency add (existing)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_potency'])) {
    $medicine_id = (int)$_POST['medicine_id'];
    $medicine_name = $_POST['medicine_name'];
    $potency = (int)$_POST['potency'];
    $price = getPotencyPrice($potency, $pdo);
    $quantity = (int)$_POST['quantity'];
    $_SESSION['cart'][] = [
        'type' => 'single',
        'medicine_id' => $medicine_id,
        'medicine_name' => $medicine_name,
        'potency' => $potency,
        'price' => $price,
        'quantity' => $quantity
    ];
    header("Location: shop.php?added=1");
    exit;
}

// Handle combo add (existing)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_combo'])) {
    $combo_id = (int)$_POST['combo_id'];
    $stmt = $pdo->prepare("SELECT c.*, m.name as medicine_name FROM combos c JOIN medicines m ON c.medicine_id = m.id WHERE c.id = ?");
    $stmt->execute([$combo_id]);
    $combo = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($combo) {
        $_SESSION['cart'][] = [
            'type' => 'combo',
            'combo_id' => $combo['id'],
            'medicine_name' => $combo['medicine_name'],
            'potency_start' => $combo['potency_start'],
            'potency_end' => $combo['potency_end'],
            'package_price' => (float)$combo['package_price'],
            'quantity' => 1
        ];
    }
    header("Location: shop.php?added=1");
    exit;
}

// Handle bulk tick submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['bulk_add'])) {
    if (isset($_POST['ticked']) && is_array($_POST['ticked'])) {
        foreach ($_POST['ticked'] as $tick) {
            list($med_id, $potency) = explode('|', $tick);
            $med_id = (int)$med_id;
            $potency = (int)$potency;
            // Get medicine name
            $stmt = $pdo->prepare("SELECT name FROM medicines WHERE id = ?");
            $stmt->execute([$med_id]);
            $med_name = $stmt->fetchColumn();
            if ($med_name) {
                $price = getPotencyPrice($potency, $pdo);
                $_SESSION['cart'][] = [
                    'type' => 'single',
                    'medicine_id' => $med_id,
                    'medicine_name' => $med_name,
                    'potency' => $potency,
                    'price' => $price,
                    'quantity' => 1
                ];
            }
        }
    }
    header("Location: shop.php?bulk_added=1");
    exit;
}

// Search logic
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
if ($search !== '') {
    $stmt = $pdo->prepare("SELECT * FROM medicines WHERE name LIKE ? ORDER BY name");
    $stmt->execute(["%$search%"]);
} else {
    $stmt = $pdo->query("SELECT * FROM medicines ORDER BY name");
}
$medicines = $stmt->fetchAll(PDO::FETCH_ASSOC);

$prices = getAllPotencyPrices($pdo);
$cart_count = count($_SESSION['cart']);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>HomoeoCare – Shop</title>
    <link rel="stylesheet" href="style.css">
    <style>
        .view-toggle {
            display: flex;
            gap: 12px;
            margin-bottom: 20px;
            justify-content: flex-end;
        }
        .view-toggle button {
            background: #e0ece0;
            color: #2c5e2e;
            border: none;
            padding: 8px 20px;
            border-radius: 40px;
            cursor: pointer;
            font-weight: 500;
        }
        .view-toggle button.active {
            background: #2c5e2e;
            color: white;
        }
        .bulk-table {
            width: 100%;
            border-collapse: collapse;
            background: white;
            border-radius: 24px;
            overflow-x: auto;
            display: block;
        }
        .bulk-table th, .bulk-table td {
            border: 1px solid #cde0cd;
            padding: 10px 8px;
            text-align: center;
            font-size: 0.85rem;
        }
        .bulk-table th {
            background: #eef5ea;
            position: sticky;
            top: 0;
        }
        .medicine-name-col {
            text-align: left;
            font-weight: bold;
            background: #f9fff9;
            position: sticky;
            left: 0;
            background: white;
        }
        .bulk-table input[type="checkbox"] {
            width: 18px;
            height: 18px;
            cursor: pointer;
        }
        .selected-counter {
            background: #ff9800;
            color: white;
            padding: 6px 12px;
            border-radius: 40px;
            display: inline-block;
            margin-top: 16px;
        }
        .bulk-add-btn {
            background: #2c5e2e;
            color: white;
            padding: 10px 24px;
            border: none;
            border-radius: 40px;
            font-size: 1rem;
            cursor: pointer;
            margin-top: 16px;
        }
        .scrollable-table {
            overflow-x: auto;
            max-width: 100%;
        }
        @media (max-width: 700px) {
            .bulk-table th, .bulk-table td { padding: 6px 4px; font-size: 0.7rem; }
            .bulk-table input { transform: scale(0.8); }
        }
    </style>
</head>
<body>
<div class="container">
    <header>
        <h1>🌿 HomoeoCare</h1>
        <nav>
            <a href="index.php">Home</a>
            <a href="shop.php" class="active">Shop</a>
            <a href="cart.php">🛒 Cart <span class="cart-count"><?= $cart_count ?></span></a>
            <a href="admin.php">Admin</a>
        </nav>
    </header>

    <?php if (isset($_GET['added'])): ?>
        <div class="alert success">✓ Item added to cart!</div>
    <?php endif; ?>
    <?php if (isset($_GET['bulk_added'])): ?>
        <div class="alert success">✓ Selected items added to cart!</div>
    <?php endif; ?>

    <!-- Search bar -->
    <div class="search-bar">
        <form method="get" style="display: flex; gap: 10px; width: 100%;">
            <input type="text" name="search" placeholder="Search medicine by name..." value="<?= htmlspecialchars($search) ?>">
            <button type="submit">🔍 Search</button>
            <?php if ($search !== ''): ?>
                <a href="shop.php" class="clear-search" style="background:#999; padding:12px 20px; border-radius:60px; color:white; text-decoration:none;">Clear</a>
            <?php endif; ?>
        </form>
    </div>

    <!-- View toggles (preserve current view via JS) -->
    <div class="view-toggle">
        <button id="showCardsBtn" class="active">📦 Card View (Single/Combo)</button>
        <button id="showBulkBtn">✅ Bulk Tick View (M/1–M/30)</button>
    </div>

    <!-- CARD VIEW (existing) -->
    <div id="cardView">
        <?php if (empty($medicines)): ?>
            <div class="empty-cart">No medicines found. <a href="admin.php">Add medicines</a>.</div>
        <?php else: ?>
            <div class="medicine-grid">
                <?php foreach ($medicines as $med): ?>
                    <div class="medicine-card">
                        <h2><?= htmlspecialchars($med['name']) ?></h2>
                        <form method="post">
                            <input type="hidden" name="medicine_id" value="<?= $med['id'] ?>">
                            <input type="hidden" name="medicine_name" value="<?= htmlspecialchars($med['name']) ?>">
                            <div class="potency-row">
                                <select name="potency">
                                    <?php for ($p=1; $p<=30; $p++): ?>
                                        <option value="<?= $p ?>">M/<?= $p ?> (<?= number_format($prices[$p],2) ?> BDT)</option>
                                    <?php endfor; ?>
                                </select>
                                <input type="number" name="quantity" value="1" min="1" style="width:80px">
                                <button type="submit" name="add_potency">+ Add Single</button>
                            </div>
                        </form>
                        <?php
                        $comboStmt = $pdo->prepare("SELECT * FROM combos WHERE medicine_id = ?");
                        $comboStmt->execute([$med['id']]);
                        $combos = $comboStmt->fetchAll();
                        ?>
                        <?php if (!empty($combos)): ?>
                            <div class="combos">
                                <strong>🔥 Combo Packages:</strong><br>
                                <?php foreach ($combos as $combo): ?>
                                    <?php
                                    $normal_total = 0;
                                    for ($i=$combo['potency_start']; $i<=$combo['potency_end']; $i++) $normal_total += $prices[$i];
                                    $saving = $normal_total - $combo['package_price'];
                                    ?>
                                    <form method="post" style="display:inline-block">
                                        <input type="hidden" name="combo_id" value="<?= $combo['id'] ?>">
                                        <button type="submit" name="add_combo" class="btn-combo">
                                            M/<?= $combo['potency_start'] ?>–M/<?= $combo['potency_end'] ?> = <?= number_format($combo['package_price'],2) ?> BDT (Save <?= number_format($saving,2) ?>)
                                        </button>
                                    </form>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>

    <!-- BULK TICK VIEW (new) -->
    <div id="bulkView" style="display: none;">
        <?php if (empty($medicines)): ?>
            <div class="empty-cart">No medicines to display.</div>
        <?php else: ?>
            <form method="post" id="bulkForm">
                <div class="scrollable-table">
                    <table class="bulk-table">
                        <thead>
                            <tr>
                                <th>Medicine</th>
                                <?php for ($p=1; $p<=30; $p++): ?>
                                    <th>M/<?= $p ?><br><small><?= number_format($prices[$p],2) ?> ৳</small></th>
                                <?php endfor; ?>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($medicines as $med): ?>
                                <tr>
                                    <td class="medicine-name-col"><?= htmlspecialchars($med['name']) ?></td>
                                    <?php for ($p=1; $p<=30; $p++): ?>
                                        <td>
                                            <input type="checkbox" name="ticked[]" value="<?= $med['id'] . '|' . $p ?>" class="potency-chk" data-med="<?= $med['id'] ?>" data-pot="<?= $p ?>">
                                        </td>
                                    <?php endfor; ?>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <div style="text-align: center; margin-top: 20px;">
                    <span id="selectedCountDisplay" class="selected-counter">0 selected</span>
                    <button type="submit" name="bulk_add" class="bulk-add-btn">➕ Add Selected to Cart</button>
                </div>
            </form>
            <script>
                // Live counter for ticked checkboxes
                const checkboxes = document.querySelectorAll('#bulkForm .potency-chk');
                const countSpan = document.getElementById('selectedCountDisplay');
                function updateCount() {
                    let checked = 0;
                    checkboxes.forEach(cb => { if(cb.checked) checked++; });
                    countSpan.innerText = checked + ' selected';
                }
                checkboxes.forEach(cb => cb.addEventListener('change', updateCount));
                updateCount();
            </script>
        <?php endif; ?>
    </div>
</div>

<script>
    // Toggle between card view and bulk tick view
    const cardView = document.getElementById('cardView');
    const bulkView = document.getElementById('bulkView');
    const showCardsBtn = document.getElementById('showCardsBtn');
    const showBulkBtn = document.getElementById('showBulkBtn');

    showCardsBtn.addEventListener('click', () => {
        cardView.style.display = 'block';
        bulkView.style.display = 'none';
        showCardsBtn.classList.add('active');
        showBulkBtn.classList.remove('active');
    });
    showBulkBtn.addEventListener('click', () => {
        cardView.style.display = 'none';
        bulkView.style.display = 'block';
        showBulkBtn.classList.add('active');
        showCardsBtn.classList.remove('active');
    });
</script>
</body>
</html>