<?php $title=__('ingredients.edit_ingredient', 'Edit Ingredient'); ob_start(); ?>

<div class="d-flex justify-content-between align-items-center mb-4">
  <h1 class="h3 mb-0">
    <i class="fas fa-warehouse"></i> <?= __('ingredients.edit_ingredient', 'Edit Ingredient') ?>
  </h1>
  <div class="btn-group">
    <a href="/samanta_crm/ingredients" class="btn btn-secondary">
      <i class="fas fa-arrow-left"></i> <?= __('common.back', 'Back') ?>
    </a>
  </div>
</div>

<?php if(isset($locationStocks)): $main=(int)round($locationStocks['MAIN']??0); $rollback=(int)round($locationStocks['ROLLBACK']??0); $total=$main+$rollback; ?>
<div class="alert alert-info d-flex align-items-center mb-3">
  <i class="fas fa-info-circle me-2"></i>
  <div>
    <strong><?= __('ingredients.location_stock', 'Location Stock') ?>:</strong>
    <span class="badge bg-primary ms-2"><?= __('ingredients.main', 'Main') ?>: <?=$main?></span>
    <span class="badge bg-warning text-dark ms-1"><?= __('ingredients.rollback', 'Rollback') ?>: <?=$rollback?></span>
    <span class="badge bg-secondary ms-1"><?= __('common.total', 'Total') ?>: <?=$total?></span>
  </div>
</div>
<?php endif; ?>
<div class="card mb-3">
  <div class="card-header py-2">
    <span class="small fw-bold">
      <i class="fas fa-sliders-h me-1"></i><?= __('ingredients.quick_adjust_stock', 'Quick Adjust Stock (Location)') ?>
    </span>
  </div>
  <div class="card-body py-3">
    <form class="row g-3 align-items-end" method="post" action="/samanta_crm/storage/adjust">
      <input type="hidden" name="ingredient_id" value="<?=$ingredient['id']?>">
      <input type="hidden" name="return_to" value="/samanta_crm/ingredients/<?=$ingredient['id']?>/edit">
      <div class="col-md-3">
        <label class="form-label"><?= __('common.quantity', 'Quantity') ?> (+/-)</label>
        <div class="input-group">
          <input type="number" step="0.01" name="quantity" class="form-control" placeholder="<?= __('ingredients.qty_example', 'e.g. 5') ?>" required>
          <select name="quantity_unit" class="form-select" style="max-width: 80px;">
            <?php 
            $baseUnit = $ingredient['unit'] ?? 'g';
            // Get convertible units
            $convertibleUnits = [$baseUnit];
            if ($baseUnit === 'g') $convertibleUnits[] = 'kg';
            if ($baseUnit === 'kg') $convertibleUnits[] = 'g';
            if ($baseUnit === 'ml') $convertibleUnits[] = 'l';
            if ($baseUnit === 'l') $convertibleUnits[] = 'ml';
            if ($baseUnit === 'mg') $convertibleUnits[] = 'g';
            
            foreach ($convertibleUnits as $u): 
            ?>
              <option value="<?= $u ?>" <?= $u === $baseUnit ? 'selected' : '' ?>><?= strtoupper($u) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <small class="form-text text-muted"><?= __('ingredients.base_unit', 'Base') ?>: <?= strtoupper($ingredient['unit'] ?? 'g') ?></small>
      </div>
      <div class="col-md-2">
        <label class="form-label"><?= __('ingredients.location', 'Location') ?></label>
        <select name="location" class="form-select">
          <option value="MAIN"><?= __('ingredients.main', 'MAIN') ?></option>
          <option value="ROLLBACK"><?= __('ingredients.rollback', 'ROLLBACK') ?></option>
        </select>
      </div>
      <div class="col-md-3">
        <label class="form-label"><?= __('common.note', 'Note') ?></label>
        <input type="text" name="note" class="form-control" placeholder="<?= __('ingredients.optional_note', 'Optional note') ?>">
      </div>
      <div class="col-md-2">
        <button class="btn btn-primary w-100"><?= __('common.apply', 'Apply') ?></button>
      </div>
    </form>
    <div class="small text-muted mt-2">
      <i class="fas fa-info-circle me-1"></i><?= __('ingredients.adjust_hint', 'Positive adds, negative subtracts. Applies only to selected location.') ?>
    </div>
  </div>
