<?php $title='الفواتير'; include __DIR__.'/../layout/header.php'; ?>
<style>
.invoice-shell{display:grid;grid-template-columns:minmax(0,1.35fr) minmax(320px,.65fr);gap:16px;align-items:start}
.invoice-panel{min-width:0}
.invoice-grid{display:grid;grid-template-columns:repeat(12,minmax(0,1fr));gap:14px}
.invoice-grid .col-1{grid-column:span 1}.invoice-grid .col-2{grid-column:span 2}.invoice-grid .col-3{grid-column:span 3}.invoice-grid .col-4{grid-column:span 4}.invoice-grid .col-6{grid-column:span 6}.invoice-grid .col-12{grid-column:span 12}
.invoice-card{background:linear-gradient(180deg,#fff,#fbf7f2);border:1px solid #eadfce;border-radius:22px;padding:18px;box-shadow:0 10px 26px rgba(17,24,39,.05)}
.invoice-soft{background:#faf7f4}
.invoice-inline-note{font-size:12px;color:#7b6a58;margin-top:6px}
.invoice-summary{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px}
.invoice-stat{background:rgba(255,255,255,.08);border:1px solid rgba(255,255,255,.10);border-radius:18px;padding:14px}
.invoice-stat strong{display:block;font-size:28px;margin-top:8px}
.line-item{border:1px solid #eadfd5;border-radius:18px;padding:14px;background:#fcfaf8;margin-bottom:12px}
.line-item .line-total-wrap{margin-top:10px;color:#6b7280}
.invoice-right-col .card{position:sticky;top:88px}
.invoice-actions{display:flex;gap:10px;flex-wrap:wrap}
@media (max-width:1100px){
  .invoice-shell{grid-template-columns:1fr}
  .invoice-right-col .card{position:static}
}
@media (max-width:900px){
  .invoice-grid .col-1,.invoice-grid .col-2,.invoice-grid .col-3,.invoice-grid .col-4,.invoice-grid .col-6,.invoice-grid .col-12{grid-column:1/-1}
  .invoice-summary{grid-template-columns:repeat(2,minmax(0,1fr))}
}
@media (max-width:560px){
  .invoice-summary{grid-template-columns:1fr}
  .invoice-card{padding:14px}
}
</style>

<div class="invoice-shell">
  <div class="invoice-panel">
    <div class="invoice-card hero">
      <div class="page-head">
        <div>
          <h2 style="margin:0">فاتورة جديدة</h2>
          <div class="muted">واجهة أسرع للرسبشن مع جلب العميل والأصناف المتاحة بشكل مباشر.</div>
        </div>
      </div>

      <form method="post" action="<?= e(base_url('?page=invoices')) ?>" id="invoiceForm">
        <input type="hidden" name="_csrf" value="<?= e(csrf_token()) ?>">
        <div id="customerFlags" class="alert error hidden"></div>

        <div class="invoice-grid">
          <div class="col-6">
            <label class="label">رقم الهاتف أو الرقم المدني</label>
            <div style="position:relative">
              <input class="input" id="customer_lookup" placeholder="اكتب الرقم وسيتم جلب البيانات بسرعة" autocomplete="off">
              <div id="customerSuggest" class="search-suggestions hidden"></div>
            </div>
            <div class="invoice-inline-note">إذا كان العميل موجوداً سيتم تعبئة بياناته تلقائياً.</div>
          </div>

          <div class="col-6">
            <label class="label">اسم العميل</label>
            <input class="input" name="customer_name" id="customer_name" required>
          </div>

          <div class="col-6">
            <label class="label">رقم الهاتف</label>
            <input class="input" name="customer_phone" id="customer_phone" required>
          </div>

          <div class="col-6">
            <label class="label">الرقم المدني</label>
            <input class="input" name="customer_civil_id" id="customer_civil_id">
          </div>

          <div class="col-6">
            <label class="label">تاريخ التسليم</label>
            <input class="input" type="date" name="delivery_date" id="delivery_date" value="<?= e(date('Y-m-d')) ?>" required>
          </div>

          <div class="col-6">
            <label class="label">تاريخ الإرجاع</label>
            <input class="input" type="date" name="return_date" id="return_date" value="<?= e(date('Y-m-d', strtotime('+1 day'))) ?>" required>
            <div class="invoice-inline-note">اليوم إلى الغد = يوم واحد.</div>
          </div>

          <div class="col-6">
            <label class="label">وقت تجهيز المعرس</label>
            <input class="input" type="time" name="groom_prep_time" id="groom_prep_time">
            <div class="invoice-inline-note">اختياري.</div>
          </div>
        </div>

        <div class="invoice-card invoice-soft" style="margin-top:16px">
          <div class="invoice-grid">
            <div class="col-4">
              <label class="label">الفئة</label>
              <select class="select" id="filter_category">
                <option value="">اختر فئة</option>
                <?php foreach($categories as $c): ?>
                  <option value="<?= $c['id'] ?>"><?= e($c['name_ar']) ?></option>
                <?php endforeach; ?>
              </select>
            </div>

            <div class="col-4">
              <label class="label">العناصر المتاحة</label>
              <select class="select" id="available_items">
                <option value="">اختر الفترة والفئة أولاً</option>
              </select>
              <div class="invoice-inline-note">لن تظهر القطع المحجوزة في نفس التاريخ أو الموجودة تحت الصيانة.</div>
            </div>

            <div class="col-2">
              <label class="label">النوع</label>
              <select class="select" id="line_type">
                <option value="rental">إيجار</option>
                <option value="sale">بيع</option>
              </select>
            </div>

            <div class="col-2" style="display:flex;align-items:end">
              <button class="btn secondary" type="button" id="addLineBtn" style="width:100%">إضافة إلى الفاتورة</button>
            </div>
          </div>
        </div>

        <div id="linesContainer" style="margin-top:16px"></div> 

        <div class="invoice-grid" style="margin-top:16px">
          <div class="col-6">
            <label class="label">اسم الموقّع</label>
            <input class="input" name="signature_name" placeholder="اسم العميل أو من ينوب عنه">
          </div>

          <div class="col-6">
            <label class="label">التوقيع</label>
            <canvas id="signaturePad" width="600" height="360" style="width:100%;height:360px;border:1px dashed #d1d5db;border-radius:12px;background:#fff"></canvas>
            <input type="hidden" name="signature_data" id="signature_data">
            <button class="btn light" type="button" id="clearSig" style="margin-top:8px">مسح التوقيع</button>
          </div>
        </div>

        <div class="invoice-card invoice-soft" style="margin-top:16px">
          <h3 style="margin-top:0">الدفعات</h3>
          <div id="paymentsWrap">
            <div class="invoice-grid payment-row">
              <div class="col-3"><label class="label">الطريقة</label><select class="select" name="payments[0][payment_method]"><option value="cash">كاش</option><option value="card">بطاقة</option><option value="transfer">تحويل</option></select></div>
              <div class="col-3"><label class="label">المبلغ</label><input class="input payment-amount" type="number" step="0.001" name="payments[0][amount]" value="0"></div>
              <div class="col-3"><label class="label">مرجع التحويل</label><input class="input" name="payments[0][transfer_reference]" placeholder="مثال: 9999999"></div>
              <div class="col-3"><label class="label">ملاحظات</label><input class="input" name="payments[0][notes]"></div>
            </div>
          </div>
          <div class="invoice-actions" style="margin-top:14px">
            <button type="button" class="btn light" id="addPaymentBtn">إضافة دفعة</button>
          </div>
        </div>

        <div class="invoice-card" style="background:#111827;color:#fff;margin-top:16px">
          <div class="invoice-summary">
            <div class="invoice-stat"><div class="muted" style="color:#cbd5e1">عدد الأيام</div><strong id="daysCount">1</strong></div>
            <div class="invoice-stat"><div class="muted" style="color:#cbd5e1">الإجمالي</div><strong id="grandTotal">0.000</strong></div>
            <div class="invoice-stat"><div class="muted" style="color:#cbd5e1">المدفوع</div><strong id="paidTotal">0.000</strong></div>
            <div class="invoice-stat"><div class="muted" style="color:#cbd5e1">المتبقي</div><strong id="balanceDue">0.000</strong></div>
          </div>
          <label class="label" style="color:#fff;margin-top:14px">ملاحظات</label>
          <textarea class="textarea" name="notes"></textarea>
          <button class="btn secondary" style="margin-top:14px" id="invoiceSubmitBtn">حفظ الفاتورة</button>
        </div>
      </form>
    </div>
  </div>

  <div class="invoice-right-col">
    <div class="card">
      <h3 style="margin-top:0">آخر الفواتير</h3>
      <div class="table-wrap">
        <table class="table">
          <thead><tr><th>رقم</th><th>العميل</th><th>عرض</th></tr></thead>
          <tbody>
          <?php foreach($recentInvoices as $r): ?>
            <tr>
              <td><?= e($r['invoice_no']) ?></td>
              <td><?= e($r['customer_name']) ?></td>
              <td><a class="btn light" href="<?= e(base_url('?page=invoice_show&id='.$r['id'])) ?>">فتح</a></td>
            </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>

<script>
let paymentIndex = 1;
let lineIndex = 0;
const linesWrap = document.getElementById('linesContainer');
const lookup = document.getElementById('customer_lookup');
const suggest = document.getElementById('customerSuggest');
const addPaymentBtn = document.getElementById('addPaymentBtn');
const paymentsWrap = document.getElementById('paymentsWrap');
const delivery = document.getElementById('delivery_date');
const ret = document.getElementById('return_date');
const cat = document.getElementById('filter_category');
const itemsSel = document.getElementById('available_items');
const lineType = document.getElementById('line_type');
const addLineBtn = document.getElementById('addLineBtn');

function rentalDaysBetween(){
  const d1 = new Date(delivery.value);
  const d2 = new Date(ret.value);
  if (isNaN(d1.getTime()) || isNaN(d2.getTime())) return 1;
  const diff = Math.round((d2 - d1) / 86400000);
  return diff > 0 ? diff : 1;
}

function refreshTotals(){
  document.getElementById('daysCount').textContent = rentalDaysBetween();
  let total = 0;
  document.querySelectorAll('.line-item').forEach(row => total += parseFloat(row.dataset.total || '0'));
  let paid = 0;
  document.querySelectorAll('.payment-amount').forEach(el => paid += parseFloat(el.value || '0'));
  document.getElementById('grandTotal').textContent = total.toFixed(3);
  document.getElementById('paidTotal').textContent = paid.toFixed(3);
  document.getElementById('balanceDue').textContent = Math.max(0,total-paid).toFixed(3);
}

function inferTypeMeta(item){
  const rawType = String(
    item.allowed_line_type ??
    item.line_type ??
    item.item_type ??
    item.type ??
    item.availability_type ??
    ''
  ).toLowerCase();

  const rentalOnly = rawType === 'rental' || rawType === 'rental_only' || rawType === 'lease';
  const saleOnly = rawType === 'sale' || rawType === 'sale_only';

  return { rentalOnly, saleOnly, rawType };
}

function setTypeOptionsForItem(item){
  const meta = inferTypeMeta(item);
  lineType.innerHTML = '';

  if (meta.rentalOnly) {
    lineType.innerHTML = '<option value="rental">إيجار</option>';
    lineType.value = 'rental';
    return;
  }

  if (meta.saleOnly) {
    lineType.innerHTML = '<option value="sale">بيع</option>';
    lineType.value = 'sale';
    return;
  }

  lineType.innerHTML = '<option value="rental">إيجار</option><option value="sale">بيع</option>';
}

async function loadAvailableItems(){
  itemsSel.innerHTML = '<option value="">جاري التحميل...</option>';
  if (!cat.value || !delivery.value || !ret.value) {
    itemsSel.innerHTML = '<option value="">اختر الفترة والفئة أولاً</option>';
    return;
  }

  const url = `<?= e(base_url('?page=available_items')) ?>&category_id=${encodeURIComponent(cat.value)}&delivery_date=${encodeURIComponent(delivery.value)}&return_date=${encodeURIComponent(ret.value)}`;
  const res = await fetch(url, { headers: { 'X-Requested-With': 'XMLHttpRequest' }});
  const data = await res.json();

  itemsSel.innerHTML = '<option value="">اختر القطعة</option>';
  const safeItems = (Array.isArray(data) ? data : []).filter(item => {
    const status = String(item.item_status ?? item.status ?? '').toLowerCase();
    if (status === 'maintenance' || status === 'under_maintenance') return false;
    if (item.is_available === false || String(item.is_available) === '0') return false;
    if (String(item.is_booked ?? '') === '1') return false;
    return true;
  });

  safeItems.forEach(item => {
    const opt = document.createElement('option');
    const meta = inferTypeMeta(item);
    const typeLabel = meta.rentalOnly ? ' — إيجار فقط' : (meta.saleOnly ? ' — بيع فقط' : '');
    opt.value = item.id;
    opt.textContent = `${item.item_code} — ${item.item_name || ''} (${item.default_price})${typeLabel}`;
    opt.dataset.price = item.default_price;
    opt.dataset.item = JSON.stringify(item);
    itemsSel.appendChild(opt);
  });

  if (safeItems.length === 0) {
    itemsSel.innerHTML = '<option value="">لا توجد قطع متاحة في هذه الفترة</option>';
  }
}

[delivery, ret, cat].forEach(el => el.addEventListener('change', loadAvailableItems));
itemsSel.addEventListener('change', () => {
  const opt = itemsSel.selectedOptions[0];
  if (!opt || !opt.dataset.item) return;
  try {
    const item = JSON.parse(opt.dataset.item);
    setTypeOptionsForItem(item);
  } catch(e) {}
});

addLineBtn.addEventListener('click', () => {
  const opt = itemsSel.selectedOptions[0];
  if (!opt || !opt.value) return alert('اختر القطعة أولاً');

  const price = parseFloat(opt.dataset.price || '0');
  const type = lineType.value;
  const days = type === 'sale' ? 1 : rentalDaysBetween();
  const total = price * days;

  let selectedItem = null;
  try { selectedItem = opt.dataset.item ? JSON.parse(opt.dataset.item) : null; } catch(e) {}

  const box = document.createElement('div');
  box.className = 'line-item';
  box.dataset.total = total.toFixed(3);

  const typeMeta = selectedItem ? inferTypeMeta(selectedItem) : {rentalOnly:false,saleOnly:false};
  let typeOptions = '';
  if (typeMeta.rentalOnly) {
    typeOptions = '<option value="rental" selected>إيجار</option>';
  } else if (typeMeta.saleOnly) {
    typeOptions = '<option value="sale" selected>بيع</option>';
  } else {
    typeOptions = `<option value="rental" ${type==='rental'?'selected':''}>إيجار</option><option value="sale" ${type==='sale'?'selected':''}>بيع</option>`;
  }

  box.innerHTML = `
    <div class="invoice-grid">
      <div class="col-3">
        <label class="label">القطعة</label>
        <input class="input" value="${opt.textContent.replaceAll('"','&quot;')}" disabled>
        <input type="hidden" name="lines[${lineIndex}][item_id]" value="${opt.value}">
      </div>
      <div class="col-2">
        <label class="label">النوع</label>
        <select class="select line-type" name="lines[${lineIndex}][line_type]">${typeOptions}</select>
      </div>
      <div class="col-2">
        <label class="label">الكمية</label>
        <input class="input qty" type="number" min="1" value="1" name="lines[${lineIndex}][quantity]">
      </div>
      <div class="col-2">
        <label class="label">السعر</label>
        <input class="input price" type="number" step="0.001" value="${price}" name="lines[${lineIndex}][unit_price]">
      </div>
      <div class="col-2">
        <label class="label">الأيام</label>
        <input class="input days" type="number" min="1" value="${days}" disabled>
      </div>
      <div class="col-1" style="display:flex;align-items:end">
        <button class="btn light remove-line" type="button">حذف</button>
      </div>
    </div>
    <div class="line-total-wrap">الإجمالي: <strong class="line-total">${total.toFixed(3)}</strong></div>
  `;

  linesWrap.appendChild(box);
  box.querySelectorAll('.qty,.price,.line-type').forEach(el => el.addEventListener('input', () => updateLine(box)));
  box.querySelector('.remove-line').addEventListener('click', ()=>{ box.remove(); refreshTotals(); });

  lineIndex++;
  refreshTotals();
});

function updateLine(box){
  const type = box.querySelector('.line-type').value;
  const qty = parseFloat(box.querySelector('.qty').value || '1');
  const price = parseFloat(box.querySelector('.price').value || '0');
  const days = type === 'sale' ? 1 : rentalDaysBetween();
  box.querySelector('.days').value = days;
  const total = qty * price * days;
  box.dataset.total = total.toFixed(3);
  box.querySelector('.line-total').textContent = total.toFixed(3);
  refreshTotals();
}

delivery.addEventListener('change', ()=> document.querySelectorAll('.line-item').forEach(updateLine));
ret.addEventListener('change', ()=> document.querySelectorAll('.line-item').forEach(updateLine));

addPaymentBtn.addEventListener('click', ()=>{
  const row = document.createElement('div');
  row.className='invoice-grid payment-row';
  row.innerHTML = `
    <div class="col-3"><label class="label">الطريقة</label><select class="select" name="payments[${paymentIndex}][payment_method]"><option value="cash">كاش</option><option value="card">بطاقة</option><option value="transfer">تحويل</option></select></div>
    <div class="col-3"><label class="label">المبلغ</label><input class="input payment-amount" type="number" step="0.001" name="payments[${paymentIndex}][amount]" value="0"></div>
    <div class="col-3"><label class="label">مرجع التحويل</label><input class="input" name="payments[${paymentIndex}][transfer_reference]"></div>
    <div class="col-3"><label class="label">ملاحظات</label><input class="input" name="payments[${paymentIndex}][notes]"></div>
  `;
  paymentsWrap.appendChild(row);
  paymentIndex++;
  row.querySelector('.payment-amount').addEventListener('input', refreshTotals);
});

document.addEventListener('input', e => {
  if (e.target.classList.contains('payment-amount')) refreshTotals();
});

lookup.addEventListener('input', async ()=>{
  const q = lookup.value.trim();
  if(q.length < 3){ suggest.classList.add('hidden'); suggest.innerHTML=''; return; }

  const exact = await fetch(`<?= e(base_url('?page=customer_lookup')) ?>&q=${encodeURIComponent(q)}`, { headers: { 'X-Requested-With': 'XMLHttpRequest' }}).then(r=>r.json());
  if(exact){
    fillCustomer(exact);
    suggest.classList.add('hidden');
    return;
  }

  const res = await fetch(`<?= e(base_url('?page=customer_search')) ?>&q=${encodeURIComponent(q)}`, { headers: { 'X-Requested-With': 'XMLHttpRequest' }});
  const rows = await res.json();
  suggest.innerHTML = '';
  rows.forEach(row=>{
    const btn = document.createElement('button');
    btn.type='button';
    btn.textContent=`${row.full_name} — ${row.phone}`;
    btn.onclick=()=>{ fillCustomer(row); suggest.classList.add('hidden'); };
    suggest.appendChild(btn);
  });
  suggest.classList.toggle('hidden', rows.length===0);
});

function fillCustomer(row){
  document.getElementById('customer_name').value = row.full_name || '';
  document.getElementById('customer_phone').value = row.phone || '';
  document.getElementById('customer_civil_id').value = row.civil_id || '';

  const flags = document.getElementById('customerFlags');
  const submitBtn = document.getElementById('invoiceSubmitBtn');
  if (parseInt(row.is_blacklisted || 0, 10) === 1) {
    flags.textContent = 'تنبيه: هذا العميل موجود في القائمة السوداء ولا يمكن إنشاء فاتورة له' + (row.blacklist_reason ? ' — ' + row.blacklist_reason : '');
    flags.classList.remove('hidden');
    if (submitBtn) submitBtn.disabled = true;
  } else {
    flags.classList.add('hidden');
    flags.textContent = '';
    if (submitBtn) submitBtn.disabled = false;
  }
}

const canvas = document.getElementById('signaturePad');
const ctx = canvas.getContext('2d');
let drawing = false;

function getPos(e){
  const r = canvas.getBoundingClientRect();
  const p = e.touches ? e.touches[0] : e;
  return {x:(p.clientX-r.left)*(canvas.width/r.width), y:(p.clientY-r.top)*(canvas.height/r.height)};
}
function start(e){ drawing=true; const p=getPos(e); ctx.beginPath(); ctx.moveTo(p.x,p.y); e.preventDefault(); }
function move(e){ if(!drawing)return; const p=getPos(e); ctx.lineTo(p.x,p.y); ctx.strokeStyle='#111'; ctx.lineWidth=2; ctx.lineCap='round'; ctx.stroke(); document.getElementById('signature_data').value = canvas.toDataURL('image/png'); e.preventDefault(); }
function end(){ drawing=false; }

['mousedown','touchstart'].forEach(ev=>canvas.addEventListener(ev,start));
['mousemove','touchmove'].forEach(ev=>canvas.addEventListener(ev,move));
['mouseup','mouseleave','touchend'].forEach(ev=>canvas.addEventListener(ev,end));
document.getElementById('clearSig').onclick = ()=>{ ctx.clearRect(0,0,canvas.width,canvas.height); document.getElementById('signature_data').value=''; };

loadAvailableItems();
refreshTotals();
</script>

<?php include __DIR__.'/../layout/footer.php'; ?>
