<?php // vars: $form, $customers, $errors, $is_edit, $statuses ?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <h4 class="mb-0"><?= $is_edit ? 'تعديل عرض سعر' : 'إنشاء عرض سعر' ?></h4>
  <a class="btn btn-outline-secondary" href="<?= e(url($quotations_url ?? '/sales/quotations')) ?>">رجوع</a>
</div>

<?php if (!empty($errors)): ?>
  <div class="alert alert-danger"><ul class="mb-0"><?php foreach ($errors as $er): ?><li><?= e($er) ?></li><?php endforeach; ?></ul></div>
<?php endif; ?>

<form method="post" id="quotationForm">
  <?= csrf_field() ?>
  <div class="card p-3 mb-3">
    <div class="row g-3">
      <div class="col-md-3">
        <label class="form-label">رقم العرض</label>
        <input type="text" class="form-control" name="quotation_no" value="<?= e($form['quotation_no']) ?>" required>
      </div>
      <div class="col-md-3">
        <label class="form-label">تاريخ العرض</label>
        <input type="date" class="form-control" name="quotation_date" value="<?= e($form['quotation_date']) ?>" required>
      </div>
      <div class="col-md-3">
        <label class="form-label">ساري حتى</label>
        <input type="date" class="form-control" name="valid_until" value="<?= e($form['valid_until']) ?>">
      </div>
      <div class="col-md-3">
        <label class="form-label">الحالة</label>
        <select class="form-select" name="status">
          <?php foreach ($statuses as $k=>$v): ?>
            <option value="<?= e($k) ?>" <?= (($form['status'] ?? '') === $k ? 'selected' : '') ?>><?= e($v) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
    </div>
  </div>

  <div class="card p-3 mb-3">
    <div class="d-flex justify-content-between align-items-center mb-3">
      <h5 class="mb-0">بيانات العميل</h5>
      <div class="btn-group" role="group">
        <input type="radio" class="btn-check" name="customer_mode" id="customer_mode_existing" value="existing" <?= (($form['customer_mode'] ?? 'existing') !== 'quick' ? 'checked' : '') ?>>
        <label class="btn btn-outline-primary" for="customer_mode_existing">عميل موجود</label>
        <input type="radio" class="btn-check" name="customer_mode" id="customer_mode_quick" value="quick" <?= (($form['customer_mode'] ?? '') === 'quick' ? 'checked' : '') ?>>
        <label class="btn btn-outline-primary" for="customer_mode_quick">تسجيل سريع من الشاشة</label>
      </div>
    </div>

    <div id="existingCustomerBox" class="row g-3">
      <div class="col-md-8">
        <label class="form-label">العميل</label>
        <select class="form-select" name="party_id" id="party_id" data-searchable-select="1" data-search-placeholder="اكتب أول حرفين من اسم العميل...">
          <option value="0">اختر عميلًا</option>
          <?php foreach ($customers as $c): ?>
            <option value="<?= (int)$c['id'] ?>" <?= ((int)($form['party_id'] ?? 0) === (int)$c['id'] ? 'selected' : '') ?>><?= e($c['name']) ?><?= !empty($c['phone']) ? ' — '.e($c['phone']) : '' ?></option>
          <?php endforeach; ?>
        </select>
      </div>
    </div>

    <div id="quickCustomerBox" class="row g-3" style="display:none;">
      <div class="col-md-5">
        <label class="form-label">اسم العميل <span class="text-danger">*</span></label>
        <input type="text" class="form-control" name="quick_customer_name" value="<?= e($form['quick_customer_name'] ?? '') ?>">
      </div>
      <div class="col-md-4">
        <label class="form-label">رقم التليفون <span class="text-danger">*</span></label>
        <input type="text" class="form-control" name="quick_customer_phone" value="<?= e($form['quick_customer_phone'] ?? '') ?>">
      </div>
      <div class="col-md-3">
        <label class="form-label">البريد الإلكتروني</label>
        <input type="email" class="form-control" name="quick_customer_email" value="<?= e($form['quick_customer_email'] ?? '') ?>">
      </div>
    </div>
  </div>

  <div class="card p-3 mb-3">
    <h5 class="mb-3">شروط العرض والتوريد</h5>
    <div class="row g-3">
      <div class="col-md-6">
        <label class="form-label">طريقة الدفع</label>
        <textarea class="form-control" name="payment_terms" rows="3" placeholder="مثال: 50% مقدم والباقي عند التسليم"><?= e($form['payment_terms'] ?? '') ?></textarea>
      </div>
      <div class="col-md-6">
        <label class="form-label">مدة/شروط التوريد</label>
        <textarea class="form-control" name="delivery_terms" rows="3" placeholder="مثال: التوريد خلال 7 أيام عمل من تأكيد الطلب"><?= e($form['delivery_terms'] ?? '') ?></textarea>
      </div>
      <div class="col-12">
        <label class="form-label">الشروط والأحكام</label>
        <textarea class="form-control" name="terms_conditions" rows="4" placeholder="أي شروط إضافية، الضمان، مكان التسليم، صلاحية العرض...
