<?php require_once __DIR__ . '/../../layouts/header.php'; ?>

<div class="page-header" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 2rem;">
    <h2>Inventory Management</h2>
    <div class="header-actions" style="display: flex; gap: 1rem; align-items: center; flex-wrap: wrap;">
        <?php if ($_SESSION['role'] === 'admin'): ?>
        <select id="branchFilter" onchange="filterInventory()" style="padding: 0.75rem 1rem; border-radius: 8px; border: 1px solid var(--glass-border); background: rgba(15,23,42,0.6); color: white; outline: none; min-width: 150px;">
            <option value="all" <?php echo ($selectedBranch === 'all') ? 'selected' : ''; ?>>All Branches</option>
            <?php foreach($branches as $b): ?>
                <option value="<?php echo $b['id']; ?>" <?php echo ($selectedBranch == $b['id']) ? 'selected' : ''; ?> style="background: var(--bg-dark);">
                    <?php echo htmlspecialchars($b['name']); ?>
                </option>
            <?php endforeach; ?>
        </select>
        <?php endif; ?>

        <select id="stockLevelFilter" onchange="filterInventory()" style="padding: 0.75rem 1rem; border-radius: 8px; border: 1px solid var(--glass-border); background: rgba(15,23,42,0.6); color: white; outline: none; min-width: 150px; color-scheme: dark;">
            <option value="all" <?php echo ($selectedStockLevel === 'all') ? 'selected' : ''; ?>>All Stock Levels</option>
            <option value="In-stock" <?php echo ($selectedStockLevel === 'In-stock') ? 'selected' : ''; ?>>In Stock</option>
            <option value="low-stock" <?php echo ($selectedStockLevel === 'low-stock') ? 'selected' : ''; ?>>Low Stock</option>
            <option value="out-of stock" <?php echo ($selectedStockLevel === 'out-of stock') ? 'selected' : ''; ?>>Out of Stock</option>
        </select>
        
        <input type="text" id="searchInput" placeholder="Search medicine or generic name..." value="<?php echo htmlspecialchars($searchQuery ?? ''); ?>" style="padding: 0.75rem 1rem; border-radius: 8px; border: 1px solid var(--glass-border); background: rgba(15,23,42,0.6); color: white; width: 300px; outline: none;">
        <a href="/inventory/bulk" class="btn-primary" style="width: auto; margin-top: 0; text-decoration: none; background: rgba(79, 70, 229, 0.2); border: 1px solid rgba(79, 70, 229, 0.4); color: var(--primary-color);">Bulk Upload</a>
        <a href="/inventory/create" class="btn-primary" style="width: auto; margin-top: 0; text-decoration: none;">+ Add Stock</a>
    </div>
</div>

