<?php
include 'db.php';
include 'layout.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$user_id = $_SESSION['user_id'] ?? null;
$store_id = $_SESSION['store_id'] ?? 1;

// Get categories for item selection
$categories = $conn->query("SELECT * FROM categories ORDER BY name");
$customers = $conn->query("SELECT * FROM customers WHERE active = 1 ORDER BY name");

// Get tax rates
$tax_rates = $conn->query("SELECT * FROM tax_rates");
?>

<div class="main-wrapper">

    <div class="page-wrapper" style="margin-left: 250px; padding: 100px;">
        <div class="page-header d-flex justify-content-between align-items-center">
            <h4 class="page-title">Create New Quotation</h4>
            <div class="d-flex gap-2">
                <button class="btn btn-outline-primary" onclick="window.location.href='quotation_list.php'">
                    <i class="fas fa-list"></i> View Quotations
                </button>
            </div>
        </div>

        <!-- Enhanced Search / Barcode -->
        <div class="row mb-3">
            <div class="col-md-6">
                <label>Search Items</label>
                <div class="position-relative">
                    <input type="text" id="itemSearchInput" class="form-control" placeholder="Type item name or code to search...">
                    <div id="searchDropdown" class="position-absolute w-100 bg-white border rounded shadow-sm" style="top: 100%; left: 0; z-index: 1050; max-height: 300px; overflow-y: auto; display: none;">
                        <!-- Search results will be populated here -->
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <label>&nbsp;</label>
                <div>
                    <button type="button" class="btn btn-outline-primary" onclick="openItemBrowser()">
                        <i class="fas fa-th-large"></i> Browse All Items
                    </button>
                </div>
            </div>
        </div>

        <!-- Customer Information -->
        <div class="row mb-3">
            <div class="col-md-12">
                <label>Customer Name <span class="text-danger">*</span></label>
                <input type="text" id="customer_name" class="form-control" placeholder="Enter customer name" required>
            </div>
        </div>

        <!-- Item Table -->
        <table class="table table-bordered" id="productTable">
            <thead>
                <tr>
                    <th style="width:25%">Item <button type="button" class="btn btn-sm btn-success" onclick="addRow()">+</button></th>
                    <th>Qty</th>
                    <th>Unit Price</th>
                    <th>Tax %</th>
                    <th>Total</th>
                    <th>Remarks</th>
                    <th>–</th>
                </tr>
            </thead>
            <tbody></tbody>
        </table>

        <!-- Totals Section -->
        <div class="row mt-2">
            <div class="col-md-4">
                <label>Discount</label>
                <input type="number" id="discount" class="form-control" value="0" oninput="updateGrandTotal()">
            </div>
            <div class="col-md-4">
                <label>Remarks</label>
                <textarea id="remarks" class="form-control" placeholder="Optional..."></textarea>
            </div>
            <div class="col-md-4">
                <label><strong>Grand Total</strong></label>
                <input type="text" id="grandTotal" class="form-control" readonly>
            </div>
        </div>

        <!-- Action Buttons -->
        <div class="row mt-3">
            <div class="col-md-12 text-end">
                <button type="button" class="btn btn-secondary me-2" onclick="clearAll()">
                    <i class="fas fa-trash"></i> Clear All
                </button>
                <button type="button" class="btn btn-success" onclick="saveQuotation()" id="save_btn">
                    <i class="fas fa-save"></i> Save Quotation
                </button>
            </div>
        </div>
    </div>

    <!-- Item Browser Modal -->
    <div class="modal fade" id="itemBrowserModal" tabindex="-1">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Browse Items</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <!-- Search and Filter -->
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <input type="text" id="browserSearch" class="form-control" placeholder="Search items...">
                        </div>
                        <div class="col-md-3">
                            <select id="browserCategory" class="form-control">
                                <option value="">All Categories</option>
                                <?php 
                                $categories->data_seek(0);
                                while ($cat = $categories->fetch_assoc()): 
                                ?>
                                    <option value="<?php echo $cat['id']; ?>"><?php echo htmlspecialchars($cat['name']); ?></option>
                                <?php endwhile; ?>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <select id="browserType" class="form-control">
                                <option value="">All Types</option>
                                <option value="stock">Stock Items</option>
                                <option value="material">Materials</option>
                                <option value="service">Services</option>
                            </select>
                        </div>
                    </div>

                    <!-- Items Grid -->
                    <div class="row" id="browserItemsGrid">
                        <!-- Items will be loaded here -->
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Custom Item Modal -->
    <div class="modal fade" id="customItemModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Add Custom Item</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="custom_item_name" class="form-label">Item Name</label>
                        <input type="text" class="form-control" id="custom_item_name" required>
                    </div>
                    <div class="mb-3">
                        <label for="custom_item_price" class="form-label">Unit Price</label>
                        <input type="number" class="form-control" id="custom_item_price" step="0.01" min="0" required>
                    </div>
                    <div class="mb-3">
                        <label for="custom_item_quantity" class="form-label">Quantity</label>
                        <input type="number" class="form-control" id="custom_item_quantity" value="1" min="1" required>
                    </div>
                    <div class="mb-3">
                        <label for="custom_item_tax" class="form-label">Tax Rate (%)</label>
                        <input type="number" class="form-control" id="custom_item_tax" value="0" step="0.01" min="0">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-primary" onclick="addCustomItemToCart()">Add to Cart</button>
                </div>
            </div>
        </div>
    </div>

    <style>
        .search-result-item {
            cursor: pointer;
            transition: background-color 0.2s;
        }
        
        .search-result-item:hover {
            background-color: #f8f9fa !important;
        }
        
        .search-result-item.bg-primary:hover {
            background-color: #0056b3 !important;
        }
        
        #searchDropdown {
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            border: 1px solid #dee2e6;
        }
        
        .item-browser-card {
            transition: transform 0.2s;
        }
        
        .item-browser-card:hover {
            transform: translateY(-2px);
        }
    </style>

    <script>
        let searchTimeout;
        let selectedIndex = -1;
        let searchResults = [];
        let quotationItems = [];

        // Initialize quotation system
        document.addEventListener('DOMContentLoaded', function() {
            addRow(); // Add first empty row
            setupEventListeners();
            
            // Check if we're in edit mode
            const urlParams = new URLSearchParams(window.location.search);
            const editId = urlParams.get('edit');
            if (editId) {
                loadQuotationForEditing();
            }
        });

        function setupEventListeners() {
            // Enhanced search functionality
            document.getElementById('itemSearchInput').addEventListener('input', function() {
                const searchTerm = this.value.trim();
                
                clearTimeout(searchTimeout);
                
                if (searchTerm.length < 2) {
                    hideDropdown();
                    return;
                }
                
                // Show loading state
                showDropdown();
                document.getElementById('searchDropdown').innerHTML = '<div class="p-3 text-center text-muted"><i class="fas fa-spinner fa-spin"></i> Searching...</div>';
                
                searchTimeout = setTimeout(() => {
                    searchItems(searchTerm);
                }, 300);
            });

            // Handle keyboard navigation
            document.getElementById('itemSearchInput').addEventListener('keydown', function(e) {
                if (e.key === 'ArrowDown') {
                    e.preventDefault();
                    selectedIndex = Math.min(selectedIndex + 1, searchResults.length - 1);
                    updateDropdownSelection();
                } else if (e.key === 'ArrowUp') {
                    e.preventDefault();
                    selectedIndex = Math.max(selectedIndex - 1, -1);
                    updateDropdownSelection();
                } else if (e.key === 'Enter') {
                    e.preventDefault();
                    if (selectedIndex >= 0 && searchResults[selectedIndex]) {
                        selectSearchResult(searchResults[selectedIndex]);
                    }
                } else if (e.key === 'Escape') {
                    hideDropdown();
                }
            });

            // Hide dropdown when clicking outside
            document.addEventListener('click', function(e) {
                if (!e.target.closest('#itemSearchInput') && !e.target.closest('#searchDropdown')) {
                    hideDropdown();
                }
            });
        }

        function searchItems(searchTerm) {
            fetch(`ajax/get_items_for_quotation.php?search=${encodeURIComponent(searchTerm)}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        searchResults = data.items;
                        displaySearchResults();
                    } else {
                        document.getElementById('searchDropdown').innerHTML = '<div class="p-3 text-center text-muted">No items found</div>';
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    document.getElementById('searchDropdown').innerHTML = '<div class="p-3 text-center text-muted">Error searching items</div>';
                });
        }

        function displaySearchResults() {
            const dropdown = document.getElementById('searchDropdown');
            
            if (searchResults.length === 0) {
                dropdown.innerHTML = '<div class="p-3 text-center text-muted">No items found</div>';
                return;
            }
            
            dropdown.innerHTML = searchResults.map((item, index) => `
                <div class="search-result-item p-2 border-bottom ${index === selectedIndex ? 'bg-primary text-white' : ''}" 
                     onclick="selectSearchResult(${JSON.stringify(item).replace(/"/g, '&quot;')})">
                                    <div class="fw-bold">${item.name}</div>
                <small class="text-muted">${item.item_code} - ${parseFloat(item.retail_price).toFixed(2)}</small>
                </div>
            `).join('');
        }

        function updateDropdownSelection() {
            const items = document.querySelectorAll('.search-result-item');
            items.forEach((item, index) => {
                if (index === selectedIndex) {
                    item.classList.add('bg-primary', 'text-white');
                } else {
                    item.classList.remove('bg-primary', 'text-white');
                }
            });
        }

        function selectSearchResult(item) {
            addItemToTable(item);
            hideDropdown();
            document.getElementById('itemSearchInput').value = '';
            selectedIndex = -1;
        }

        function showDropdown() {
            document.getElementById('searchDropdown').style.display = 'block';
        }

        function hideDropdown() {
            document.getElementById('searchDropdown').style.display = 'none';
        }

        function openItemBrowser() {
            const modal = new bootstrap.Modal(document.getElementById('itemBrowserModal'));
            modal.show();
            loadBrowserItems();
        }

        function loadBrowserItems() {
            const search = document.getElementById('browserSearch').value;
            const category = document.getElementById('browserCategory').value;
            const type = document.getElementById('browserType').value;
            
            fetch(`ajax/get_items_for_quotation.php?search=${encodeURIComponent(search)}&category=${category}&type=${type}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        displayBrowserItems(data.items);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                });
        }

        function displayBrowserItems(items) {
            const grid = document.getElementById('browserItemsGrid');
            
            if (items.length === 0) {
                grid.innerHTML = '<div class="col-12 text-center text-muted py-4">No items found</div>';
                return;
            }
            
            grid.innerHTML = items.map(item => `
                <div class="col-md-3 mb-3">
                    <div class="card h-100">
                        <div class="card-body">
                            <h6 class="card-title">${item.name}</h6>
                            <p class="card-text text-muted small">${item.item_code}</p>
                            <p class="card-text"><strong>${parseFloat(item.retail_price).toFixed(2)}</strong></p>
                            <button class="btn btn-sm btn-primary w-100" onclick="addItemToTable(${JSON.stringify(item).replace(/"/g, '&quot;')})">
                                <i class="fas fa-plus"></i> Add
                            </button>
                        </div>
                    </div>
                </div>
            `).join('');
        }

        function addRow() {
            const tbody = document.querySelector('#productTable tbody');
            const rowCount = tbody.children.length;
            
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>
                    <input type="text" class="form-control item-name" placeholder="Item name" readonly>
                    <input type="hidden" class="item-id">
                </td>
                <td><input type="number" class="form-control quantity" value="1" min="1" onchange="updateRowTotal(this)"></td>
                <td><input type="number" class="form-control unit-price" step="0.01" min="0" onchange="updateRowTotal(this)"></td>
                <td><input type="number" class="form-control tax-rate" step="0.01" min="0" value="0" onchange="updateRowTotal(this)"></td>
                <td><input type="text" class="form-control total-price" readonly></td>
                <td><input type="text" class="form-control remarks" placeholder="Optional"></td>
                <td><button type="button" class="btn btn-sm btn-danger" onclick="removeRow(this)">–</button></td>
            `;
            
            tbody.appendChild(row);
            updateGrandTotal();
        }

        function removeRow(button) {
            if (document.querySelectorAll('#productTable tbody tr').length > 1) {
                button.closest('tr').remove();
                updateGrandTotal();
            }
        }

        function addItemToTable(item) {
            // Find first empty row or add new row
            let targetRow = document.querySelector('#productTable tbody tr:not(.has-item)');
            if (!targetRow) {
                addRow();
                targetRow = document.querySelector('#productTable tbody tr:last-child');
            }
            
            // Fill the row with item data
            targetRow.querySelector('.item-name').value = item.name;
            targetRow.querySelector('.item-id').value = item.id;
            targetRow.querySelector('.unit-price').value = parseFloat(item.retail_price).toFixed(2);
            targetRow.querySelector('.tax-rate').value = item.tax_rate || 0;
            targetRow.classList.add('has-item');
            
            updateRowTotal(targetRow.querySelector('.quantity'));
            updateGrandTotal();
            
            // Close browser modal if open
            const modal = bootstrap.Modal.getInstance(document.getElementById('itemBrowserModal'));
            if (modal) modal.hide();
        }

        function updateRowTotal(input) {
            const row = input.closest('tr');
            const quantity = parseFloat(row.querySelector('.quantity').value) || 0;
            const unitPrice = parseFloat(row.querySelector('.unit-price').value) || 0;
            const taxRate = parseFloat(row.querySelector('.tax-rate').value) || 0;
            
            const subtotal = quantity * unitPrice;
            const taxAmount = subtotal * (taxRate / 100);
            const total = subtotal + taxAmount;
            
            row.querySelector('.total-price').value = total.toFixed(2);
            updateGrandTotal();
        }

        function updateGrandTotal() {
            let subtotal = 0;
            let taxTotal = 0;
            
            document.querySelectorAll('#productTable tbody tr').forEach(row => {
                const total = parseFloat(row.querySelector('.total-price').value) || 0;
                const quantity = parseFloat(row.querySelector('.quantity').value) || 0;
                const unitPrice = parseFloat(row.querySelector('.unit-price').value) || 0;
                const taxRate = parseFloat(row.querySelector('.tax-rate').value) || 0;
                
                const rowSubtotal = quantity * unitPrice;
                const rowTax = rowSubtotal * (taxRate / 100);
                
                subtotal += rowSubtotal;
                taxTotal += rowTax;
            });
            
            const discount = parseFloat(document.getElementById('discount').value) || 0;
            const grandTotal = subtotal + taxTotal - discount;
            
            document.getElementById('grandTotal').value = grandTotal.toFixed(2);
        }

        function clearAll() {
            if (confirm('Are you sure you want to clear all items?')) {
                document.querySelector('#productTable tbody').innerHTML = '';
                addRow();
                updateGrandTotal();
            }
        }

        function saveQuotation() {
            const customerName = document.getElementById('customer_name').value.trim();
            if (!customerName) {
                alert('Please enter customer name');
                return;
            }
            
            const items = [];
            let hasItems = false;
            
            document.querySelectorAll('#productTable tbody tr').forEach(row => {
                const itemName = row.querySelector('.item-name').value.trim();
                if (itemName) {
                    hasItems = true;
                    items.push({
                        item_id: row.querySelector('.item-id').value || 0,
                        item_name: itemName,
                        quantity: parseFloat(row.querySelector('.quantity').value) || 0,
                        unit_price: parseFloat(row.querySelector('.unit-price').value) || 0,
                        tax_rate: parseFloat(row.querySelector('.tax-rate').value) || 0,
                        total_price: parseFloat(row.querySelector('.total-price').value) || 0,
                        remarks: row.querySelector('.remarks').value.trim()
                    });
                }
            });
            
            if (!hasItems) {
                alert('Please add at least one item to the quotation');
                return;
            }
            

            const remarks = document.getElementById('remarks').value.trim();
            const discount = parseFloat(document.getElementById('discount').value) || 0;
            const grandTotal = parseFloat(document.getElementById('grandTotal').value) || 0;
            
            const subtotal = items.reduce((sum, item) => sum + (item.quantity * item.unit_price), 0);
            const taxAmount = items.reduce((sum, item) => sum + ((item.quantity * item.unit_price * item.tax_rate) / 100), 0);
            
            // Check if we're editing or creating
            const editId = document.getElementById('save_btn').getAttribute('data-edit-id');
            const action = editId ? 'update' : 'create';
            
            const quotationData = {
                action: action,
                customer_name: customerName,
                remarks: remarks,
                items_json: JSON.stringify(items),
                subtotal: subtotal,
                tax_amount: taxAmount,
                discount_amount: discount,
                net_amount: grandTotal
            };
            
            // Add quotation ID if editing
            if (editId) {
                quotationData.quotation_id = editId;
            }
            
            fetch('handlers/quotation_handler.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams(quotationData)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    if (editId) {
                        Swal.fire({
                            icon: 'success',
                            title: 'Success!',
                            text: 'Quotation updated successfully!',
                            showConfirmButton: true
                        }).then(() => {
                            window.location.href = 'quotation_list.php';
                        });
                    } else {
                        Swal.fire({
                            icon: 'success',
                            title: 'Success!',
                            text: 'Quotation created successfully!\nQuotation Number: ' + data.quotation_number,
                            showConfirmButton: true
                        }).then(() => {
                            window.location.href = 'quotation_list.php';
                        });
                    }
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error!',
                        text: 'Error ' + (editId ? 'updating' : 'creating') + ' quotation: ' + data.message
                    });
                }
            })
            .catch(error => {
                console.error('Error:', error);
                Swal.fire({
                    icon: 'error',
                    title: 'Error!',
                    text: 'Error ' + (editId ? 'updating' : 'creating') + ' quotation. Please try again.'
                });
            });
        }

        function loadQuotationForEditing() {
            const quotationData = localStorage.getItem('editing_quotation');
            const itemsData = localStorage.getItem('editing_items');
            
            if (quotationData && itemsData) {
                const quotation = JSON.parse(quotationData);
                const items = JSON.parse(itemsData);
                
                // Populate quotation header
                document.getElementById('customer_name').value = quotation.customer_name || '';
                document.getElementById('remarks').value = quotation.remarks || '';
                
                // Clear existing rows and add items
                document.querySelector('#productTable tbody').innerHTML = '';
                
                items.forEach(item => {
                    addRow();
                    const lastRow = document.querySelector('#productTable tbody tr:last-child');
                    
                    lastRow.querySelector('.item-name').value = item.item_name;
                    lastRow.querySelector('.item-id').value = item.item_id;
                    lastRow.querySelector('.quantity').value = item.quantity;
                    lastRow.querySelector('.unit-price').value = parseFloat(item.unit_price).toFixed(2);
                    lastRow.querySelector('.tax-rate').value = parseFloat(item.tax_rate).toFixed(2);
                    lastRow.querySelector('.remarks').value = item.remarks || '';
                    lastRow.classList.add('has-item');
                    
                    updateRowTotal(lastRow.querySelector('.quantity'));
                });
                
                // Set discount
                document.getElementById('discount').value = parseFloat(quotation.discount_amount || 0).toFixed(2);
                
                // Update totals
                updateGrandTotal();
                
                // Change page title and save button
                document.querySelector('.page-title').textContent = 'Edit Quotation';
                document.getElementById('save_btn').innerHTML = '<i class="fas fa-save"></i> Update Quotation';
                
                // Store edit ID for saving
                document.getElementById('save_btn').setAttribute('data-edit-id', new URLSearchParams(window.location.search).get('edit'));
                
                // Clear localStorage
                localStorage.removeItem('editing_quotation');
                localStorage.removeItem('editing_items');
            }
        }

        // Browser event listeners
        document.getElementById('browserSearch').addEventListener('input', function() {
            clearTimeout(searchTimeout);
            searchTimeout = setTimeout(loadBrowserItems, 300);
        });

        document.getElementById('browserCategory').addEventListener('change', loadBrowserItems);
        document.getElementById('browserType').addEventListener('change', loadBrowserItems);
    </script>