</div>

  <div
      <?php if(!empty($movements)): $colName = isset($movements[0]['change_qty'])?'change_qty':'quantity'; ?>
      <div class="card mb-3">
        <div class="card-header py-2">
          <span class="small fw-bold">
            <i class="fas fa-history me-1"></i><?= __('ingredients.recent_movements', 'Recent Movements') ?>
          </span>
        </div>
        <div class="card-body pt-0">
          <div class="table-responsive">
            <table class="table table-sm table-hover align-middle mb-0">
            <thead class="small"><tr><th><?= __('common.date', 'Date') ?></th><th><?= __('ingredients.ref_date', 'Ref Date') ?></th><th><?= __('ingredients.location', 'Location') ?></th><th class="text-end"><?= __('common.quantity', 'Qty') ?></th><th><?= __('ingredients.reason', 'Reason') ?></th><th><?= __('common.note', 'Note') ?></th></tr></thead>
            <tbody class="small">
            <?php foreach($movements as $m): ?>
              <tr>
                <td><?= htmlspecialchars(substr($m['created_at']??'',0,19)) ?></td>
                <td><?= htmlspecialchars($m['ref_date']??'') ?></td>
                <td><?= htmlspecialchars($m['location']??'') ?></td>
                <td class="text-end"><?= (int)round($m[$colName]??0) ?></td>
                <td><?= htmlspecialchars($m['reason']??'') ?></td>
                <td><?= htmlspecialchars($m['note']??$m['notes']??'') ?></td>
              </tr>
            <?php endforeach; ?>
            </tbody>
            </table>
          </div>
        </div>
      </div>
      <?php endif; ?>
  <div class=row>
  <div class="col-md-6">          
      <div class="card mb-3">
        <div class="card-header py-2">
          <span class="small fw-bold">
            <i class="fas fa-edit me-1"></i><?= __('ingredients.ingredient_details', 'Ingredient Details') ?>
          </span>
        </div>
        <div class="card-body py-3">
          <form method="POST" action="/samanta_crm/ingredients/<?= $ingredient['id'] ?>/update" id="ingredientForm">
            <div class="mb-3">
              <label class="form-label"><?= __('common.name', 'Name') ?> *</label>
              <input name="name" value="<?= htmlspecialchars($ingredient['name']) ?>" class="form-control" required>
            </div>
            <div class="mb-3">
              <label class="form-label"><?= __('common.unit', 'Unit') ?></label>
              <select name="unit_code" class="form-select">
            <option value=""><?= __('common.none', '-- None --') ?></option>
            <?php foreach(($units??[]) as $u): $sel = ($ingredient['unit']??'')===$u['code']?'selected':''; ?>
              <option value="<?= htmlspecialchars($u['code']) ?>" <?= $sel ?>><?= htmlspecialchars($u['name']) ?> (<?= htmlspecialchars($u['code']) ?>)</option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="mb-3">
          <label class="form-label"><?= __('ingredients.supplier', 'Supplier') ?></label>
          <input name="supplier" value="<?= htmlspecialchars($ingredient['supplier'] ?? '') ?>" class="form-control" placeholder="<?= __('ingredients.supplier_placeholder', 'Supplier name') ?>">
        </div>
        <div class="mb-3">
          <label class="form-label"><?= __('ingredients.notes', 'Notes') ?></label>
          <textarea name="notes" class="form-control" rows="3"><?= htmlspecialchars($ingredient['notes']) ?></textarea>
        </div>
          </form>
        </div>
      </div>
  
  </div>
    <div class="col-md-6">  
      <div class="card mb-3">
        <div class="card-header py-2">
          <span class="small fw-bold">
            <i class="fas fa-exclamation-triangle me-1"></i><?= __('ingredients.stock_levels', 'Stock Level Alerts') ?>
          </span>
        </div>
        <div class="card-body py-3">
          <form method="POST" action="/samanta_crm/ingredients/<?= $ingredient['id'] ?>/update" id="stockLevelsForm">
            <!-- Hidden fields to satisfy controller validation -->
            <input type="hidden" name="name" value="<?= htmlspecialchars($ingredient['name']) ?>">
            <input type="hidden" name="unit_code" value="<?= htmlspecialchars($ingredient['unit'] ?? '') ?>">
            <input type="hidden" name="supplier" value="<?= htmlspecialchars($ingredient['supplier'] ?? '') ?>">
            <input type="hidden" name="notes" value="<?= htmlspecialchars($ingredient['notes'] ?? '') ?>">
            
            <div class="row g-3">
              <?php 
              $baseUnit = $ingredient['unit'] ?? 'g';
              $convertibleUnits = [$baseUnit];
              if ($baseUnit === 'g') $convertibleUnits[] = 'kg';
              if ($baseUnit === 'kg') $convertibleUnits[] = 'g';
              if ($baseUnit === 'ml') $convertibleUnits[] = 'l';
              if ($baseUnit === 'l') $convertibleUnits[] = 'ml';
              if ($baseUnit === 'mg') $convertibleUnits[] = 'g';
              ?>
              <div class="col-md-6">
                <label class="form-label"><?= __('ingredients.critical_low_stock', 'Critical Low Stock') ?></label>
                <div class="input-group">
                  <input type="number" step="0.01" name="critical_low_stock" value="<?= htmlspecialchars($ingredient['critical_low_stock'] ?? '') ?>" class="form-control" placeholder="<?= __('ingredients.critical_low_hint', 'Alert when below this level') ?>">
                  <select name="critical_low_stock_unit" class="form-select" style="max-width: 80px;">
                    <?php foreach ($convertibleUnits as $u): ?>
                      <option value="<?= $u ?>" <?= $u === $baseUnit ? 'selected' : '' ?>><?= strtoupper($u) ?></option>
                    <?php endforeach; ?>
                  </select>
                </div>
                <div class="form-text"><?= __('ingredients.critical_low_desc', 'Urgent restock needed') ?></div>
              </div>
              <div class="col-md-6">
                <label class="form-label"><?= __('ingredients.low_stock', 'Low Stock') ?></label>
                <div class="input-group">
                  <input type="number" step="0.01" name="low_stock" value="<?= htmlspecialchars($ingredient['low_stock'] ?? '') ?>" class="form-control" placeholder="<?= __('ingredients.low_stock_hint', 'Warning level') ?>">
                  <select name="low_stock_unit" class="form-select" style="max-width: 80px;">
                    <?php foreach ($convertibleUnits as $u): ?>
                      <option value="<?= $u ?>" <?= $u === $baseUnit ? 'selected' : '' ?>><?= strtoupper($u) ?></option>
                    <?php endforeach; ?>
                  </select>
                </div>
                <div class="form-text"><?= __('ingredients.low_stock_desc', 'Should restock soon') ?></div>
              </div>
              <div class="col-md-6">
                <label class="form-label"><?= __('ingredients.high_stock', 'High Stock') ?></label>
                <div class="input-group">
                  <input type="number" step="0.01" name="high_stock" value="<?= htmlspecialchars($ingredient['high_stock'] ?? '') ?>" class="form-control" placeholder="<?= __('ingredients.high_stock_hint', 'Warning level') ?>">
                  <select name="high_stock_unit" class="form-select" style="max-width: 80px;">
                    <?php foreach ($convertibleUnits as $u): ?>
                      <option value="<?= $u ?>" <?= $u === $baseUnit ? 'selected' : '' ?>><?= strtoupper($u) ?></option>
                    <?php endforeach; ?>
                  </select>
                </div>
                <div class="form-text"><?= __('ingredients.high_stock_desc', 'Stock above normal') ?></div>
              </div>
              <div class="col-md-6">
                <label class="form-label"><?= __('ingredients.critical_high_stock', 'Critical High Stock') ?></label>
                <div class="input-group">
                  <input type="number" step="0.01" name="critical_high_stock" value="<?= htmlspecialchars($ingredient['critical_high_stock'] ?? '') ?>" class="form-control" placeholder="<?= __('ingredients.critical_low_hint', 'Alert when above this level') ?>">
                  <select name="critical_high_stock_unit" class="form-select" style="max-width: 80px;">
                    <?php foreach ($convertibleUnits as $u): ?>
                      <option value="<?= $u ?>" <?= $u === $baseUnit ? 'selected' : '' ?>><?= strtoupper($u) ?></option>
                    <?php endforeach; ?>
                  </select>
                </div>
                <div class="form-text"><?= __('ingredients.critical_high_desc', 'Overstocked - risk of waste') ?></div>
              </div>
            </div>
          </form>
        </div>
      </div>
      <div class="d-flex gap-2 mb-4">
        <button type="submit" form="ingredientForm" class="btn btn-primary">
          <i class="fas fa-save"></i> <?= __('common.update', 'Update') ?>
        </button>
        <button type="submit" form="stockLevelsForm" class="btn btn-success">
          <i class="fas fa-bell"></i> <?= __('ingredients.update_alerts', 'Update Alerts') ?>
        </button>
        <a href="/samanta_crm/ingredients" class="btn btn-secondary">
          <i class="fas fa-times"></i> <?= __('common.cancel', 'Cancel') ?>
        </a>
      </div>
    </div>
  </div>
