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

<div style="max-width: 1000px;">
    <h2 style="margin-bottom: 1.5rem;">Add New Stock</h2>

    <form action="/inventory/store" method="POST">
        <div style="display: flex; flex-direction: column; gap: 2rem;">
            
            <!-- Top Card: Medicine Selection -->
            <div class="card" style="padding: 1.25rem;">
                <h4 style="margin-bottom: 1.25rem; color: var(--text-muted); border-bottom: 1px solid var(--glass-border); padding-bottom: 0.5rem;">Medicine Selection</h4>
                
                <div style="display: flex; gap: 1rem; margin-bottom: 1rem;" class="form-row">
                    <div class="input-group" style="flex: 1; margin-bottom: 0;">
                        <label>Mode</label>
                        <select id="medicine_mode" name="medicine_mode" required style="width: 100%; padding: 0.5rem 0.75rem; background: rgba(15, 23, 42, 0.6); border: 1px solid var(--glass-border); border-radius: 8px; color: var(--text-light); outline: none;">
                            <option value="new" style="background: var(--bg-dark);">Register New Medicine</option>
                            <option value="existing" style="background: var(--bg-dark);">Add Batch to Existing Medicine</option>
                        </select>
                    </div>
                    <?php if($user['role'] === 'admin'): ?>
                    <div class="input-group" style="flex: 1; margin-bottom: 0;">
                        <label for="branch_id">Store in Branch *</label>
                        <select id="branch_id" name="branch_id" required style="width: 100%; padding: 0.5rem 0.75rem; background: rgba(15, 23, 42, 0.6); border: 1px solid var(--glass-border); border-radius: 8px; color: var(--text-light); outline: none;">
                            <?php foreach($branches as $branch): ?>
                                <option value="<?php echo $branch['id']; ?>" <?php echo ($selectedBranch == $branch['id']) ? 'selected' : ''; ?> style="background: var(--bg-dark);"><?php echo htmlspecialchars($branch['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <?php else: ?>
                    <div style="flex: 1;"></div>
                    <?php endif; ?>
                </div>

                <!-- Existing Medicine Block -->
                <div id="existing_block" style="display: none; margin-bottom: 1rem;">
                    <style>
                        .autocomplete-dropdown-item:hover, .autocomplete-dropdown-item.active {
                            background: rgba(79, 70, 229, 0.35) !important;
                            color: white !important;
                        }
                    </style>
                    <div style="display: flex; gap: 1rem;" class="form-row">
                        <div class="input-group" style="flex: 1; margin-bottom: 0; position: relative;">
                            <label for="medicine_search">Select Existing Medicine</label>
                            <input type="text" id="medicine_search" placeholder="Type to search medicine..." autocomplete="off" style="width: 100%; padding: 0.5rem 0.75rem; background: rgba(15, 23, 42, 0.6); border: 1px solid var(--glass-border); border-radius: 8px; color: var(--text-light); outline: none;">
                            <input type="hidden" id="medicine_id" name="medicine_id">
                            
                            <!-- Custom Autocomplete Dropdown Panel -->
                            <div id="medicine_dropdown" style="display: none; position: absolute; top: 100%; left: 0; right: 0; z-index: 1000; background: rgba(15, 23, 42, 0.95); border: 1px solid var(--glass-border); border-radius: 8px; max-height: 250px; overflow-y: auto; margin-top: 4px; box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.5); backdrop-filter: blur(10px);">
                                <?php foreach($medicines as $m): ?>
                                    <div class="autocomplete-dropdown-item" data-value="<?php echo $m['id']; ?>" data-search="<?php echo htmlspecialchars(strtolower($m['name'] . ' ' . $m['generic_name'])); ?>" style="padding: 0.6rem 1rem; cursor: pointer; color: var(--text-light); border-bottom: 1px solid rgba(255,255,255,0.05); transition: background 0.2s ease;">
                                        <strong><?php echo htmlspecialchars($m['name']); ?></strong>
                                        <?php if (!empty($m['generic_name'])): ?>
                                            <span style="color: var(--text-muted); font-size: 0.85rem; margin-left: 0.5rem;">(<?php echo htmlspecialchars($m['generic_name']); ?>)</span>
                                        <?php endif; ?>
                                    </div>
                                <?php endforeach; ?>
                                <div id="no_medicines_found" style="padding: 1rem; color: var(--text-muted); display: none; text-align: center;">No matching medicines found</div>
                            </div>
                        </div>
                        <div style="flex: 1;"></div>
                    </div>
                </div>

                <!-- New Medicine Block -->
                <div id="new_block">
                    <div style="display: flex; gap: 1rem; margin-bottom: 1rem;" class="form-row">
                        <div class="input-group" style="flex: 1; margin-bottom: 0;">
                            <label for="name">Medicine Name *</label>
                            <input type="text" id="name" name="name" placeholder="e.g. Paracetamol 500mg" style="padding: 0.5rem 0.75rem;">
                        </div>
                        <div class="input-group" style="flex: 1; margin-bottom: 0;">
                            <label for="generic_name">Generic Name</label>
                            <input type="text" id="generic_name" name="generic_name" placeholder="e.g. Acetaminophen" style="padding: 0.5rem 0.75rem;">
                        </div>
                    </div>
                    
                    <div style="display: flex; gap: 1rem; margin-bottom: 1rem;" class="form-row">
                        <div class="input-group" style="flex: 1; margin-bottom: 0;">
                            <label for="item_code">Item Code</label>
                            <input type="text" id="item_code" name="item_code" placeholder="e.g. MED-001" style="padding: 0.5rem 0.75rem;">
                        </div>
                        <div style="flex: 1;"></div>
                    </div>
                    
                    <div style="display: flex; gap: 1rem; margin-bottom: 1rem;" class="form-row">
                        <div class="input-group" style="flex: 1; margin-bottom: 0;">
                            <label for="uom_id">Unit of Measure *</label>
                            <select id="uom_id" name="uom_id" required style="width: 100%; padding: 0.5rem 0.75rem; background: rgba(15, 23, 42, 0.6); border: 1px solid var(--glass-border); border-radius: 8px; color: var(--text-light); outline: none;">
                                <option value="" style="background: var(--bg-dark);">-- Select Unit --</option>
                                <?php foreach($uoms as $uom): ?>
                                    <option value="<?php echo $uom['id']; ?>" style="background: var(--bg-dark);"><?php echo htmlspecialchars($uom['name']); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="input-group" style="flex: 1; margin-bottom: 0;">
                            <label for="volume">Volume</label>
                            <input type="number" id="volume" name="volume" step="0.01" min="0" placeholder="e.g. 500" style="padding: 0.5rem 0.75rem;">
                        </div>
                    </div>
                </div>

                <!-- Shared Row for Quantity and Reorder Level -->
                <div style="display: flex; gap: 1rem;" class="form-row">
                    <div class="input-group" style="flex: 1; margin-bottom: 0;">
                        <label for="quantity">Initial Quantity *</label>
                        <input type="number" id="quantity" name="quantity" required min="1" value="1" style="padding: 0.5rem 0.75rem;">
                    </div>
                    <div class="input-group" id="reorder_level_wrapper" style="flex: 1; margin-bottom: 0;">
                        <label for="reorder_level">Reorder Level</label>
                        <input type="number" id="reorder_level" name="reorder_level" value="10" min="0" style="padding: 0.5rem 0.75rem;">
                    </div>
                </div>
            </div>

            <!-- Bottom Card: Batch & Stock Details -->
            <div class="card" style="padding: 1.25rem;">
                <h4 style="margin-bottom: 1rem; color: var(--text-muted); border-bottom: 1px solid var(--glass-border); padding-bottom: 0.5rem;">Batch & Stock Details</h4>
                <p style="font-size: 0.85rem; color: var(--text-muted); margin-bottom: 1.25rem;">Changes here apply ONLY to Batch <strong style="color: #c084fc;"><?php echo htmlspecialchars($autoBatchNumber ?? ''); ?></strong>.</p>
                
                <div style="display: flex; gap: 1rem; margin-bottom: 1rem;" class="form-row">
                    <div class="input-group" style="flex: 1; margin-bottom: 0;">
                        <label for="batch_number">Batch Number *</label>
                        <input type="text" id="batch_number" name="batch_number" required value="<?php echo htmlspecialchars($autoBatchNumber ?? ''); ?>" style="padding: 0.5rem 0.75rem; border-color: #c084fc;">
                    </div>
                    <div class="input-group" style="flex: 1; margin-bottom: 0;">
                        <label for="expiry_date">Expiry Date *</label>
                        <input type="date" id="expiry_date" name="expiry_date" required style="padding: 0.5rem 0.75rem; border-color: #f59e0b;">
                    </div>
                </div>

                <div style="display: flex; gap: 1rem; margin-bottom: 1rem;" class="form-row">
                    <div class="input-group" style="flex: 1; margin-bottom: 0;">
                        <label for="supplier">Supplier</label>
                        <input type="text" id="supplier" name="supplier" style="padding: 0.5rem 0.75rem;">
                    </div>
                    <div class="input-group" id="expiry_alert_days_wrapper" style="flex: 1; margin-bottom: 0;">
                        <label for="expiry_alert_days">Notify Days Before Expiry *</label>
                        <input type="number" id="expiry_alert_days" name="expiry_alert_days" value="30" min="1" required style="padding: 0.5rem 0.75rem;">
                    </div>
                </div>

                <div style="display: flex; gap: 1rem; margin-bottom: 1rem;" class="form-row">
                    <div class="input-group" style="flex: 1; margin-bottom: 0;">
                        <label for="unit_price">Unit Cost (<?php echo htmlspecialchars($_SESSION['currency_code'] ?? '$'); ?>)</label>
                        <input type="number" id="unit_price" name="unit_price" step="0.01" min="0" style="padding: 0.5rem 0.75rem;">
                    </div>
                    <div class="input-group" style="flex: 1; margin-bottom: 0;">
                        <label for="selling_price">Selling Price (<?php echo htmlspecialchars($_SESSION['currency_code'] ?? '$'); ?>)</label>
                        <input type="number" id="selling_price" name="selling_price" step="0.01" min="0" style="padding: 0.5rem 0.75rem;">
                    </div>
                </div>

                <div style="margin-bottom: 1rem;">
                    <div class="input-group" style="margin-bottom: 0;">
                        <label for="notes">Notes</label>
                        <textarea id="notes" name="notes" rows="3" placeholder="Optional notes about this batch (e.g. storage conditions, special handling)..." style="width: 100%; padding: 0.5rem 0.75rem; background: rgba(15, 23, 42, 0.6); border: 1px solid var(--glass-border); border-radius: 8px; color: var(--text-light); outline: none; resize: vertical; font-family: inherit; font-size: inherit;"></textarea>
                    </div>
                </div>

                <div style="display: flex; gap: 1rem;" class="form-row">
                    <div class="input-group" style="flex: 1; margin-bottom: 0;">
                        <label for="batch_status">Batch Status *</label>
                        <select id="batch_status" name="batch_status" required style="width: 100%; padding: 0.5rem 0.75rem; background: rgba(15, 23, 42, 0.6); border: 1px solid var(--glass-border); border-radius: 8px; color: var(--text-light); outline: none;">
                            <option value="active" style="background: var(--bg-dark);" selected>Active</option>
                            <option value="inactive" style="background: var(--bg-dark);">Inactive</option>
                        </select>
                    </div>
                    <div style="flex: 1;"></div>
                </div>
            </div>

        </div>

        <div style="display: flex; gap: 1rem; margin-top: 1.5rem; max-width: 300px;" class="form-row">
            <button type="submit" class="btn-primary" style="flex: 1; margin-top: 0; padding: 0.6rem;">Save Stock</button>
            <a href="/inventory" class="btn-primary" style="flex: 1; margin-top: 0; padding: 0.6rem; background: transparent; border: 1px solid var(--glass-border); color: var(--text-light); text-align: center; text-decoration: none;">Cancel</a>
        </div>
    </form>
</div>

<script>
// Mode Toggling logic
document.getElementById('medicine_mode').addEventListener('change', function() {
    if (this.value === 'existing') {
        document.getElementById('existing_block').style.display = 'block';
        document.getElementById('new_block').style.display = 'none';
        document.getElementById('reorder_level_wrapper').style.display = 'none';
        document.getElementById('expiry_alert_days_wrapper').style.display = 'none';
        // Toggle required attributes to prevent form submission errors
        document.getElementById('medicine_search').required = true;
        document.getElementById('name').required = false;
        document.getElementById('uom_id').required = false;
        document.getElementById('expiry_alert_days').required = false;
    } else {
        document.getElementById('existing_block').style.display = 'none';
        document.getElementById('new_block').style.display = 'block';
        document.getElementById('reorder_level_wrapper').style.display = 'flex';
        document.getElementById('expiry_alert_days_wrapper').style.display = 'block';
        document.getElementById('medicine_search').required = false;
        document.getElementById('name').required = true;
        document.getElementById('uom_id').required = true;
        document.getElementById('expiry_alert_days').required = true;
    }
});

// Custom Autocomplete Dropdown logic
(function() {
    const searchInput = document.getElementById('medicine_search');
    const dropdown = document.getElementById('medicine_dropdown');
    const hiddenInput = document.getElementById('medicine_id');
    const items = dropdown.querySelectorAll('.autocomplete-dropdown-item');
    const noResults = document.getElementById('no_medicines_found');

    let highlightedIndex = -1;

    function getVisibleItems() {
        return Array.from(items).filter(item => item.style.display !== 'none');
    }

    function updateHighlight(visibleItems) {
        items.forEach(item => item.classList.remove('active'));
        if (highlightedIndex >= 0 && highlightedIndex < visibleItems.length) {
            visibleItems[highlightedIndex].classList.add('active');
            visibleItems[highlightedIndex].scrollIntoView({ block: 'nearest' });
        }
    }

    function filterList() {
        const filter = searchInput.value.toLowerCase().trim();
        let hasMatch = false;
        
        items.forEach(item => {
            const text = item.getAttribute('data-search');
            if (text.includes(filter)) {
                item.style.display = 'block';
                hasMatch = true;
            } else {
                item.style.display = 'none';
            }
        });
        
        noResults.style.display = hasMatch ? 'none' : 'block';
        
        const visible = getVisibleItems();
        updateHighlight(visible);
    }

    function selectItem(item) {
        const medName = item.querySelector('strong').textContent;
        const genericNameSpan = item.querySelector('span');
        const genericName = genericNameSpan ? ` ${genericNameSpan.textContent}` : '';
        
        searchInput.value = medName + genericName;
        hiddenInput.value = item.getAttribute('data-value');
        searchInput.setCustomValidity('');
        dropdown.style.display = 'none';
        highlightedIndex = -1;
    }

    // Event Listeners
    searchInput.addEventListener('focus', function() {
        dropdown.style.display = 'block';
        filterList();
    });

    searchInput.addEventListener('input', function() {
        hiddenInput.value = '';
        searchInput.setCustomValidity('');
        dropdown.style.display = 'block';
        highlightedIndex = -1;
        filterList();
    });

    searchInput.addEventListener('keydown', function(e) {
        const visible = getVisibleItems();
        
        if (e.key === 'ArrowDown') {
            e.preventDefault();
            if (dropdown.style.display === 'none') {
                dropdown.style.display = 'block';
            }
            if (visible.length > 0) {
                highlightedIndex = (highlightedIndex + 1) % visible.length;
                updateHighlight(visible);
            }
        } else if (e.key === 'ArrowUp') {
            e.preventDefault();
            if (visible.length > 0) {
                highlightedIndex = (highlightedIndex - 1 + visible.length) % visible.length;
                updateHighlight(visible);
            }
        } else if (e.key === 'Enter') {
            if (dropdown.style.display === 'block' && highlightedIndex >= 0 && highlightedIndex < visible.length) {
                e.preventDefault();
                selectItem(visible[highlightedIndex]);
            }
        } else if (e.key === 'Escape') {
            dropdown.style.display = 'none';
            highlightedIndex = -1;
        }
    });

    items.forEach(item => {
        item.addEventListener('click', function() {
            selectItem(item);
        });
    });

    document.addEventListener('click', function(e) {
        if (!searchInput.contains(e.target) && !dropdown.contains(e.target)) {
            dropdown.style.display = 'none';
            highlightedIndex = -1;
            
            if (searchInput.value !== '' && !hiddenInput.value) {
                searchInput.setCustomValidity("Please select a valid medicine from the autocomplete dropdown list.");
            }
        }
    });

    // Form submission validation
    const form = document.querySelector('form');
    if (form) {
        form.addEventListener('submit', function(e) {
            const mode = document.getElementById('medicine_mode').value;
            if (mode === 'existing') {
                if (!hiddenInput.value) {
                    searchInput.setCustomValidity("Please select a valid medicine from the autocomplete dropdown list.");
                    searchInput.reportValidity();
                    e.preventDefault();
                } else {
                    searchInput.setCustomValidity("");
                }
            }
        });
    }
})();
</script>

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