<div class="card" style="padding: 0;">
    <div class="data-grid" style="display: grid; grid-template-columns: 1fr; gap: 1.5rem;" id="inventoryTable">
        <?php 
        $isFirst = true;
        foreach($groupedInventory as $medId => $group): 
            $activeQty = intval($group['active_quantity'] ?? 0);
            $reorderLevel = intval($group['reorder_level'] ?? 10);
            if ($activeQty === 0) {
                $medStockLevel = 'out-of stock';
                $medLevelStyle = 'background: rgba(239, 68, 68, 0.15); color: #ef4444; border: 1px solid rgba(239, 68, 68, 0.3);';
            } elseif ($activeQty <= $reorderLevel) {
                $medStockLevel = 'low-stock';
                $medLevelStyle = 'background: rgba(245, 158, 11, 0.15); color: #f59e0b; border: 1px solid rgba(245, 158, 11, 0.3);';
            } else {
                $medStockLevel = 'In-stock';
                $medLevelStyle = 'background: rgba(16, 185, 129, 0.15); color: #10b981; border: 1px solid rgba(16, 185, 129, 0.3);';
            }
        ?>
        <div class="card medicine-group-card searchable-group" data-medid="<?php echo $medId; ?>" style="padding: 1.5rem; border: 1px solid var(--glass-border); background: rgba(15,23,42,0.4); border-radius: 12px; position: relative;">
            <!-- Group Header -->
            <div class="medicine-group-header" data-medid="<?php echo $medId; ?>" style="display: flex; justify-content: space-between; align-items: flex-start; cursor: pointer; gap: 1rem; flex-wrap: wrap;">
                <div style="display: flex; align-items: flex-start; gap: 1rem; flex: 1; min-width: 250px;">
                    <div style="margin-top: 0.25rem;">
                        <i class="ph <?php echo $isFirst ? 'ph-caret-down' : 'ph-caret-right'; ?> toggle-icon" id="toggle-icon-<?php echo $medId; ?>" style="color: var(--text-muted); font-size: 1.5rem; transition: transform 0.3s ease;"></i>
                    </div>
                    <div>
                        <strong style="font-size: 1.05rem; color: white;" class="med-name"><?php echo htmlspecialchars($group['medicine_name']); ?></strong>
                        <?php if (!empty($group['item_code'])): ?>
                            <span style="margin-left: 0.5rem; font-size: 0.85rem; padding: 0.15rem 0.4rem; background: rgba(79, 70, 229, 0.15); border: 1px solid rgba(79, 70, 229, 0.3); border-radius: 4px; color: #a5b4fc;"><?php echo htmlspecialchars($group['item_code']); ?></span>
                        <?php endif; ?>
                        <?php if (!empty($group['generic_name'])): ?>
                            <br><span style="color: var(--text-muted); font-size: 0.95rem;"><?php echo htmlspecialchars($group['generic_name']); ?></span>
                        <?php endif; ?>
                    </div>
                </div>
                
                <div style="display: flex; gap: 1.5rem; align-items: center; flex-wrap: wrap;">
                    <div style="text-align: right;">
                        <span style="color: var(--text-muted); display: block; font-size: 0.8rem; margin-bottom: 0.25rem;">Total Stock</span>
                        <span style="padding: 0.25rem 0.75rem; border-radius: 6px; font-weight: bold; background: rgba(79, 70, 229, 0.2); color: #818cf8; font-size: 1.1rem;">
                            <?php echo $group['total_quantity']; ?>
                        </span>
                    </div>
                    <div style="text-align: right;">
                        <span style="color: var(--text-muted); display: block; font-size: 0.8rem; margin-bottom: 0.25rem;">Expiry Alert</span>
                        <span style="color: var(--text-light); font-weight: bold;"><?php echo htmlspecialchars($group['expiry_alert_days'] ?? '30'); ?> days</span>
                    </div>
                    <div style="text-align: right;">
                        <span style="color: var(--text-muted); display: block; font-size: 0.8rem; margin-bottom: 0.25rem;">Status</span>
                        <span style="<?php echo $medLevelStyle; ?> padding: 0.25rem 0.75rem; border-radius: 6px; font-size: 0.85rem; font-weight: 600; text-transform: uppercase;"><?php echo htmlspecialchars($medStockLevel); ?></span>
                    </div>
                </div>
            </div>

            <!-- Batches Grid -->
            <div class="batches-container batch-row-<?php echo $medId; ?>" style="margin-top: 1.5rem; padding-top: 1.5rem; border-top: 1px solid rgba(255,255,255,0.05); <?php echo $isFirst ? '' : 'display: none;'; ?>">
                <h4 style="color: var(--text-muted); font-size: 0.9rem; margin-bottom: 1rem; text-transform: uppercase; letter-spacing: 0.05em;">Batches</h4>
                <div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 1rem;">
                    <?php foreach($group['batches'] as $b): ?>
                    <?php 
                        $expiryDate = new DateTime($b['expiry_date']);
                        $today = new DateTime();
                        $diff = $today->diff($expiryDate)->format("%r%a");
                        
                        $expiryColor = '#34d399'; // Green
                        if ($diff < 0) {
                            $expiryColor = '#ef4444'; // Red (Expired)
                        } elseif ($diff <= 30) {
                            $expiryColor = '#f59e0b'; // Orange (Expiring soon)
                        }

                        $isReturned = (strtolower($b['stock_level']) === 'returned' || strtolower($b['status']) === 'returned');
                        $cardBorder = $isReturned ? 'border: 1px solid rgba(239, 68, 68, 0.5); box-shadow: 0 0 10px rgba(239, 68, 68, 0.1);' : 'border: 1px solid rgba(255,255,255,0.05);';
                    ?>
                    <div class="card batch-card" style="padding: 1.25rem; background: rgba(0,0,0,0.2); <?php echo $cardBorder; ?> border-radius: 8px; position: relative;">
                        <?php if($isReturned): ?>
                            <div style="position: absolute; top: -8px; right: -8px; background: #ef4444; color: white; font-size: 0.65rem; font-weight: bold; padding: 0.2rem 0.5rem; border-radius: 4px; text-transform: uppercase; box-shadow: 0 2px 4px rgba(0,0,0,0.3); z-index: 10;">Returned</div>
                        <?php endif; ?>
                        <div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 1rem;">
                            <div>
                                <strong style="color: #c084fc; font-size: 1.1rem;" class="batch-num"><?php echo htmlspecialchars($b['batch_number']); ?></strong>
                                <br><span style="color: var(--text-muted); font-size: 0.85rem;"><?php echo htmlspecialchars($b['branch_name']); ?></span>
                            </div>
                            <span style="padding: 0.15rem 0.5rem; border-radius: 4px; font-weight: bold; background: rgba(255, 255, 255, 0.05); color: var(--text-light);"><?php echo $b['quantity']; ?> qty</span>
                        </div>
                        
                        <div style="display: flex; flex-wrap: wrap; gap: 0.75rem; margin-bottom: 1rem; font-size: 0.85rem;">
                            <div style="flex: 1 1 45%; min-width: 130px;">
                                <span style="color: var(--text-muted); display: block; font-size: 0.75rem; text-transform: uppercase;">Cost</span>
                                <span style="color: var(--text-light); font-weight: 500;"><?php echo htmlspecialchars($_SESSION['currency_code'] ?? '$'); ?> <?php echo number_format($b['unit_price'], 2); ?></span>
                            </div>
                            <div style="flex: 1 1 45%; min-width: 130px;">
                                <span style="color: var(--text-muted); display: block; font-size: 0.75rem; text-transform: uppercase;">Retail</span>
                                <strong style="color: var(--text-light);"><?php echo htmlspecialchars($_SESSION['currency_code'] ?? '$'); ?> <?php echo number_format($b['selling_price'], 2); ?></strong>
                            </div>
                            <div style="flex: 1 1 45%; min-width: 130px;">
                                <span style="color: var(--text-muted); display: block; font-size: 0.75rem; text-transform: uppercase;">Expiry</span>
                                <strong style="color: <?php echo $expiryColor; ?>;"><?php echo htmlspecialchars($b['expiry_date']); ?></strong>
                                <?php if($diff < 0): ?>
                                    <small style="color: #ef4444; display:block;">Expired</small>
                                <?php endif; ?>
                            </div>
                            <div style="flex: 1 1 45%; min-width: 130px;">
                                <span style="color: var(--text-muted); display: block; font-size: 0.75rem; text-transform: uppercase;">Added</span>
                                <span style="color: var(--text-light);"><?php echo !empty($b['created_at']) ? date('Y-m-d', strtotime($b['created_at'])) : '-'; ?></span>
                            </div>
                        </div>
                        
                        <div style="display: flex; justify-content: flex-end; gap: 0.5rem; border-top: 1px dashed rgba(255,255,255,0.1); padding-top: 0.75rem;">
                            <button type="button" onclick="openWithdrawModal(<?php echo $b['id']; ?>, <?php echo intval($b['quantity']); ?>)" title="Withdraw Stock" style="background: rgba(245, 158, 11, 0.1); border: 1px solid rgba(245, 158, 11, 0.2); color: #f59e0b; padding: 0.4rem; border-radius: 6px; cursor: pointer; transition: all 0.3s ease; display: inline-flex; align-items: center; justify-content: center;">
                                <i class="ph ph-minus-circle" style="font-size: 1.1rem;"></i>
                            </button>
                            <a href="/inventory/edit/<?php echo $b['id']; ?>" title="Edit Batch" style="background: rgba(79, 70, 229, 0.1); border: 1px solid rgba(79, 70, 229, 0.2); color: var(--primary-color); padding: 0.4rem; border-radius: 6px; text-decoration: none; display: inline-flex; align-items: center; justify-content: center; transition: all 0.3s ease;">
                                <i class="ph ph-pencil-simple" style="font-size: 1.1rem;"></i>
                            </a>
                            <button type="button" onclick="openDeleteModal(<?php echo $b['id']; ?>)" title="Delete Batch" style="background: rgba(239, 68, 68, 0.1); border: 1px solid rgba(239, 68, 68, 0.2); color: #ef4444; padding: 0.4rem; border-radius: 6px; cursor: pointer; transition: all 0.3s ease; display: inline-flex; align-items: center; justify-content: center;">
                                <i class="ph ph-trash" style="font-size: 1.1rem;"></i>
                            </button>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
        <?php 
        $isFirst = false;
        endforeach; 
        ?>
        
        <?php if(empty($groupedInventory)): ?>
            <div id="noInventoryRow" style="padding: 2rem; text-align: center; color: var(--text-muted); background: rgba(15,23,42,0.4); border-radius: 12px; border: 1px dashed var(--glass-border);">No inventory stock found.</div>
        <?php endif; ?>
    </div>
    
    <!-- Pagination -->
    <?php if($totalPages > 1): ?>
    <div style="display: flex; justify-content: space-between; align-items: center; padding: 1rem; border-top: 1px solid var(--glass-border);">
        <span style="color: var(--text-muted);">Showing Page <?php echo $page; ?> of <?php echo $totalPages; ?></span>
        <div style="display: flex; gap: 0.5rem;">
            <?php 
            $paginationParams = $_GET;
            ?>
            <?php if($page > 1): ?>
                <?php 
                $paginationParams['page'] = $page - 1;
                $prevUrl = '?' . http_build_query($paginationParams);
                ?>
                <a href="<?php echo htmlspecialchars($prevUrl); ?>" style="padding: 0.5rem 1rem; background: rgba(255,255,255,0.1); color: white; text-decoration: none; border-radius: 6px; font-size: 0.9rem;">Previous</a>
            <?php endif; ?>
            
            <?php if($page < $totalPages): ?>
                <?php 
                $paginationParams['page'] = $page + 1;
                $nextUrl = '?' . http_build_query($paginationParams);
                ?>
                <a href="<?php echo htmlspecialchars($nextUrl); ?>" style="padding: 0.5rem 1rem; background: rgba(255,255,255,0.1); color: white; text-decoration: none; border-radius: 6px; font-size: 0.9rem;">Next</a>
            <?php endif; ?>
        </div>
    </div>
    <?php endif; ?>
