/* ====================================================================
   বধুবরণ জুয়েলার্স ERP — Sales List Page
   File: ui/js/sales_list.js
   v2 (2026-06-05): Due payment বাটন + modal যোগ
   ==================================================================== */

(function(){
'use strict';

const API_BASE = '../api/sales/';
const PER_PAGE = 20;

const state = {
  filters: { q:'', from_date:'', to_date:'', payment_status:'all' },
  page: 1,
  totalPages: 0,
  currentSale: null,
  accounts: []
};

const $  = s => document.querySelector(s);
const $$ = s => document.querySelectorAll(s);

const fmtTk = n => '৳ ' + (Number(n)||0).toLocaleString('en-IN',
  {minimumFractionDigits:2, maximumFractionDigits:2});

const fmtTkShort = n => {
  const v = Number(n)||0;
  if (v >= 100000) return '৳ ' + (v/100000).toFixed(1) + 'L';
  if (v >= 1000)   return '৳ ' + Math.round(v/1000) + 'K';
  return '৳ ' + Math.round(v);
};

const fmtW = g => (Number(g)||0).toFixed(3) + 'g';

function escapeHtml(s){
  if(s==null) return '';
  return String(s).replace(/[&<>"']/g, c =>
    ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
}

function debounce(fn, ms){
  let t; return (...a) => { clearTimeout(t); t = setTimeout(()=>fn(...a), ms); };
}

function fmtDate(s){
  if(!s) return '';
  const d = new Date(String(s).replace(' ','T'));
  if(isNaN(d.getTime())) return s;
  const dd = String(d.getDate()).padStart(2,'0');
  const mm = String(d.getMonth()+1).padStart(2,'0');
  const yy = String(d.getFullYear()).slice(-2);
  const hh = String(d.getHours()).padStart(2,'0');
  const mn = String(d.getMinutes()).padStart(2,'0');
  return `${dd}/${mm}/${yy} ${hh}:${mn}`;
}

function today(){
  const d = new Date();
  return d.getFullYear()+'-'+String(d.getMonth()+1).padStart(2,'0')+'-'+String(d.getDate()).padStart(2,'0');
}

async function api(url, opts={}){
  try{
    const r = await fetch(url, {credentials:'same-origin', ...opts});
    return await r.json();
  }catch(e){
    return {ok:false, error:'Network error'};
  }
}

// ── Cash accounts load ──
async function loadAccounts(){
  try{
    const r = await api('../api/cash/get_accounts.php');
    state.accounts = (r.data&&r.data.accounts) ? r.data.accounts
                   : (r.accounts || r.data || []);
  }catch(e){ state.accounts = []; }
}

// ===== List =====
async function loadList(){
  $('#loadingState').classList.remove('hidden');
  $('#salesList').innerHTML = '';
  $('#emptyState').classList.add('hidden');

  const params = new URLSearchParams({
    q: state.filters.q,
    from_date: state.filters.from_date,
    to_date: state.filters.to_date,
    payment_status: state.filters.payment_status,
    page: state.page,
    per_page: PER_PAGE
  });

  const r = await api(`${API_BASE}get_sales_list.php?${params}`);
  $('#loadingState').classList.add('hidden');

  if(!r.ok){
    $('#emptyState').textContent = r.error || 'Load fail';
    $('#emptyState').classList.remove('hidden');
    return;
  }

  const sum = r.summary || {};
  $('#statTotal').textContent = fmtTkShort(sum.sum_grand_total);
  $('#statPaid').textContent  = fmtTkShort(sum.sum_paid_total);
  $('#statDue').textContent   = fmtTkShort(sum.sum_due_amount);
  $('#statCount').textContent = r.total;
  state.totalPages = r.total_pages || 0;

  if(!r.results.length){
    $('#emptyState').textContent = 'কোনো বিক্রি পাওয়া যায়নি';
    $('#emptyState').classList.remove('hidden');
    $('#paginationBar').innerHTML = '';
    return;
  }

  $('#salesList').innerHTML = r.results.map(renderSaleRow).join('');
  renderPagination();
}

function renderSaleRow(s){
  const statusText = s.payment_status==='paid' ? 'Paid'
                   : s.payment_status==='partial' ? 'Partial' : 'Due';
  const dueAmt = Number(s.due_amount)||0;
  const dueLine = dueAmt > 0
    ? `<br><span style="color:var(--red);">Due ${fmtTkShort(dueAmt)}</span>` : '';

  // due payment বাটন (partial বা due হলে)
  const payBtn = (s.payment_status !== 'paid' && dueAmt > 0)
    ? `<button class="due-pay-btn" data-sale-id="${s.id}"
         data-invoice="${escapeHtml(s.invoice_no)}"
         data-due="${dueAmt}"
         style="margin-top:8px;width:100%;padding:9px;
                background:linear-gradient(135deg,#059669,#10B981);
                color:#fff;border:none;border-radius:9px;
                font-size:13px;font-weight:800;cursor:pointer;font-family:inherit;">
         💸 Due পরিশোধ করুন
       </button>` : '';

  return `
    <div class="sale-row" data-sale-id="${s.id}">
      <div class="sale-row-top">
        <span class="sale-row-inv num">${escapeHtml(s.invoice_no)}</span>
        <span class="sale-row-date num">${fmtDate(s.sale_date)}</span>
      </div>
      <div class="sale-row-cust">
        ${escapeHtml(s.customer_name||'— Walk-in')}
        ${s.customer_phone?' • '+escapeHtml(s.customer_phone):''}
      </div>
      <div class="sale-row-meta">
        <span class="sale-row-total num">${fmtTk(s.grand_total)}</span>
        <span class="status-pill status-${s.payment_status}">${statusText}</span>
        <div class="sale-row-extra">
          ${s.item_count||0} item • Paid ${fmtTkShort(s.paid_total)}
          ${dueLine}
        </div>
      </div>
      ${payBtn}
    </div>`;
}

function renderPagination(){
  const bar = $('#paginationBar');
  if(state.totalPages<=1){bar.innerHTML='';return;}
  bar.innerHTML=`
    <button id="btnPrevPage" ${state.page<=1?'disabled':''}>← আগে</button>
    <span class="page-info">${state.page} / ${state.totalPages}</span>
    <button id="btnNextPage" ${state.page>=state.totalPages?'disabled':''}>পরে →</button>`;
}

// ===== Detail Modal =====
async function openDetail(saleId){
  $('#detailBody').innerHTML='<div class="loading">Loading...</div>';
  $('#detailTitle').textContent='Invoice Details';
  $('#detailModal').classList.add('show');
  state.currentSale=null;

  const r = await api(`${API_BASE}get_sale_details.php?id=${saleId}`);
  if(!r.ok){
    $('#detailBody').innerHTML=`<div class="empty-state">${escapeHtml(r.error||'Load fail')}</div>`;
    return;
  }
  state.currentSale=r;
  $('#detailTitle').textContent=r.sale.invoice_no;
  $('#detailBody').innerHTML=renderDetail(r);
}

function renderDetail(d){
  const s=d.sale, items=d.items||[], exchanges=d.exchanges||[], payments=d.payments||[];
  return `
    <div class="detail-section">
      <div class="detail-h">বধুবরণ জুয়েলার্স</div>
      <div class="detail-line"><span>Invoice</span><span class="num">${escapeHtml(s.invoice_no)}</span></div>
      <div class="detail-line"><span>তারিখ</span><span class="num">${fmtDate(s.sale_date)}</span></div>
    </div>
    <div class="detail-section">
      <div class="detail-h">গ্রাহক</div>
      <div class="detail-line"><span>নাম</span><span>${escapeHtml(s.customer_name_snapshot||'— Walk-in')}</span></div>
      <div class="detail-line"><span>মোবাইল</span><span class="num">${escapeHtml(s.customer_phone_snapshot||'—')}</span></div>
    </div>
    <div class="detail-section">
      <div class="detail-h">আইটেম (${items.length})</div>
      ${items.map(it=>`
        <div class="detail-item">
          <div class="detail-item-name">${escapeHtml(it.product_name)}</div>
          <div class="detail-item-meta">
            ${escapeHtml(it.karat||'-')} • ${fmtW(it.gross_weight_gram)} × ৳${(+it.rate_per_gram).toFixed(2)}/g
            ${(+it.making_charge)>0?' + Mk ৳'+(+it.making_charge).toFixed(2):''}
          </div>
          <div class="detail-item-total num">${fmtTk(it.item_total)}</div>
        </div>`).join('')}
    </div>
    ${exchanges.length?`
      <div class="detail-section">
        <div class="detail-h">পুরনো সোনা</div>
        ${exchanges.map(ex=>`
          <div class="detail-item">
            <div class="detail-item-name">${escapeHtml(ex.item_description||'পুরনো সোনা')}</div>
            <div class="detail-item-meta">${escapeHtml(ex.karat)} (${ex.purity_percent}%) • ${fmtW(ex.gross_weight_gram)} → pure ${fmtW(ex.pure_gold_gram)} × ৳${(+ex.rate_per_gram).toFixed(2)}</div>
            <div class="detail-item-total num" style="color:var(--red);">− ${fmtTk(ex.exchange_value)}</div>
          </div>`).join('')}
      </div>` : ''}
    <div class="detail-section">
      <div class="detail-h">হিসাব</div>
      <div class="detail-line"><span>Items Total</span><span class="num">${fmtTk(s.items_subtotal)}</span></div>
      ${(+s.making_charge_total)>0?`<div class="detail-line"><span>Making</span><span class="num">${fmtTk(s.making_charge_total)}</span></div>`:''}
      ${(+s.vat_amount)>0?`<div class="detail-line"><span>VAT (${s.vat_percent}%)</span><span class="num">${fmtTk(s.vat_amount)}</span></div>`:''}
      ${(+s.discount_amount)>0?`<div class="detail-line"><span>Discount</span><span class="num" style="color:var(--red);">− ${fmtTk(s.discount_amount)}</span></div>`:''}
      ${(+s.exchange_value)>0?`<div class="detail-line"><span>Exchange বাদ</span><span class="num" style="color:var(--red);">− ${fmtTk(s.exchange_value)}</span></div>`:''}
    </div>
    <div class="detail-grand">
      <div class="detail-line bold"><span>মোট</span><span class="num">${fmtTk(s.grand_total)}</span></div>
      <div class="detail-line"><span>Paid</span><span class="num" style="color:var(--green);font-weight:600;">${fmtTk(s.paid_total)}</span></div>
      ${(+s.due_amount)>0?`<div class="detail-line"><span>Due</span><span class="num" style="color:var(--red);font-weight:700;">${fmtTk(s.due_amount)}</span></div>`:''}
    </div>
    <div class="detail-section" style="margin-top:14px;">
      <div class="detail-h">পেমেন্ট বিবরণ</div>
      ${payments.map(p=>`
        <div class="detail-line">
          <span>${escapeHtml(p.cash_account_name||'Account #'+p.cash_account_id)}${p.reference_no?' ('+escapeHtml(p.reference_no)+')':''}</span>
          <span class="num" style="color:var(--green);">${fmtTk(p.amount)}</span>
        </div>`).join('')}
    </div>
    ${s.notes?`<div class="detail-section"><div class="detail-h">Notes</div><div style="font-size:14px;">${escapeHtml(s.notes)}</div></div>`:''}`;
}

// ===== Due Payment Modal =====
function injectPayModalIfNeeded(){
  if(document.getElementById('duePayModal')) return;

  const style = document.createElement('style');
  style.textContent=`
    #duePayModal{position:fixed;inset:0;background:rgba(4,8,18,.88);
      backdrop-filter:blur(4px);z-index:200;
      display:none;align-items:flex-end;justify-content:center;}
    #duePayModal.show{display:flex;}
    #duePayBox{background:#0D1829;border:1px solid #1E3358;
      border-radius:20px 20px 0 0;width:100%;max-width:520px;
      padding:22px 18px;max-height:90vh;overflow-y:auto;}
    #duePayBox h3{margin:0 0 4px;color:#F5B800;font-size:17px;font-weight:800;}
    #duePayBox .sub{font-size:13px;color:#7B9BC8;margin-bottom:16px;}
    #duePayBox label{display:block;font-size:12px;color:#7B9BC8;font-weight:700;margin:12px 0 5px;}
    #duePayBox select,#duePayBox input{
      width:100%;background:#0A1424;border:1.5px solid #1E3358;
      color:#F1F5FD;padding:11px 13px;border-radius:10px;
      font-size:15px;font-family:inherit;}
    #duePayBox select:focus,#duePayBox input:focus{outline:none;border-color:rgba(245,184,0,.5);}
    #duePayBox .due-info{background:rgba(239,68,68,.1);border:1px solid rgba(239,68,68,.25);
      border-radius:8px;padding:10px 12px;font-size:13px;color:#FCA5A5;margin-top:10px;}
    #duePayBox .btn-row{display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-top:16px;}
    #duePayBox .cancel-btn{background:rgba(255,255,255,.06);border:1px solid #1E3358;
      color:#7B9BC8;padding:13px;border-radius:11px;font-size:14px;font-weight:700;cursor:pointer;font-family:inherit;}
    #duePayBox .save-btn{background:linear-gradient(135deg,#059669,#10B981);
      color:#fff;border:none;padding:13px;border-radius:11px;
      font-size:15px;font-weight:800;cursor:pointer;font-family:inherit;}
    #duePayBox .save-btn:disabled{opacity:.5;cursor:not-allowed;}
    #duePayBox .msg-ok{background:rgba(16,185,129,.1);border:1px solid rgba(16,185,129,.2);
      color:#10B981;padding:10px;border-radius:9px;text-align:center;display:none;font-weight:700;margin-top:12px;}
    #duePayBox .msg-er{background:rgba(239,68,68,.1);border:1px solid rgba(239,68,68,.2);
      color:#FCA5A5;padding:10px;border-radius:9px;text-align:center;display:none;font-weight:700;margin-top:12px;}`;
  document.head.appendChild(style);

  const div = document.createElement('div');
  div.id = 'duePayModal';
  div.innerHTML = `
    <div id="duePayBox">
      <h3 id="dpTitle">💸 Due পরিশোধ</h3>
      <div class="sub" id="dpSub"></div>
      <label>অ্যাকাউন্ট</label>
      <select id="dpAccount"></select>
      <label>পরিমাণ (৳)</label>
      <input type="number" id="dpAmount" min="1" step="0.01" placeholder="0.00">
      <div class="due-info" id="dpDueInfo"></div>
      <label>তারিখ</label>
      <input type="date" id="dpDate">
      <label>নোট (ঐচ্ছিক)</label>
      <input type="text" id="dpNote" placeholder="যেমন: বাকি পরিশোধ">
      <div class="msg-ok" id="dpOk"></div>
      <div class="msg-er" id="dpEr"></div>
      <div class="btn-row">
        <button class="cancel-btn" id="dpCancel">বাতিল</button>
        <button class="save-btn" id="dpSave">✅ সংরক্ষণ করুন</button>
      </div>
    </div>`;
  document.body.appendChild(div);
}

let _dpSaleId = null, _dpDue = 0;

function openDuePayModal(saleId, invoiceNo, due){
  injectPayModalIfNeeded();
  _dpSaleId = saleId;
  _dpDue    = due;

  document.getElementById('dpTitle').textContent = '💸 Due পরিশোধ — ' + invoiceNo;
  document.getElementById('dpSub').textContent   = 'বকেয়া পরিশোধ করুন';
  document.getElementById('dpDueInfo').textContent = 'বর্তমান বকেয়া: ৳' + Number(due).toLocaleString('en-IN',{minimumFractionDigits:2});
  document.getElementById('dpAmount').value  = due;
  document.getElementById('dpDate').value    = today();
  document.getElementById('dpNote').value    = '';
  document.getElementById('dpOk').style.display = 'none';
  document.getElementById('dpEr').style.display = 'none';
  document.getElementById('dpSave').disabled = false;
  document.getElementById('dpSave').textContent = '✅ সংরক্ষণ করুন';

  // accounts populate
  const sel = document.getElementById('dpAccount');
  sel.innerHTML = state.accounts.length
    ? state.accounts.map(a=>`<option value="${a.id}">${a.account_name||a.name} (৳${Number(a.current_balance||a.balance||0).toLocaleString('en-IN',{maximumFractionDigits:0})})</option>`).join('')
    : '<option value="">অ্যাকাউন্ট লোড হয়নি</option>';

  document.getElementById('duePayModal').classList.add('show');
}

function closeDuePayModal(){
  const m = document.getElementById('duePayModal');
  if(m) m.classList.remove('show');
  _dpSaleId = null;
}

async function saveDuePayment(){
  const btn    = document.getElementById('dpSave');
  const okBox  = document.getElementById('dpOk');
  const erBox  = document.getElementById('dpEr');
  okBox.style.display = 'none';
  erBox.style.display = 'none';

  const amount    = parseFloat(document.getElementById('dpAmount').value);
  const accountId = parseInt(document.getElementById('dpAccount').value);
  const date      = document.getElementById('dpDate').value;
  const note      = document.getElementById('dpNote').value;

  if(!amount || amount<=0){ erBox.textContent='পরিমাণ দিন'; erBox.style.display='block'; return; }
  if(!accountId)           { erBox.textContent='অ্যাকাউন্ট বেছে নিন'; erBox.style.display='block'; return; }

  btn.disabled=true; btn.textContent='সংরক্ষণ হচ্ছে...';

  try{
    const r = await api('../api/sales/sale_payment.php', {
      method:'POST',
      headers:{'Content-Type':'application/json'},
      body: JSON.stringify({
        sale_id: _dpSaleId,
        cash_account_id: accountId,
        amount, note,
        payment_date: date,
      })
    });

    if(r.ok){
      okBox.textContent = '✅ ' + (r.message||'Payment সফল');
      okBox.style.display='block';
      setTimeout(()=>{ closeDuePayModal(); loadList(); }, 1200);
    } else {
      erBox.textContent = r.error || 'ব্যর্থ হয়েছে';
      erBox.style.display='block';
    }
  }catch(e){
    erBox.textContent='সংযোগ ব্যর্থ';
    erBox.style.display='block';
  }

  btn.disabled=false;
  btn.textContent='✅ সংরক্ষণ করুন';
}

function closeModal(id){ const m=$('#'+id); if(m) m.classList.remove('show'); }
function printInvoice(){ if(state.currentSale) window.print(); }

// ===== Event Delegation =====
document.addEventListener('click', e => {
  const t = e.target;

  // due pay button — sale-row এর বাটন
  const dpBtn = t.closest ? t.closest('.due-pay-btn') : null;
  if(dpBtn){
    e.stopPropagation();
    openDuePayModal(
      parseInt(dpBtn.dataset.saleId),
      dpBtn.dataset.invoice,
      parseFloat(dpBtn.dataset.due)
    );
    return;
  }

  // due pay modal cancel
  if(t.id==='dpCancel' || (t.id==='duePayModal' && t===e.currentTarget)){
    closeDuePayModal(); return;
  }
  if(t.id==='dpSave'){ saveDuePayment(); return; }

  // detail modal close
  if(t.matches('[data-close]')){ closeModal(t.getAttribute('data-close')); return; }
  if(t.classList.contains('modal-bg') && t.id){ closeModal(t.id); return; }

  // sale row → detail (বাটন click হলে detail খুলবে না)
  const row = t.closest ? t.closest('.sale-row') : null;
  if(row && !t.closest('.due-pay-btn')){
    openDetail(parseInt(row.dataset.saleId,10)); return;
  }

  if(t.matches('#btnPrintInvoice')){ printInvoice(); return; }
  if(t.matches('#btnPrevPage')){ if(state.page>1){state.page--;loadList();} return; }
  if(t.matches('#btnNextPage')){ if(state.page<state.totalPages){state.page++;loadList();} return; }
});

const onFilterChange = debounce(()=>{
  state.filters.q             = $('#searchQ').value.trim();
  state.filters.from_date     = $('#fromDate').value;
  state.filters.to_date       = $('#toDate').value;
  state.filters.payment_status= $('#paymentStatus').value;
  state.page=1; loadList();
}, 300);

document.addEventListener('input', e=>{
  if(e.target.matches('#searchQ,#fromDate,#toDate')) onFilterChange();
});
document.addEventListener('change', e=>{
  if(e.target.matches('#paymentStatus,#fromDate,#toDate')) onFilterChange();
});

// ===== Init =====
async function init(){
  const d = new Date();
  const first = new Date(d.getFullYear(), d.getMonth(), 1);
  const toISO = d2 => d2.getFullYear()+'-'+String(d2.getMonth()+1).padStart(2,'0')+'-'+String(d2.getDate()).padStart(2,'0');
  $('#fromDate').value = toISO(first);
  $('#toDate').value   = toISO(d);
  state.filters.from_date = $('#fromDate').value;
  state.filters.to_date   = $('#toDate').value;

  await loadAccounts();
  loadList();
}

init();
})();