</div>

<div class="card mb-3">
  <div class="card-header py-2 d-flex justify-content-between align-items-center">
    <span class="small fw-bold">
      <i class="fas fa-link me-1"></i><?= __('ingredients.quick_product_link', 'Quick Products Link') ?>
    </span>
    <button class="btn btn-sm btn-outline-secondary" type="button" data-bs-toggle="collapse" data-bs-target="#quickProductsWrap">
      <i class="fas fa-chevron-down"></i>
    </button>
  </div>
  <div class="collapse" id="quickProductsWrap">
    <div class="card-body py-3">
      <p class="text-muted small mb-3">
        <i class="fas fa-info-circle me-1"></i><?= __('ingredients.quick_link_hint', 'Quickly assign this ingredient to products with quantities') ?>
      </p>
      
      <form method="POST" action="/samanta_crm/ingredients/<?= $ingredient['id'] ?>/link-products" id="quickLinkForm">
        <div class="row g-3 align-items-end mb-3">
          <div class="col-md-6">
            <label class="form-label"><?= __('products.product', 'Product') ?> *</label>
            <select name="product_id" class="form-select product-search-select" id="productSelect" required>
              <option value=""><?= __('common.select', '-- Select Product --') ?></option>
              <?php if(isset($products)): foreach($products as $p): ?>
                <option value="<?= $p['id'] ?>" data-code="<?= htmlspecialchars($p['code']??'') ?>"><?= htmlspecialchars($p['name']) ?> <?php if(!empty($p['code'])): ?>(<?= htmlspecialchars($p['code']) ?>)<?php endif; ?></option>
              <?php endforeach; endif; ?>
            </select>
          </div>
          <div class="col-md-3">
            <label class="form-label"><?= __('ingredients.ingredient_qty', 'Ingredient Quantity') ?> *</label>
            <input type="number" step="0.01" name="ingredient_qty" class="form-control" placeholder="0.00" required id="qtyInput">
          </div>
          <div class="col-md-3">
            <button type="submit" class="btn btn-primary w-100" id="addLinkBtn">
              <i class="fas fa-plus"></i> <?= __('common.add', 'Add Link') ?>
            </button>
          </div>
        </div>
      </form>

      <div id="productLinksContainer">
        <?php if(isset($productLinks) && !empty($productLinks)): ?>
        <hr class="my-3">
        <div class="table-responsive">
          <table class="table table-sm table-hover align-middle mb-0" id="productLinksTable">
            <thead class="small">
              <tr>
                <th><?= __('products.product', 'Product') ?></th>
                <th><?= __('products.code', 'Code') ?></th>
                <th class="text-end"><?= __('ingredients.ingredient_qty', 'Qty') ?> <i class="fas fa-info-circle text-muted" title="<?= __('common.click_to_edit', 'Click to edit') ?>"></i></th>
                <th class="text-end"></th>
              </tr>
            </thead>
            <tbody class="small">
              <?php foreach($productLinks as $link): ?>
              <tr>
                <td><strong><?= htmlspecialchars($link['product_name']??'') ?></strong></td>
                <td><code><?= htmlspecialchars($link['product_code']??'') ?></code></td>
                <td class="text-end editable-qty" data-product-id="<?= $link['product_id'] ?>" data-qty="<?= $link['ingredient_qty']??0 ?>" style="cursor: pointer;" title="<?= __('common.click_to_edit', 'Click to edit') ?>">
                  <span class="qty-display"><?= number_format($link['ingredient_qty']??0, 2) ?></span>
                  <i class="fas fa-edit ms-1 text-muted" style="font-size: 0.8em;"></i>
                </td>
                <td class="text-end">
                  <button type="button" class="btn btn-sm btn-outline-danger unlink-product" data-product-id="<?= $link['product_id'] ?>">
                    <i class="fas fa-unlink"></i>
                  </button>
                </td>
              </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
        <?php else: ?>
        <div class="alert alert-info mb-0">
          <i class="fas fa-info-circle me-1"></i><?= __('ingredients.no_product_links', 'No products linked yet') ?>
        </div>
        <?php endif; ?>
      </div>
    </div>
  </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
  const ingredientId = <?= $ingredient['id'] ?>;
  
  // Initialize product search select with filtering
  const productSelect = document.getElementById('productSelect');
  
  if (productSelect && typeof $ !== 'undefined' && $.fn.select2) {
    // Use Select2 for enhanced search
    $(productSelect).select2({
      theme: 'bootstrap-5',
      width: '100%',
      placeholder: '<?= __('common.search_products', 'Search products...') ?>',
      allowClear: true,
      dropdownAutoWidth: true,
      templateResult: function(data) {
        if (!data.id) {
          return data.text;
        }
        const code = $(data.element).data('code');
        if (code) {
          return $('<span>' + data.text + '</span>');
        }
        return data.text;
      },
      matcher: function(params, data) {
        // If there are no search terms, return all data
        if ($.trim(params.term) === '') {
          return data;
        }
        
        // Do not display the item if there is no 'text' property
        if (typeof data.text === 'undefined') {
          return null;
        }
        
        // Search in both text and data-code attribute
        const searchTerm = params.term.toLowerCase();
        const text = data.text.toLowerCase();
        const code = ($(data.element).data('code') || '').toString().toLowerCase();
        
        if (text.indexOf(searchTerm) > -1 || code.indexOf(searchTerm) > -1) {
          return data;
        }
        
        return null;
      }
    });
    
    // Auto-focus quantity input when product selected
    $(productSelect).on('select2:select', function() {
      setTimeout(() => {
        const qtyInput = document.getElementById('qtyInput');
        if (qtyInput) qtyInput.focus();
      }, 100);
    });
  } else {
    // Fallback: Simple search filter
    const searchWrapper = document.createElement('div');
    searchWrapper.className = 'mb-2';
    searchWrapper.innerHTML = `
      <input type="text" 
             class="form-control form-control-sm" 
             id="productSearchInput" 
             placeholder="<?= __('common.search_products', 'Search products...') ?>" 
             autocomplete="off">
    `;
    productSelect.parentNode.insertBefore(searchWrapper, productSelect);
    
    const searchInput = document.getElementById('productSearchInput');
    const options = Array.from(productSelect.options).slice(1); // Skip first empty option
    
    searchInput.addEventListener('input', function() {
      const searchTerm = this.value.toLowerCase();
      
      // Reset select
      productSelect.innerHTML = '<option value="">-- <?= __('common.select', 'Select Product') ?> --</option>';
      
      // Filter and add matching options
      const matches = options.filter(opt => {
        const text = opt.textContent.toLowerCase();
        const code = opt.getAttribute('data-code') || '';
        return text.includes(searchTerm) || code.toLowerCase().includes(searchTerm);
      });
      
      matches.forEach(opt => {
        productSelect.appendChild(opt.cloneNode(true));
      });
      
      // Show count
      if (searchTerm && matches.length === 0) {
        const noResult = document.createElement('option');
        noResult.textContent = '<?= __('common.no_results', 'No results found') ?>';
        noResult.disabled = true;
        productSelect.appendChild(noResult);
      }
    });
    
    // Clear search when option selected
    productSelect.addEventListener('change', function() {
      if (this.value) {
        searchInput.value = '';
        const qtyInput = document.getElementById('qtyInput');
        if (qtyInput) qtyInput.focus();
      }
    });
  }
  
  // AJAX form submission
  const quickLinkForm = document.getElementById('quickLinkForm');
  const addLinkBtn = document.getElementById('addLinkBtn');
  
  quickLinkForm.addEventListener('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    const productId = formData.get('product_id');
    const qty = formData.get('ingredient_qty');
    
    if (!productId || !qty) {
      alert('<?= __('common.fill_required', 'Please fill all required fields') ?>');
      return;
    }
    
    // Disable button
    addLinkBtn.disabled = true;
    addLinkBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> <?= __('common.adding', 'Adding...') ?>';
    
    fetch('/samanta_crm/ingredients/' + ingredientId + '/link-products', {
      method: 'POST',
      body: formData
    })
    .then(response => response.json())
    .then(data => {
      if (data.success) {
        // Reset form
        quickLinkForm.reset();
        if (typeof $ !== 'undefined' && $.fn.select2) {
          $(productSelect).val(null).trigger('change');
        }
        
        // Reload product links
        loadProductLinks();
        
        // Show success message
        showToast('success', data.message || '<?= __('common.success', 'Success') ?>');
      } else {
        showToast('error', data.message || '<?= __('common.error', 'An error occurred') ?>');
      }
    })
    .catch(error => {
      console.error('Error:', error);
      showToast('error', '<?= __('common.error', 'An error occurred') ?>');
    })
    .finally(() => {
      // Re-enable button
      addLinkBtn.disabled = false;
      addLinkBtn.innerHTML = '<i class="fas fa-plus"></i> <?= __('common.add', 'Add Link') ?>';
    });
  });
  
  // Load product links via AJAX
  function loadProductLinks() {
    const container = document.getElementById('productLinksContainer');
    container.innerHTML = '<div class="text-center py-3"><i class="fas fa-spinner fa-spin"></i> <?= __('common.loading', 'Loading...') ?></div>';
    
    fetch('/samanta_crm/ingredients/' + ingredientId + '/product-links')
      .then(response => response.json())
      .then(data => {
        if (data.success && data.links && data.links.length > 0) {
          let html = `
            <hr class="my-3">
            <div class="table-responsive">
              <table class="table table-sm table-hover align-middle mb-0" id="productLinksTable">
                <thead class="small">
                  <tr>
                    <th><?= __('products.product', 'Product') ?></th>
                    <th><?= __('products.code', 'Code') ?></th>
                    <th class="text-end"><?= __('ingredients.ingredient_qty', 'Qty') ?></th>
                    <th class="text-end"></th>
                  </tr>
                </thead>
                <tbody class="small">
          `;
          
          data.links.forEach(link => {
            html += `
              <tr>
                <td><strong>${escapeHtml(link.product_name || '')}</strong></td>
                <td><code>${escapeHtml(link.product_code || '')}</code></td>
                <td class="text-end editable-qty" data-product-id="${link.product_id}" data-qty="${link.ingredient_qty || 0}" style="cursor: pointer;" title="<?= __('common.click_to_edit', 'Click to edit') ?>">
                  <span class="qty-display">${parseFloat(link.ingredient_qty || 0).toFixed(2)}</span>
                  <i class="fas fa-edit ms-1 text-muted" style="font-size: 0.8em;"></i>
                </td>
                <td class="text-end">
                  <button type="button" class="btn btn-sm btn-outline-danger unlink-product" data-product-id="${link.product_id}">
                    <i class="fas fa-unlink"></i>
                  </button>
                </td>
              </tr>
            `;
          });
          
          html += `
                </tbody>
              </table>
            </div>
          `;
          container.innerHTML = html;
        } else {
          container.innerHTML = `
            <div class="alert alert-info mb-0">
              <i class="fas fa-info-circle me-1"></i><?= __('ingredients.no_product_links', 'No products linked yet') ?>
            </div>
          `;
        }
        
        // Re-attach unlink handlers
        attachUnlinkHandlers();
        attachEditHandlers();
      })
      .catch(error => {
        console.error('Error:', error);
        container.innerHTML = `
          <div class="alert alert-danger mb-0">
            <i class="fas fa-exclamation-triangle me-1"></i><?= __('common.error', 'Error loading links') ?>
          </div>
        `;
      });
  }
  
  // Unlink product handler
  function attachUnlinkHandlers() {
    document.querySelectorAll('.unlink-product').forEach(btn => {
      btn.addEventListener('click', function() {
        if (!confirm('<?= __('common.confirm_remove', 'Remove this link?') ?>')) {
          return;
        }
        
        const productId = this.getAttribute('data-product-id');
        const originalHtml = this.innerHTML;
        this.disabled = true;
        this.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
        
        const formData = new FormData();
        formData.append('product_id', productId);
        
        fetch('/samanta_crm/ingredients/' + ingredientId + '/unlink-product', {
          method: 'POST',
          body: formData
        })
        .then(response => response.json())
        .then(data => {
          if (data.success) {
            loadProductLinks();
            showToast('success', data.message || '<?= __('common.success', 'Success') ?>');
          } else {
            showToast('error', data.message || '<?= __('common.error', 'An error occurred') ?>');
            this.disabled = false;
            this.innerHTML = originalHtml;
          }
        })
        .catch(error => {
          console.error('Error:', error);
          showToast('error', '<?= __('common.error', 'An error occurred') ?>');
          this.disabled = false;
          this.innerHTML = originalHtml;
        });
      });
    });
  }
  
  // Initial attachment
  attachUnlinkHandlers();
  attachEditHandlers();
  
  // Inline edit quantity handler
  function attachEditHandlers() {
    document.querySelectorAll('.editable-qty').forEach(cell => {
      cell.addEventListener('click', function() {
        if (this.querySelector('input')) return; // Already editing
        
        const productId = this.getAttribute('data-product-id');
        const currentQty = parseFloat(this.getAttribute('data-qty')) || 0;
        const display = this.querySelector('.qty-display');
        
        // Create input
        const input = document.createElement('input');
        input.type = 'number';
        input.step = '0.01';
        input.value = currentQty;
        input.className = 'form-control form-control-sm text-end';
        input.style.width = '80px';
        input.style.display = 'inline-block';
        
        // Replace display with input
        const icon = this.querySelector('.fa-edit');
        this.innerHTML = '';
        this.appendChild(input);
        input.focus();
        input.select();
        
        // Save on blur or enter
        const saveEdit = () => {
          const newQty = parseFloat(input.value) || 0;
          
          if (newQty <= 0) {
            showToast('error', '<?= __('common.invalid_quantity', 'Quantity must be greater than 0') ?>');
            input.focus();
            return;
          }
          
          if (newQty === currentQty) {
            // No change, just restore display
            this.innerHTML = `<span class="qty-display">${newQty.toFixed(2)}</span><i class="fas fa-edit ms-1 text-muted" style="font-size: 0.8em;"></i>`;
            this.setAttribute('data-qty', newQty);
            attachEditHandlers();
            return;
          }
          
          // Show saving indicator
          this.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
          
          // Save via AJAX
          const formData = new FormData();
          formData.append('product_id', productId);
          formData.append('quantity', newQty);
          
          fetch('/samanta_crm/ingredients/' + ingredientId + '/update-link-quantity', {
            method: 'POST',
            body: formData
          })
          .then(response => response.json())
          .then(data => {
            if (data.success) {
              this.innerHTML = `<span class="qty-display">${newQty.toFixed(2)}</span><i class="fas fa-edit ms-1 text-muted" style="font-size: 0.8em;"></i>`;
              this.setAttribute('data-qty', newQty);
              showToast('success', data.message || '<?= __('common.updated', 'Updated successfully') ?>');
              attachEditHandlers();
            } else {
              showToast('error', data.message || '<?= __('common.error', 'An error occurred') ?>');
              this.innerHTML = `<span class="qty-display">${currentQty.toFixed(2)}</span><i class="fas fa-edit ms-1 text-muted" style="font-size: 0.8em;"></i>`;
              attachEditHandlers();
            }
          })
          .catch(error => {
            console.error('Error:', error);
            showToast('error', '<?= __('common.error', 'An error occurred') ?>');
            this.innerHTML = `<span class="qty-display">${currentQty.toFixed(2)}</span><i class="fas fa-edit ms-1 text-muted" style="font-size: 0.8em;"></i>`;
            attachEditHandlers();
          });
        };
        
        input.addEventListener('blur', saveEdit);
        input.addEventListener('keypress', function(e) {
          if (e.key === 'Enter') {
            e.preventDefault();
            saveEdit();
          } else if (e.key === 'Escape') {
            cell.innerHTML = `<span class="qty-display">${currentQty.toFixed(2)}</span><i class="fas fa-edit ms-1 text-muted" style="font-size: 0.8em;"></i>`;
            attachEditHandlers();
          }
        });
      });
    });
  }
  
  // Helper functions
  function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
  }
  
  function showToast(type, message) {
    // Simple toast notification
    const toast = document.createElement('div');
    toast.className = `alert alert-${type === 'success' ? 'success' : 'danger'} position-fixed top-0 end-0 m-3`;
    toast.style.zIndex = '9999';
    toast.innerHTML = `
      <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-circle'} me-2"></i>${message}
      <button type="button" class="btn-close ms-2" onclick="this.parentElement.remove()"></button>
    `;
    document.body.appendChild(toast);
    
    setTimeout(() => {
      toast.remove();
    }, 3000);
  }
});
</script>


<?php $content=ob_get_clean(); include '../app/Views/layout.php'; ?>