</div>

<!-- Modals -->
<div id="withdrawModal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.7); z-index: 1000; justify-content: center; align-items: center; backdrop-filter: blur(5px);">
    <div class="card" style="width: 100%; max-width: 400px; animation: slideUp 0.3s ease;">
        <h3 style="margin-bottom: 1rem; border-bottom: 1px solid var(--glass-border); padding-bottom: 0.5rem;">Withdraw Stock</h3>
        <form id="withdrawForm" method="POST" action="">
            <div class="input-group" style="margin-bottom: 1rem;">
                <label for="available_quantity">Available Quantity</label>
                <input type="number" id="available_quantity" readonly style="width: 100%; padding: 0.75rem; background: rgba(255,255,255,0.05); border: 1px solid var(--glass-border); color: var(--text-muted); cursor: not-allowed;">
            </div>
            <div class="input-group" style="margin-bottom: 1rem;">
                <label for="withdraw_quantity">Quantity to Withdraw</label>
                <input type="number" id="withdraw_quantity" name="withdraw_quantity" min="1" required style="width: 100%; padding: 0.75rem;">
            </div>
            <div class="input-group" style="margin-bottom: 1rem;">
                <label for="withdrawal_comment">Comments / Reason</label>
                <textarea id="withdrawal_comment" name="withdrawal_comment" rows="3" style="width: 100%; padding: 0.75rem; border-radius: 8px; border: 1px solid var(--glass-border); background: rgba(15,23,42,0.6); color: white; outline: none; font-family: 'Inter', sans-serif;" placeholder="e.g. Expired, damaged, transferred to another branch..."></textarea>
            </div>
            <div style="display: flex; gap: 1rem; margin-top: 1.5rem;">
                <button type="button" class="btn-primary" style="flex: 1; background: transparent; border: 1px solid var(--glass-border); margin-top: 0; color: white;" onclick="closeModals()">Cancel</button>
                <button type="submit" class="btn-primary" style="flex: 1; margin-top: 0; background: #f59e0b;">Withdraw</button>
            </div>
        </form>
    </div>