"><?= e($form['terms_conditions'] ?? '') ?></textarea>
      </div>
      <div class="col-12">
        <label class="form-label">ملاحظات داخلية / إضافية</label>
        <textarea class="form-control" name="notes" rows="2"><?= e($form['notes'] ?? '') ?></textarea>
      </div>
    </div>
  </div>

  <div class="card p-3 mb-3">
    <div class="d-flex justify-content-between align-items-center mb-3">
      <h5 class="mb-0">بنود عرض السعر</h5>
      <button class="btn btn-outline-primary btn-sm" type="button" id="addLineBtn"><i class="fa-solid fa-plus"></i> إضافة سطر</button>
    </div>

    <div class="table-responsive">
      <table class="table table-bordered align-middle" id="quotationLinesTable">
        <thead>
        <tr>
          <th style="width:32%;">الصنف</th>
          <th style="width:10%;">الكمية</th>
          <th style="width:14%;">السعر</th>
          <th>ملاحظات</th>
          <th style="width:14%;">الإجمالي</th>
          <th style="width:7%;"></th>
        </tr>
        </thead>
        <tbody>
        <?php foreach (($form['lines'] ?? []) as $i => $ln): ?>
          <tr>
            <td>
              <input type="hidden" name="item_id[]" class="item-id" value="<?= (int)($ln['item_id'] ?? 0) ?>">
              <div class="position-relative">
                <input type="text" name="item_name[]" class="form-control item-name" value="<?= e($ln['item_name'] ?? '') ?>" placeholder="ابحث باسم الصنف أو الباركود" autocomplete="off">
                <div class="list-group position-absolute w-100 shadow-sm item-suggest" style="z-index:10; display:none; max-height:220px; overflow:auto;"></div>
              </div>
            </td>
            <td><input type="number" step="0.001" min="0.001" name="qty[]" class="form-control qty" value="<?= e((string)($ln['qty'] ?? 1)) ?>"></td>
            <td><input type="number" step="0.01" min="0" name="price[]" class="form-control price" value="<?= e((string)($ln['price'] ?? 0)) ?>"></td>
            <td><input type="text" name="line_notes[]" class="form-control" value="<?= e($ln['line_notes'] ?? '') ?>"></td>
            <td><input type="text" class="form-control line-total" value="<?= e(number_format((float)($ln['line_total'] ?? 0), 2, '.', '')) ?>" readonly></td>
            <td class="text-center"><button class="btn btn-outline-danger btn-sm remove-line" type="button"><i class="fa-solid fa-trash"></i></button></td>
          </tr>
        <?php endforeach; ?>
        </tbody>
        <tfoot>
        <tr>
          <th colspan="4" class="text-end">الإجمالي</th>
          <th><input type="text" class="form-control" id="quotationTotal" value="0.00" readonly></th>
          <th></th>
        </tr>
        </tfoot>
      </table>
    </div>
  </div>

  <div class="d-flex gap-2 mb-4">
    <button class="btn btn-primary" type="submit"><i class="fa-solid fa-floppy-disk"></i> حفظ عرض السعر</button>
    <a class="btn btn-outline-secondary" href="<?= e(url($quotations_url ?? '/sales/quotations')) ?>">إلغاء</a>
  </div>
</form>

<template id="quotationLineTemplate">
  <tr>
    <td>
      <input type="hidden" name="item_id[]" class="item-id" value="0">
      <div class="position-relative">
        <input type="text" name="item_name[]" class="form-control item-name" placeholder="ابحث باسم الصنف أو الباركود" autocomplete="off">
        <div class="list-group position-absolute w-100 shadow-sm item-suggest" style="z-index:10; display:none; max-height:220px; overflow:auto;"></div>
      </div>
    </td>
    <td><input type="number" step="0.001" min="0.001" name="qty[]" class="form-control qty" value="1"></td>
    <td><input type="number" step="0.01" min="0" name="price[]" class="form-control price" value="0"></td>
    <td><input type="text" name="line_notes[]" class="form-control" value=""></td>
    <td><input type="text" class="form-control line-total" value="0.00" readonly></td>
    <td class="text-center"><button class="btn btn-outline-danger btn-sm remove-line" type="button"><i class="fa-solid fa-trash"></i></button></td>
  </tr>
