<?php
include 'db.php';
?>
<!-- Add Purchase Modal -->
<div class="modal fade" id="addPurchaseModal" tabindex="-1">
  <div class="modal-dialog modal-xl">
    <form class="modal-content" id="addPurchaseForm" method="POST" action="add_purchase.php">
      <div class="modal-header">
        <h5 class="modal-title">Add Purchase</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">

        <!-- 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>

        <!-- Store Selection -->
        <div class="row mb-3">
          <div class="col-md-6">
            <label>Purchase for Store <span class="text-danger">*</span></label>
            <select name="store_id" class="form-control" required>
              <?php
              // Simple query to get all stores
              $current_store_id = $_SESSION['current_store_id'] ?? 1;
              
              $stores_query = "SELECT id, store_name, store_code FROM stores WHERE is_active = 1 ORDER BY store_name";
              $stores_result = $conn->query($stores_query);
              
              if ($stores_result && $stores_result->num_rows > 0) {
                  while ($store = $stores_result->fetch_assoc()) {
                      $selected = ($store['id'] == $current_store_id) ? 'selected' : '';
                      echo "<option value='{$store['id']}' {$selected}>{$store['store_name']} ({$store['store_code']})</option>";
                  }
              } else {
                  // Fallback if no stores found
                  echo "<option value='1' selected>Main Store (MAIN)</option>";
              }
              ?>
            </select>
          </div>
          <div class="col-md-6">
            <label>Reference No</label>
            <input type="text" name="reference_no" class="form-control" required>
          </div>
        </div>

        <!-- Supplier & Details -->
        <div class="row mb-3">
          <div class="col-md-6">
            <label>Supplier <span class="text-danger">*</span></label>
            <select name="vendor_id" class="form-control" required>
              <option value="">Select Supplier</option>
              <?php
              $suppliers = $conn->query("SELECT id, name FROM vendors ORDER BY name");
              while ($row = $suppliers->fetch_assoc()) {
                echo "<option value='{$row['id']}'>{$row['name']}</option>";
              }
              ?>
            </select>
          </div>
          <div class="col-md-6">
            <label>Purchase Date</label>
            <input type="date" name="purchase_date" class="form-control" value="<?php echo date('Y-m-d'); ?>" required>
          </div>
        </div>

        <!-- Item Table -->
        <table class="table table-bordered" id="productTable">
          <thead>
            <tr>
              <th style="width:20%">Item <button type="button" class="btn btn-sm btn-success" onclick="addRow()">+</button></th>
              <th>Type</th>
              <th>Qty</th>
              <th>Cost Price</th>
              <th>Retail Price</th>
              <th>Tax %</th>
              <th>Total</th>
              <th>Last Purchase</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" name="discount" id="discount" class="form-control" value="0" oninput="updateGrandTotal()">
          </div>
          <div class="col-md-4">
            <label>Shipping Charges</label>
            <input type="number" name="shipping" id="shipping" class="form-control" value="0" oninput="updateGrandTotal()">
          </div>
          <div class="col-md-4">
            <label>Status</label>
            <select name="status" class="form-control">
              <option value="received">Received</option>
              <option value="pending">Pending</option>
            </select>
          </div>
        </div>

        <div class="row mt-3">
          <div class="col-md-4 offset-md-8">
            <label><strong>Grand Total</strong></label>
            <input type="text" id="grandTotal" class="form-control" readonly>
          </div>
        </div>

        <div class="row mt-2">
          <div class="col-md-12">
            <label>Notes</label>
            <textarea name="notes" class="form-control" placeholder="Optional..."></textarea>
          </div>
        </div>

      </div>
      <div class="modal-footer">
        <button type="submit" class="btn btn-primary" id="savePurchaseBtn">
          <span class="btn-text">Save Purchase</span>
          <span class="spinner-border spinner-border-sm d-none" role="status" aria-hidden="true"></span>
        </button>
      </div>
    </form>
  </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>
            </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>

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

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

// Keyboard navigation
$('#itemSearchInput').on('keydown', function(e) {
  const dropdown = $('#searchDropdown');
  const items = dropdown.find('.search-item');
  
  switch(e.keyCode) {
    case 40: // Down arrow
      e.preventDefault();
      selectedIndex = Math.min(selectedIndex + 1, items.length - 1);
      updateSelection();
      break;
    case 38: // Up arrow
      e.preventDefault();
      selectedIndex = Math.max(selectedIndex - 1, -1);
      updateSelection();
      break;
    case 13: // Enter
      e.preventDefault();
      if (selectedIndex >= 0 && searchResults[selectedIndex]) {
        selectItem(searchResults[selectedIndex]);
      }
      break;
    case 27: // Escape
      hideDropdown();
      break;
  }
});