</div>

<div id="deleteModal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.7); z-index: 1000; justify-content: center; align-items: center; backdrop-filter: blur(5px);">
    <div class="card" style="width: 100%; max-width: 400px; animation: slideUp 0.3s ease;">
        <h3 style="margin-bottom: 1rem; color: #ef4444; border-bottom: 1px solid var(--glass-border); padding-bottom: 0.5rem;">Confirm Delete</h3>
        <p style="margin-bottom: 1.5rem; color: var(--text-muted);">Are you sure you want to permanently delete this batch? This action cannot be undone.</p>
        <form id="deleteForm" method="POST" action="">
            <div style="display: flex; gap: 1rem;">
                <button type="button" class="btn-primary" style="flex: 1; background: transparent; border: 1px solid var(--glass-border); margin-top: 0; color: white;" onclick="closeModals()">Cancel</button>
                <button type="submit" class="btn-primary" style="flex: 1; margin-top: 0; background: #ef4444;">Yes, Delete</button>
            </div>
        </form>
    </div>
</div>

<script>
document.getElementById('searchInput').addEventListener('keypress', function(e) {
    if (e.key === 'Enter') {
        filterInventory();
    }
});


// Toggle expand/collapse
document.querySelectorAll('.medicine-group-header').forEach(header => {
    header.addEventListener('click', function() {
        let medId = this.getAttribute('data-medid');
        let batches = document.querySelectorAll('.batch-row-' + medId);
        let icon = document.getElementById('toggle-icon-' + medId);
        
        let isExpanded = icon.classList.contains('ph-caret-down');
        
        if (isExpanded) {
            batches.forEach(b => b.style.display = 'none');
            icon.classList.replace('ph-caret-down', 'ph-caret-right');
        } else {
            batches.forEach(b => b.style.display = '');
            icon.classList.replace('ph-caret-right', 'ph-caret-down');
        }
    });
});