</template>

<script>
(function(){
  const existingBox = document.getElementById('existingCustomerBox');
  const quickBox = document.getElementById('quickCustomerBox');
  const modeRadios = document.querySelectorAll('input[name="customer_mode"]');
  function syncCustomerMode(){
    const mode = document.querySelector('input[name="customer_mode"]:checked')?.value || 'existing';
    existingBox.style.display = mode === 'existing' ? '' : 'none';
    quickBox.style.display = mode === 'quick' ? '' : 'none';
  }
  modeRadios.forEach(r => r.addEventListener('change', syncCustomerMode));
  syncCustomerMode();

  const tbody = document.querySelector('#quotationLinesTable tbody');
  const template = document.getElementById('quotationLineTemplate');
  const totalInput = document.getElementById('quotationTotal');

  function recalcRow(tr){
    const qty = parseFloat(tr.querySelector('.qty')?.value || '0');
    const price = parseFloat(tr.querySelector('.price')?.value || '0');
    const total = Math.max(0, qty) * Math.max(0, price);
    tr.querySelector('.line-total').value = total.toFixed(2);
    recalcAll();
  }
  function recalcAll(){
    let total = 0;
    tbody.querySelectorAll('tr').forEach(tr => { total += parseFloat(tr.querySelector('.line-total')?.value || '0'); });
    totalInput.value = total.toFixed(2);
  }
  function attachRow(tr){
    tr.querySelectorAll('.qty,.price').forEach(el => el.addEventListener('input', () => recalcRow(tr)));
    tr.querySelector('.remove-line').addEventListener('click', () => {
      if (tbody.querySelectorAll('tr').length > 1) tr.remove();
      else {
        tr.querySelector('.item-id').value = '0';
        tr.querySelector('.item-name').value = '';
        tr.querySelector('.qty').value = '1';
        tr.querySelector('.price').value = '0';
        tr.querySelector('.line-total').value = '0.00';
        tr.querySelector('input[name="line_notes[]"]').value = '';
      }
      recalcAll();
    });
    setupItemSearch(tr);
    recalcRow(tr);
  }
  document.querySelectorAll('#quotationLinesTable tbody tr').forEach(attachRow);

  document.getElementById('addLineBtn').addEventListener('click', () => {
    const clone = template.content.firstElementChild.cloneNode(true);
    tbody.appendChild(clone);
    attachRow(clone);
    clone.querySelector('.item-name').focus();
  });

  function setupItemSearch(tr){
    const nameInput = tr.querySelector('.item-name');
    const idInput = tr.querySelector('.item-id');
    const priceInput = tr.querySelector('.price');
    const box = tr.querySelector('.item-suggest');
    let timer = null;

    function hideBox(){ box.style.display = 'none'; box.innerHTML = ''; }
    nameInput.addEventListener('input', () => {
      idInput.value = '0';
      const q = nameInput.value.trim();
      if (q.length < 1) { hideBox(); return; }
      clearTimeout(timer);
      timer = setTimeout(async () => {
        try {
          const res = await fetch(<?= json_encode(url('/ajax/items/search')) ?> + '?q=' + encodeURIComponent(q), {headers:{'X-Requested-With':'XMLHttpRequest'}});
          const rows = await res.json();
          box.innerHTML = '';
          if (!Array.isArray(rows) || !rows.length) { hideBox(); return; }
          rows.forEach(row => {
            const a = document.createElement('button');
            a.type = 'button';
            a.className = 'list-group-item list-group-item-action';
            a.textContent = row.text || row.name;
            a.addEventListener('click', () => {
              nameInput.value = row.name || '';
              idInput.value = row.id || 0;
              if (parseFloat(priceInput.value || '0') <= 0) priceInput.value = parseFloat(row.price || 0).toFixed(2);
              hideBox();
              recalcRow(tr);
            });
            box.appendChild(a);
          });
          box.style.display = 'block';
        } catch (e) { hideBox(); }
      }, 200);
    });
    document.addEventListener('click', (ev) => { if (!tr.contains(ev.target)) hideBox(); });
  }
  recalcAll();
})();
</script>
