<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<meta charset="UTF-8" />
<title>إنشاء فاتورة متعددة المنتجات</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.rtl.min.css" rel="stylesheet" />
<script>
function addRow() {
  const tableBody = document.getElementById('products-body');
  const rowCount = tableBody.rows.length;
  const newRow = tableBody.insertRow();
  newRow.innerHTML = `
    <td>${rowCount + 1}</td>
    <td>
      <select name="description[]" class="form-select description" required>
        <option value="">اختر وصف المنتج</option>
        <option value="كنب">كنب</option>
        <option value="ستارة">ستارة</option>
        <option value="عرض الغرفة للعملاء">عرض الغرفة للعملاء</option>
        <option value="عرض الغرفة">عرض الغرفة</option>
        <option value="أخرى">أخرى</option>
      </select>
      <input type="text" name="custom_description[]" class="form-control mt-1 d-none custom-description" placeholder="اكتب وصفًا مخصصًا" />
    </td>
    <td><input type="number" name="quantity[]" class="form-control quantity" min="1" value="1" required /></td>
    <td><input type="number" name="unit_price[]" class="form-control unit-price" min="0" step="0.01" value="0" required /></td>
    <td><input type="number" name="discount[]" class="form-control discount" min="0" max="100" step="1" value="0" required /></td>
    <td class="total-price">0.00</td>
    <td><button type="button" class="btn btn-danger btn-sm" onclick="removeRow(this)">حذف</button></td>
  `;
  attachListeners(newRow);
  calculateTotals();
}
function removeRow(button) {
  const row = button.closest('tr');
  row.remove();
  updateRowNumbers();
  calculateTotals();
}
function updateRowNumbers() {
  const rows = document.querySelectorAll('#products-body tr');
  rows.forEach((row, idx) => {
    row.cells[0].textContent = idx + 1;
  });
}
function attachListeners(row) {
  const descriptionSelect = row.querySelector('.description');
  const customDescInput = row.querySelector('.custom-description');
  const quantityInput = row.querySelector('.quantity');
  const unitPriceInput = row.querySelector('.unit-price');
  const discountInput = row.querySelector('.discount');
  descriptionSelect.addEventListener('change', () => {
    if (descriptionSelect.value === 'أخرى') {
      customDescInput.classList.remove('d-none');
      customDescInput.required = true;
    } else {
      customDescInput.classList.add('d-none');
      customDescInput.required = false;
      customDescInput.value = '';
      let priceMap = {
        'كنب': 50,
        'ستارة': 50,
        'عرض الغرفة للعملاء': 200,
        'عرض الغرفة': 250
      };
      unitPriceInput.value = priceMap[descriptionSelect.value] || 0;
    }
    calculateTotals();
  });
  [quantityInput, unitPriceInput, discountInput, customDescInput].forEach(input => {
    input.addEventListener('input', calculateTotals);
  });
}
function calculateTotals() {
  let totalInvoice = 0;
  const rows = document.querySelectorAll('#products-body tr');
  rows.forEach(row => {
    const quantity = parseFloat(row.querySelector('.quantity').value) || 0;
    const unitPrice = parseFloat(row.querySelector('.unit-price').value) || 0;
    const discount = parseFloat(row.querySelector('.discount').value) || 0;
    const total = quantity * unitPrice * (1 - discount / 100);
    row.querySelector('.total-price').textContent = total.toFixed(2);
    totalInvoice += total;
  });
  document.getElementById('invoice-total').textContent = totalInvoice.toFixed(2);
}
window.onload = function() {
  document.getElementById('add-product').addEventListener('click', addRow);
  addRow();
  fetchClients();
  setupAddClientForm();
};
function fetchClients() {
  fetch('get_clients.php')
    .then(res => res.json())
    .then(data => {
      const select = document.getElementById('client-select');
      select.innerHTML = '<option value="">-- اختر العميل --</option>';
      data.forEach(client => {
        const option = document.createElement('option');
        option.value = client.id;
        option.textContent = client.name + ' (' + client.type + ')';
        select.appendChild(option);
      });
    });
}
function setupAddClientForm() {
  document.getElementById('add-client-btn').addEventListener('click', () => {
    document.getElementById('add-client-form').style.display = 'block';
  });
  document.getElementById('cancel-add-client').addEventListener('click', () => {
    document.getElementById('add-client-form').style.display = 'none';
  });
  document.getElementById('save-client-btn').addEventListener('click', addClient);
}
function addClient() {
  const name = document.getElementById('new-client-name').value.trim();
  const phone = document.getElementById('new-client-phone').value.trim();
  const type = document.getElementById('new-client-type').value;
  if (!name || !phone) {
    alert('يرجى إدخال الاسم ورقم الهاتف');
    return;
  }
  fetch('add_client.php', {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({name, phone, type})
  }).then(res => res.json())
  .then(data => {
    if (data.success) {
      alert('تمت إضافة العميل بنجاح');
      document.getElementById('add-client-form').style.display = 'none';
      fetchClients();
    } else {
      alert('حدث خطأ أثناء الإضافة');
    }
  });
}
</script>
</head>
<body class="container py-4">
  <h1 class="mb-4">إنشاء فاتورة متعددة المنتجات</h1>
  <button id="add-client-btn" class="btn btn-secondary mb-3">إضافة عميل جديد</button>
  <div id="add-client-form" style="display:none; margin-bottom:15px;">
    <input type="text" id="new-client-name" placeholder="اسم العميل" class="form-control mb-2" />
    <input type="text" id="new-client-phone" placeholder="رقم الهاتف" class="form-control mb-2" />
    <select id="new-client-type" class="form-select mb-2">
      <option value="individual">فرد</option>
      <option value="business">شركة</option>
    </select>
    <button id="save-client-btn" class="btn btn-primary">حفظ العميل</button>
    <button id="cancel-add-client" class="btn btn-link">إلغاء</button>
  </div>
  <form action="generate_invoice.php" method="POST">
    <div class="mb-3">
      <label for="client-select" class="form-label">اختيار العميل:</label>
      <select id="client-select" name="client_id" class="form-select" required>
        <option value="">-- اختر العميل --</option>
      </select>
    </div>
    <table class="table table-bordered text-center align-middle">
      <thead>
        <tr>
          <th>رقم</th>
          <th>الوصف</th>
          <th>الكمية</th>
          <th>سعر الوحدة (ريال)</th>
          <th>الخصم (%)</th>
          <th>الإجمالي</th>
          <th>إجراءات</th>
        </tr>
      </thead>
      <tbody id="products-body"></tbody>
    </table>
    <button type="button" class="btn btn-primary" id="add-product">إضافة منتج جديد</button>
    <div class="mt-3 text-end fs-4">
      <strong>الإجمالي الكلي: <span id="invoice-total">0.00</span> ريال</strong>
    </div>
    <button type="submit" class="btn btn-success mt-3">إنشاء الفاتورة</button>
  </form>
</body>
</html>