function openWithdrawModal(batchId, currentQty) {
    document.getElementById('withdrawForm').action = '/inventory/withdraw/' + batchId;
    document.getElementById('available_quantity').value = currentQty;
    document.getElementById('withdraw_quantity').max = currentQty;
    document.getElementById('withdrawModal').style.display = 'flex';
}

function openDeleteModal(batchId) {
    document.getElementById('deleteForm').action = '/inventory/delete/' + batchId;
    document.getElementById('deleteModal').style.display = 'flex';
}

function closeModals() {
    document.getElementById('withdrawModal').style.display = 'none';
    document.getElementById('deleteModal').style.display = 'none';
    document.getElementById('withdraw_quantity').value = '';
    document.getElementById('available_quantity').value = '';
    document.getElementById('withdrawal_comment').value = '';
}

// Close modals when clicking outside
window.onclick = function(event) {
    if (event.target == document.getElementById('withdrawModal')) closeModals();
    if (event.target == document.getElementById('deleteModal')) closeModals();
}

function filterInventory() {
    const branchEl = document.getElementById('branchFilter');
    const branchId = branchEl ? branchEl.value : '<?php echo htmlspecialchars($selectedBranch); ?>';
    
    const stockLevelEl = document.getElementById('stockLevelFilter');
    const stockLevel = stockLevelEl ? stockLevelEl.value : 'all';
    
    const searchEl = document.getElementById('searchInput');
    const search = searchEl ? searchEl.value : '';
    
    window.location.href = '?branch_id=' + branchId + '&stock_level=' + stockLevel + '&search=' + encodeURIComponent(search);
}
</script>

<?php require_once __DIR__ . '/../../layouts/footer.php'; ?>