// Click outside to hide dropdown
$(document).on('click', function(e) {
  if (!$(e.target).closest('#itemSearchInput, #searchDropdown').length) {
    hideDropdown();
  }
});

function searchItems(searchTerm) {
  $.getJSON('search_items_enhanced.php', { q: searchTerm }, function(data) {
    searchResults = data;
    displaySearchResults(data);
  }).fail(function() {
    $('#searchDropdown').html('<div class="p-3 text-center text-danger">Error loading results</div>');
  });
}

function displaySearchResults(results) {
  const dropdown = $('#searchDropdown');
  
  if (results.length === 0) {
    dropdown.html('<div class="p-3 text-center text-muted">No items found</div>');
    return;
  }
  
  let html = '';
  results.forEach((item, index) => {
    html += `
      <div class="search-item p-3 border-bottom" data-index="${index}" style="cursor: pointer;">
        <div class="d-flex justify-content-between align-items-center">
          <div>
            <strong>${item.name}</strong>
            <br><small class="text-muted">${item.item_code}</small>
          </div>
          <div class="text-end">
            <div class="text-primary">${item.cost_price}</div>
            <small class="text-muted">Stock: ${item.current_stock}</small>
          </div>
        </div>
      </div>
    `;
  });
  
  dropdown.html(html);
  selectedIndex = -1;
  
  // Add click handlers
  dropdown.find('.search-item').on('click', function() {
    const index = $(this).data('index');
    selectItem(searchResults[index]);
  });
  
  // Add hover effects
  dropdown.find('.search-item').on('mouseenter', function() {
    selectedIndex = $(this).data('index');
    updateSelection();
  });
}

function updateSelection() {
  $('#searchDropdown .search-item').removeClass('bg-primary text-white');
  if (selectedIndex >= 0) {
    $('#searchDropdown .search-item').eq(selectedIndex).addClass('bg-primary text-white');
  }
}

function selectItem(item) {
  if (!item || !item.id) return;
  
  // Check if item is already in the table
  const existingRow = $(`input[name="item_id[]"][value="${item.id}"]`).closest('tr');
  if (existingRow.length > 0) {
    alert('This item is already in your purchase list!');
    return;
  }
  
  let row = $(`
    <tr>
      <td>
        <input type="hidden" name="item_id[]" value="${item.id}">
        <input type="text" class="form-control" value="${item.name}" readonly>
      </td>
      <td>${item.item_type}</td>
      <td><input type="number" name="quantity[]" class="form-control qty" value="1" required></td>
      <td><input type="number" name="price[]" class="form-control price" value="${item.cost_price}" required></td>
      <td><input type="number" name="retail_price[]" class="form-control retail" value="${item.retail_price}" required></td>
      <td><input type="text" name="tax[]" class="form-control tax" value="${item.tax_rate}" readonly></td>
      <td><input type="text" class="form-control lineTotal" readonly></td>
      <td><div class="prevPurchase text-muted small">Loading...</div></td>
      <td><button type="button" class="btn btn-danger btn-sm" onclick="removeRow(this)">x</button></td>
    </tr>
  `);

  $('#productTable tbody').append(row);
  calculateRow(row);
  loadLastPurchase(row, item.id);

  row.find('.qty, .price').on('input', function () {
    calculateRow(row);
  });

  // Clear search and hide dropdown
  $('#itemSearchInput').val('');
  hideDropdown();
}

function showDropdown() {
  $('#searchDropdown').show();
}

function hideDropdown() {
  $('#searchDropdown').hide();
  selectedIndex = -1;
}

function openItemBrowser() {
  $('#itemBrowserModal').modal('show');
  loadBrowserItems();
}

function loadBrowserItems() {
  $.getJSON('get_items_for_browser.php', function(data) {
    displayBrowserItems(data);
  });
}

function displayBrowserItems(items) {
  const grid = $('#browserItemsGrid');
  let html = '';
  
  items.forEach(item => {
    html += `
      <div class="col-md-4 col-lg-3 mb-3">
        <div class="card h-100 item-card" style="cursor: pointer;" onclick="selectItem(${JSON.stringify(item).replace(/"/g, '&quot;')})">
          <div class="card-body text-center">
            <div class="mb-2">
              <i class="fas fa-box text-primary fa-2x"></i>
            </div>
            <h6 class="card-title">${item.name}</h6>
            <p class="text-muted small mb-2">${item.item_code}</p>
            <div class="d-flex justify-content-between">
              <span class="badge bg-secondary">${item.item_type}</span>
              <span class="badge bg-info">${item.current_stock}</span>
            </div>
            <div class="mt-2">
              <strong class="text-primary">${item.cost_price}</strong>
            </div>
          </div>
        </div>
      </div>
    `;
  });
  
  grid.html(html);
}

