// === فواتير المرتجعات الاحترافية v3 ===
(function() {
  function getInvoices() {
    if (typeof allInvoices !== 'undefined' && allInvoices.length > 0) return allInvoices;
    if (window.allInvoices && window.allInvoices.length > 0) return window.allInvoices;
    return [];
  }
  function getItems() {
    if (typeof currentItems !== 'undefined' && currentItems.length > 0) return currentItems;
    if (window.currentItems && window.currentItems.length > 0) return window.currentItems;
    return [];
  }

  // ============================
  // مرتجع المبيعات
  // ============================
  window.loadSalesForReturn = function() {
    var contactId = document.getElementById('sales-returns-contact').value;
    var invSelect = document.getElementById('sales-returns-original-invoice');
    if (!invSelect) return;
    invSelect.innerHTML = '<option value="">-- اختر الفاتورة الاصلية --</option>';
    if (!contactId) return;
    var list = getInvoices().filter(function(inv) {
      return inv.type === 'sales' && String(inv.contact_id) === String(contactId);
    });
    if (list.length === 0) {
      invSelect.innerHTML += '<option disabled>-- لا توجد فواتير مبيعات لهذه الجهة --</option>';
      return;
    }
    list.forEach(function(inv) {
      var s = inv.status === 'draft' ? ' (مسودة)' : ' (مرحلة)';
      var d = inv.date ? new Date(inv.date).toLocaleDateString('ar-EG') : '';
      var total = parseFloat(inv.total || 0).toLocaleString('en-US');
      var opt = document.createElement('option');
      opt.value = inv.id;
      opt.textContent = 'فاتورة مبيعات #' + inv.id + ' | ' + d + ' | ' + total + ' ج.م' + s;
      invSelect.appendChild(opt);
    });
  };

  window.populateSalesReturnFromInvoice = function() {
    var invId = document.getElementById('sales-returns-original-invoice').value;
    if (!invId) {
      window.currentSalesReturnLines = [];
      window.renderSalesReturnsLines();
      return;
    }
    var invoice = getInvoices().find(function(inv) { return String(inv.id) === String(invId); });
    if (!invoice) return;
    var wh = document.getElementById('sales-returns-warehouse');
    if (wh && invoice.from_warehouse_id) wh.value = invoice.from_warehouse_id;
    var proj = document.getElementById('sales-returns-project');
    if (proj && invoice.project_id) proj.value = invoice.project_id;
    window.currentSalesReturnLines = JSON.parse(JSON.stringify(invoice.items || [])).map(function(item) {
      item.max_qty = item.qty;
      return item;
    });
    window.renderSalesReturnsLines();
  };

  window.renderSalesReturnsLines = function() {
    var tbody = document.getElementById('sales-returns-lines-tbody');
    if (!tbody) return;
    tbody.innerHTML = '';
    var grand = 0;
    (window.currentSalesReturnLines || []).forEach(function(line, idx) {
      var qty = parseFloat(line.qty) || 0;
      var price = parseFloat(line.price) || 0;
      var lt = qty * price;
      var disc = parseFloat(line.discount) || 0;
      if (line.discountType === 'percent') disc = lt * disc / 100;
      lt -= disc;
      grand += lt;
      var name = line.item_name || '';
      if (!name) {
        var it = getItems().find(function(i) { return String(i.id) === String(line.item_id); });
        if (it) name = it.name;
      }
      var max = line.max_qty;
      var tr = document.createElement('tr');
      tr.style.borderBottom = '1px solid rgba(255,255,255,0.08)';

      var tdName = document.createElement('td');
      tdName.style.cssText = 'padding:10px 8px;font-weight:600;';
      tdName.textContent = name;

      var tdQty = document.createElement('td');
      tdQty.style.cssText = 'padding:10px 8px;text-align:center;';
      var inp = document.createElement('input');
      inp.type = 'number'; inp.min = '0'; inp.step = '0.01'; inp.value = qty;
      inp.style.cssText = 'width:80px;text-align:center;border-radius:6px;padding:5px;border:1px solid rgba(255,255,255,0.2);background:rgba(255,255,255,0.1);color:inherit;font-size:14px;';
      if (max !== undefined) inp.max = max;
      (function(i) { inp.onchange = function() { window.updateSalesReturnQty(i, this.value); }; })(idx);
      tdQty.appendChild(inp);
      if (max !== undefined) {
        var sm = document.createElement('small');
        sm.style.cssText = 'color:#4caf50;font-size:11px;display:block;margin-top:2px;';
        sm.textContent = 'من اصل ' + max;
        tdQty.appendChild(sm);
      }

      var tdPrice = document.createElement('td');
      tdPrice.style.cssText = 'padding:10px 8px;text-align:center;';
      tdPrice.textContent = price.toLocaleString('en-US');

      var tdDisc = document.createElement('td');
      tdDisc.style.cssText = 'padding:10px 8px;text-align:center;';
      tdDisc.textContent = line.discountType === 'percent' ? (line.discount + '%') : disc.toLocaleString('en-US');

      var tdTotal = document.createElement('td');
      tdTotal.style.cssText = 'padding:10px 8px;text-align:center;font-weight:700;color:#4caf50;';
      tdTotal.textContent = lt.toLocaleString('en-US');

      var tdDel = document.createElement('td');
      tdDel.style.cssText = 'padding:10px 8px;text-align:center;';
      var btn = document.createElement('button');
      btn.textContent = '🗑 حذف';
      btn.style.cssText = 'background:#e53935;color:#fff;border-radius:6px;padding:4px 10px;border:none;cursor:pointer;';
      (function(i) { btn.onclick = function() { window.deleteSalesReturnLine(i); }; })(idx);
      tdDel.appendChild(btn);

      tr.appendChild(tdName); tr.appendChild(tdQty); tr.appendChild(tdPrice);
      tr.appendChild(tdDisc); tr.appendChild(tdTotal); tr.appendChild(tdDel);
      tbody.appendChild(tr);
    });
    var el = document.getElementById('sales-returns-total');
    if (el) el.value = grand.toFixed(2);
  };

  window.updateSalesReturnQty = function(idx, val) {
    var qty = parseFloat(val) || 0;
    var max = window.currentSalesReturnLines[idx].max_qty;
    if (max !== undefined && qty > max) {
      alert('الحد الاقصى للمرتجع: ' + max);
      qty = max;
    }
    window.currentSalesReturnLines[idx].qty = qty;
    window.renderSalesReturnsLines();
  };

  window.deleteSalesReturnLine = function(idx) {
    window.currentSalesReturnLines.splice(idx, 1);
    window.renderSalesReturnsLines();
  };

  // ============================
  // مرتجع المشتريات
  // ============================
  window.loadPurchasesForReturn = function() {
    var contactId = document.getElementById('purchases-returns-contact').value;
    var invSelect = document.getElementById('purchases-returns-original-invoice');
    if (!invSelect) return;
    invSelect.innerHTML = '<option value="">-- اختر الفاتورة الاصلية --</option>';
    if (!contactId) return;
    var list = getInvoices().filter(function(inv) {
      return inv.type === 'purchases' && String(inv.contact_id) === String(contactId);
    });
    if (list.length === 0) {
      invSelect.innerHTML += '<option disabled>-- لا توجد فواتير مشتريات لهذه الجهة --</option>';
      return;
    }
    list.forEach(function(inv) {
      var s = inv.status === 'draft' ? ' (مسودة)' : ' (مرحلة)';
      var d = inv.date ? new Date(inv.date).toLocaleDateString('ar-EG') : '';
      var total = parseFloat(inv.total || 0).toLocaleString('en-US');
      var opt = document.createElement('option');
      opt.value = inv.id;
      opt.textContent = 'فاتورة مشتريات #' + inv.id + ' | ' + d + ' | ' + total + ' ج.م' + s;
      invSelect.appendChild(opt);
    });
  };

  window.populatePurchasesReturnFromInvoice = function() {
    var invId = document.getElementById('purchases-returns-original-invoice').value;
    if (!invId) {
      window.currentPurchasesReturnLines = [];
      window.renderPurchasesReturnsLines();
      return;
    }
    var invoice = getInvoices().find(function(inv) { return String(inv.id) === String(invId); });
    if (!invoice) return;
    var wh = document.getElementById('purchases-returns-warehouse');
    if (wh && invoice.to_warehouse_id) wh.value = invoice.to_warehouse_id;
    var proj = document.getElementById('purchases-returns-project');
    if (proj && invoice.project_id) proj.value = invoice.project_id;
    window.currentPurchasesReturnLines = JSON.parse(JSON.stringify(invoice.items || [])).map(function(item) {
      item.max_qty = item.qty;
      return item;
    });
    window.renderPurchasesReturnsLines();
  };

  window.renderPurchasesReturnsLines = function() {
    var tbody = document.getElementById('purchases-returns-lines-tbody');
    if (!tbody) return;
    tbody.innerHTML = '';
    var grand = 0;
    (window.currentPurchasesReturnLines || []).forEach(function(line, idx) {
      var qty = parseFloat(line.qty) || 0;
      var price = parseFloat(line.price) || 0;
      var lt = qty * price;
      var disc = parseFloat(line.discount) || 0;
      if (line.discountType === 'percent') disc = lt * disc / 100;
      lt -= disc;
      grand += lt;
      var name = line.item_name || '';
      if (!name) {
        var it = getItems().find(function(i) { return String(i.id) === String(line.item_id); });
        if (it) name = it.name;
      }
      var max = line.max_qty;
      var tr = document.createElement('tr');
      tr.style.borderBottom = '1px solid rgba(255,255,255,0.08)';

      var tdName = document.createElement('td');
      tdName.style.cssText = 'padding:10px 8px;font-weight:600;';
      tdName.textContent = name;

      var tdQty = document.createElement('td');
      tdQty.style.cssText = 'padding:10px 8px;text-align:center;';
      var inp = document.createElement('input');
      inp.type = 'number'; inp.min = '0'; inp.step = '0.01'; inp.value = qty;
      inp.style.cssText = 'width:80px;text-align:center;border-radius:6px;padding:5px;border:1px solid rgba(255,255,255,0.2);background:rgba(255,255,255,0.1);color:inherit;font-size:14px;';
      if (max !== undefined) inp.max = max;
      (function(i) { inp.onchange = function() { window.updatePurchasesReturnQty(i, this.value); }; })(idx);
      tdQty.appendChild(inp);
      if (max !== undefined) {
        var sm = document.createElement('small');
        sm.style.cssText = 'color:#4caf50;font-size:11px;display:block;margin-top:2px;';
        sm.textContent = 'من اصل ' + max;
        tdQty.appendChild(sm);
      }

      var tdPrice = document.createElement('td');
      tdPrice.style.cssText = 'padding:10px 8px;text-align:center;';
      tdPrice.textContent = price.toLocaleString('en-US');

      var tdDisc = document.createElement('td');
      tdDisc.style.cssText = 'padding:10px 8px;text-align:center;';
      tdDisc.textContent = line.discountType === 'percent' ? (line.discount + '%') : disc.toLocaleString('en-US');

      var tdTotal = document.createElement('td');
      tdTotal.style.cssText = 'padding:10px 8px;text-align:center;font-weight:700;color:#4caf50;';
      tdTotal.textContent = lt.toLocaleString('en-US');

      var tdDel = document.createElement('td');
      tdDel.style.cssText = 'padding:10px 8px;text-align:center;';
      var btn = document.createElement('button');
      btn.textContent = '🗑 حذف';
      btn.style.cssText = 'background:#e53935;color:#fff;border-radius:6px;padding:4px 10px;border:none;cursor:pointer;';
      (function(i) { btn.onclick = function() { window.deletePurchasesReturnLine(i); }; })(idx);
      tdDel.appendChild(btn);

      tr.appendChild(tdName); tr.appendChild(tdQty); tr.appendChild(tdPrice);
      tr.appendChild(tdDisc); tr.appendChild(tdTotal); tr.appendChild(tdDel);
      tbody.appendChild(tr);
    });
    var el = document.getElementById('purchases-returns-total');
    if (el) el.value = grand.toFixed(2);
  };

  window.updatePurchasesReturnQty = function(idx, val) {
    var qty = parseFloat(val) || 0;
    var max = window.currentPurchasesReturnLines[idx].max_qty;
    if (max !== undefined && qty > max) {
      alert('الحد الاقصى للمرتجع: ' + max);
      qty = max;
    }
    window.currentPurchasesReturnLines[idx].qty = qty;
    window.renderPurchasesReturnsLines();
  };

  window.deletePurchasesReturnLine = function(idx) {
    window.currentPurchasesReturnLines.splice(idx, 1);
    window.renderPurchasesReturnsLines();
  };

})();