// Browser search and filter
$('#browserSearch').on('input', function() {
  filterBrowserItems();
});

$('#browserCategory, #browserType').on('change', function() {
  filterBrowserItems();
});

function filterBrowserItems() {
  const searchTerm = $('#browserSearch').val().toLowerCase();
  const category = $('#browserCategory').val();
  const type = $('#browserType').val();
  
  $('.item-card').each(function() {
    const card = $(this);
    const name = card.find('.card-title').text().toLowerCase();
    const code = card.find('.text-muted').text().toLowerCase();
    const itemType = card.find('.badge').first().text();
    
    let show = true;
    
    if (searchTerm && !name.includes(searchTerm) && !code.includes(searchTerm)) {
      show = false;
    }
    
    if (type && itemType !== type) {
      show = false;
    }
    
    card.closest('.col-md-4').toggle(show);
  });
}

// Original functions
function calculateRow(row) {
  const qty = parseFloat(row.find('.qty').val()) || 0;
  const price = parseFloat(row.find('.price').val()) || 0;
  const tax = parseFloat(row.find('.tax').val()) || 0;
  const subtotal = qty * price;
  const taxAmt = subtotal * (tax / 100);
  const total = subtotal + taxAmt;
  row.find('.lineTotal').val(total.toFixed(2));
  updateGrandTotal();
}

function updateGrandTotal() {
  let total = 0;
  $('.lineTotal').each((i, el) => {
    total += parseFloat($(el).val()) || 0;
  });
  const discount = parseFloat($('#discount').val()) || 0;
  const shipping = parseFloat($('#shipping').val()) || 0;
  const net = total + shipping - discount;
  $('#grandTotal').val(net.toFixed(2));
}

function removeRow(btn) {
  $(btn).closest('tr').remove();
  updateGrandTotal();
}

function loadLastPurchase(row, itemId) {
  $.getJSON('get_last_purchase.php', { item_id: itemId }, function(data) {
    if (data && data.vendor && data.date) {
      row.find('.prevPurchase').html(`${data.price} from <strong>${data.vendor}</strong><br><small>${data.date}</small>`);
    } else {
      row.find('.prevPurchase').html("No previous purchase.");
    }
  });
}

function addRow() {
  // This function can be used to add empty rows if needed
  alert('Use the search above to add items to your purchase list.');
}

// AJAX Form Submission for Purchase
$(document).ready(function() {
    $('#addPurchaseForm').on('submit', function(e) {
        e.preventDefault();
        
        const $form = $(this);
        const $submitBtn = $('#savePurchaseBtn');
        const $btnText = $submitBtn.find('.btn-text');
        const $spinner = $submitBtn.find('.spinner-border');
        
        // Show loading state
        $submitBtn.prop('disabled', true);
        $btnText.text('Saving...');
        $spinner.removeClass('d-none');
        
        // Get form data
        const formData = new FormData(this);
        
        // Submit via AJAX
        $.ajax({
            url: 'add_purchase.php',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    // Success - show success message and redirect
                    Swal.fire({
                        title: 'Success!',
                        text: response.message,
                        icon: 'success',
                        timer: 2000,
                        showConfirmButton: false
                    }).then(() => {
                        // Close modal and redirect
                        $('#addPurchaseModal').modal('hide');
                        window.location.href = response.redirect;
                    });
                } else {
                    // Error - show error message and keep form open
                    Swal.fire({
                        title: 'Error!',
                        text: response.message,
                        icon: 'error',
                        confirmButtonText: 'OK'
                    });
                    
                    // Reset button state
                    $submitBtn.prop('disabled', false);
                    $btnText.text('Save Purchase');
                    $spinner.addClass('d-none');
                }
            },
            error: function(xhr, status, error) {
                // Handle AJAX errors
                console.error('AJAX Error:', error);
                Swal.fire({
                    title: 'Error!',
                    text: 'An unexpected error occurred. Please try again.',
                    icon: 'error',
                    confirmButtonText: 'OK'
                });
                
                // Reset button state
                $submitBtn.prop('disabled', false);
                $btnText.text('Save Purchase');
                $spinner.addClass('d-none');
            }
        });
    });
    
    // Reset form when modal is closed
    $('#addPurchaseModal').on('hidden.bs.modal', function() {
        $('#addPurchaseForm')[0].reset();
        $('#productTable tbody').empty();
        $('#savePurchaseBtn').prop('disabled', false);
        $('#savePurchaseBtn .btn-text').text('Save Purchase');
        $('#savePurchaseBtn .spinner-border').addClass('d-none');
    });
});
</script>

<style>
.search-item:hover {
  background-color: #f8f9fa;
}

.search-item.bg-primary {
  background-color: #007bff !important;
}

#searchDropdown {
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.item-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}
</style>
