<?php
// ============================================================
//  MediCore — Customer List
//  File: customer/list.php
// ============================================================
$page  = 'customer/list';
$title = 'Customer List';
require_once '../includes/header.php';

$cur           = $settings['currency'];
$totalCustomers = (int)   db_val("SELECT COUNT(*)                FROM customers WHERE id > 1");
$totalDue       = (float) db_val("SELECT COALESCE(SUM(due),0)     FROM customers WHERE id > 1");
$totalAdvance   = (float) db_val("SELECT COALESCE(SUM(advance),0) FROM customers WHERE id > 1");
$totalCollected = (float) db_val(
    "SELECT COALESCE(SUM(amount),0) FROM cash_ledger
      WHERE ref LIKE 'CUS-%' AND type = 'in'"
);
?>

<!-- ── Page actions ───────────────────────────────── -->
<script>
document.getElementById('ph-actions').innerHTML = `
  <input type="text" id="srch" placeholder="🔍  Search customer…"
    style="padding:5px 10px;border:1px solid var(--border);border-radius:var(--rsm);
           font-family:inherit;font-size:12px;width:200px;outline:none">
  <select id="filter-status" onchange="applyFilter()"
    style="padding:5px 8px;border:1px solid var(--border);border-radius:var(--rsm);
           font-family:inherit;font-size:12px;outline:none">
    <option value="all">All Customers</option>
    <option value="due">Has Due</option>
    <option value="advance">Has Advance</option>
    <option value="clear">Cleared</option>
  </select>
  <button class="btn btn-primary btn-sm" onclick="openAdd()">➕ Add Customer</button>`;
</script>

<!-- ── Summary cards ──────────────────────────────── -->
<div style="display:grid;grid-template-columns:repeat(4,1fr);gap:10px;margin-bottom:12px">
  <div class="sc" style="border-top:3px solid var(--brand)">
    <div class="slabel">Total Customers</div>
    <div class="sval b"><?= $totalCustomers ?></div>
  </div>
  <div class="sc" style="border-top:3px solid var(--danger)">
    <div class="slabel">Total Due</div>
    <div class="sval b" style="color:var(--danger)"><?= $cur . number_format($totalDue, 2) ?></div>
    <div style="font-size:10px;color:var(--text2);margin-top:2px">Customers owe you</div>
  </div>
  <div class="sc" style="border-top:3px solid var(--accent)">
    <div class="slabel">Total Collected</div>
    <div class="sval b" style="color:var(--accent)"><?= $cur . number_format($totalCollected, 2) ?></div>
    <div style="font-size:10px;color:var(--text2);margin-top:2px">All time</div>
  </div>
  <div class="sc" style="border-top:3px solid var(--purple)">
    <div class="slabel">Total Advance</div>
    <div class="sval b" style="color:var(--purple)"><?= $cur . number_format($totalAdvance, 2) ?></div>
    <div style="font-size:10px;color:var(--text2);margin-top:2px">You owe customers</div>
  </div>
</div>

<!-- ── Table ──────────────────────────────────────── -->
<div class="card" style="padding:0">
  <div class="tw">
    <table id="cus-table">
      <thead>
        <tr>
          <th style="width:40px">#</th>
          <th>Customer Name</th>
          <th>Phone</th>
          <th>Address</th>
          <th style="text-align:right">Total Purchase</th>
          <th style="text-align:right">Total Paid</th>
          <th style="text-align:right">Due</th>
          <th style="text-align:right">Advance</th>
          <th style="text-align:center;width:170px">Actions</th>
        </tr>
      </thead>
      <tbody id="cus-body">
        <tr><td colspan="9" class="empty-state loading-row"><span class="spin"></span>Loading…</td></tr>
      </tbody>
    </table>
  </div>
  <div id="cus-footer"
       style="padding:8px 14px;font-size:11px;color:var(--text3);
              border-top:1px solid var(--border)"></div>
</div>

<script>
const API = '../api/customers.php';
const CUR = '<?= addslashes($cur) ?>';
let allRows = [], timer = null;

// ── Load ──────────────────────────────────────────────────────
async function load(q = '') {
  const tbody = document.getElementById('cus-body');
  tbody.innerHTML = '<tr><td colspan="9" class="empty-state loading-row"><span class="spin"></span>Loading…</td></tr>';

  const r = await apiPost(API, { action: 'list', q });
  if (!r.success) {
    tbody.innerHTML = `<tr><td colspan="9" class="empty-state"
      style="color:var(--danger)">Error: ${r.error}</td></tr>`;
    return;
  }
  allRows = r.data;
  applyFilter();
}

function applyFilter() {
  const filter = document.getElementById('filter-status')?.value || 'all';
  let rows = allRows;
  if (filter === 'due')     rows = allRows.filter(c => parseFloat(c.due)     > 0);
  if (filter === 'advance') rows = allRows.filter(c => parseFloat(c.advance) > 0);
  if (filter === 'clear')   rows = allRows.filter(c => parseFloat(c.due) <= 0 && parseFloat(c.advance) <= 0);
  renderTable(rows);
}

function renderTable(rows) {
  const tbody  = document.getElementById('cus-body');
  const footer = document.getElementById('cus-footer');

  footer.textContent = `Showing ${rows.length} customer${rows.length === 1 ? '' : 's'}`;

  if (!rows.length) {
    tbody.innerHTML = '<tr><td colspan="9" class="empty-state">No customers found.</td></tr>';
    return;
  }

  tbody.innerHTML = rows.map((c, i) => {
    const due     = parseFloat(c.due     || 0);
    const advance = parseFloat(c.advance || 0);

    const dueCell = due > 0
      ? `<span style="font-weight:700;color:var(--danger)">${CUR}${due.toFixed(2)}</span>`
      : `<span style="color:var(--text3)">—</span>`;

    const advCell = advance > 0
      ? `<span style="font-weight:700;color:var(--accent)">${CUR}${advance.toFixed(2)}</span>`
      : `<span style="color:var(--text3)">—</span>`;

    return `<tr data-id="${c.id}">
      <td style="color:var(--text3)">${i + 1}</td>
      <td>
        <div style="font-weight:600">${esc(c.name)}</div>
        <div style="font-size:10px;color:var(--text3)">
          ${parseInt(c.total_invoices||0)} invoice(s)
        </div>
      </td>
      <td class="mono" style="font-size:11.5px">${esc(c.phone || '—')}</td>
      <td style="color:var(--text2);font-size:11px;max-width:150px;
                 overflow:hidden;text-overflow:ellipsis;white-space:nowrap"
          title="${esc(c.address||'')}">
        ${esc(c.address || '—')}
      </td>
      <td class="mono" style="text-align:right">
        ${CUR}${parseFloat(c.total_purchase||0).toFixed(2)}
      </td>
      <td class="mono" style="text-align:right;color:var(--accent)">
        ${CUR}${parseFloat(c.total_paid||0).toFixed(2)}
      </td>
      <td style="text-align:right">${dueCell}</td>
      <td style="text-align:right">${advCell}</td>
      <td style="text-align:center;white-space:nowrap">
        <button class="btn btn-sm btn-teal"
                onclick="openEdit(${c.id})">✏ Edit</button>
        <button class="btn btn-sm"
                style="background:var(--danger-light);color:var(--danger);
                       border-color:#f5a0a0"
                onclick="openCollect(${c.id},'${esc(c.name).replace(/'/g,"\\'")}',${due})"
                ${due <= 0 ? 'disabled style="opacity:.4;cursor:not-allowed"' : ''}>
          💰 Collect
        </button>
        <button class="btn btn-sm btn-danger"
                onclick="del(${c.id},'${esc(c.name).replace(/'/g,"\\'")}',${c.total_invoices||0})">
          🗑
        </button>
      </td>
    </tr>`;
  }).join('');
}

// ── Search ────────────────────────────────────────────────────
document.addEventListener('DOMContentLoaded', () => {
  load();
  const s = document.getElementById('srch');
  s.addEventListener('input', () => {
    clearTimeout(timer);
    timer = setTimeout(() => load(s.value.trim()), 250);
  });
  s.addEventListener('keydown', e => { if (e.key==='Escape') { s.value=''; load(); } });
});

// ── Add / Edit modal ──────────────────────────────────────────
function cusForm(c = {}) {
  return `
  <div style="display:flex;flex-direction:column;gap:10px">
    <div class="fg">
      <label>Customer Name *</label>
      <input id="f-name" value="${esc(c.name||'')}"
             placeholder="Full name">
    </div>
    <div class="fg2">
      <div class="fg">
        <label>Phone</label>
        <input id="f-phone" value="${esc(c.phone||'')}"
               placeholder="01700-000000">
      </div>
      <div class="fg">
        <label>Address</label>
        <input id="f-address" value="${esc(c.address||'')}"
               placeholder="Area / City">
      </div>
    </div>
    ${!c.id ? `
    <div class="fg2">
      <div class="fg">
        <label>Opening Due</label>
        <input id="f-due" type="number" step="0.01" min="0" value="0">
        <span style="font-size:10px;color:var(--text3);margin-top:2px">
          Amount customer owes you before using this system
        </span>
      </div>
      <div class="fg">
        <label>Opening Advance</label>
        <input id="f-advance" type="number" step="0.01" min="0" value="0">
        <span style="font-size:10px;color:var(--text3);margin-top:2px">
          Amount you owe the customer
        </span>
      </div>
    </div>` : ''}
    <div id="f-err" style="color:var(--danger);font-size:11px;display:none"></div>
  </div>
  <div style="display:flex;gap:8px;justify-content:flex-end;
              margin-top:14px;padding-top:12px;border-top:1px solid var(--border)">
    <button class="btn" onclick="closeModal()">Cancel</button>
    <button class="btn btn-primary" onclick="saveCus(${c.id||0})">
      ${c.id ? '💾 Save Changes' : '➕ Add Customer'}
    </button>
  </div>`;
}

function openAdd() {
  showModal(cusForm(), '➕ Add Customer');
  setTimeout(() => document.getElementById('f-name')?.focus(), 50);
}

async function openEdit(id) {
  const r = await apiPost(API, { action: 'detail', id });
  if (!r.success) { alert('Could not load customer.'); return; }
  showModal(cusForm(r.data), '✏ Edit Customer');
  setTimeout(() => document.getElementById('f-name')?.focus(), 50);
}

// ── Collect Due modal ─────────────────────────────────────────
function openCollect(id, name, due) {
  showModal(`
  <div style="margin-bottom:14px">
    <div style="font-size:12px;color:var(--text2);margin-bottom:4px">Collecting from:</div>
    <div style="font-weight:700;font-size:15px">${esc(name)}</div>
    <div style="margin-top:8px;padding:10px 14px;background:var(--danger-light);
                border-radius:var(--rsm);display:flex;justify-content:space-between;
                align-items:center">
      <span style="font-size:12px;color:var(--danger)">Outstanding Due</span>
      <span style="font-weight:700;font-size:16px;color:var(--danger)">
        ${CUR}${parseFloat(due).toFixed(2)}
      </span>
    </div>
  </div>

  <div style="display:flex;flex-direction:column;gap:10px">
    <div class="fg">
      <label>Amount Collecting *</label>
      <input id="c-amount" type="number" step="0.01"
             min="0.01" max="${due}"
             value="${parseFloat(due).toFixed(2)}">
      <span style="font-size:10px;color:var(--text3);margin-top:2px">
        Partial collection allowed
      </span>
    </div>
    <div class="fg">
      <label>Payment Account *</label>
      <select id="c-account">
        <option>Cash</option>
        <option>Bank</option>
        <option>MFS</option>
        <option>Card</option>
      </select>
    </div>
    <div class="fg">
      <label>Note (optional)</label>
      <input id="c-note" placeholder="e.g. Invoice #INV-2025-000012 payment">
    </div>
    <div id="c-err" style="color:var(--danger);font-size:11px;display:none"></div>
  </div>

  <div style="display:flex;gap:8px;justify-content:flex-end;
              margin-top:14px;padding-top:12px;border-top:1px solid var(--border)">
    <button class="btn" onclick="closeModal()">Cancel</button>
    <button class="btn btn-accent" onclick="doCollect(${id}, ${due})">
      💰 Confirm Collection
    </button>
  </div>`, `💰 Collect Due — ${esc(name)}`);

  setTimeout(() => {
    const el = document.getElementById('c-amount');
    el?.focus(); el?.select();
  }, 50);
}

// ── Save customer ─────────────────────────────────────────────
async function saveCus(id) {
  const name  = document.getElementById('f-name').value.trim();
  const errEl = document.getElementById('f-err');

  if (!name) {
    errEl.textContent = '⚠ Customer name is required.';
    errEl.style.display = 'block';
    document.getElementById('f-name').focus();
    return;
  }

  const r = await apiPost(API, {
    action:  id ? 'edit' : 'add',
    id,
    name,
    phone:   document.getElementById('f-phone')?.value.trim()   || '',
    address: document.getElementById('f-address')?.value.trim() || '',
    due:     parseFloat(document.getElementById('f-due')?.value     || 0),
    advance: parseFloat(document.getElementById('f-advance')?.value || 0),
  });

  if (r.success) {
    closeModal();
    load(document.getElementById('srch')?.value || '');
  } else {
    errEl.textContent = '⚠ ' + (r.error || 'Save failed.');
    errEl.style.display = 'block';
  }
}

// ── Process collection ────────────────────────────────────────
async function doCollect(id, maxDue) {
  const amount  = parseFloat(document.getElementById('c-amount').value)  || 0;
  const account = document.getElementById('c-account').value;
  const note    = document.getElementById('c-note').value.trim();
  const errEl   = document.getElementById('c-err');

  if (amount <= 0) {
    errEl.textContent = '⚠ Enter a valid amount.';
    errEl.style.display = 'block'; return;
  }
  if (amount > maxDue + 0.001) {
    errEl.textContent = `⚠ Amount cannot exceed due (${CUR}${maxDue.toFixed(2)}).`;
    errEl.style.display = 'block'; return;
  }

  const r = await apiPost(API, { action: 'collect', id, amount, account, note });
  if (r.success) {
    closeModal();
    load(document.getElementById('srch')?.value || '');
  } else {
    errEl.textContent = '⚠ ' + (r.error || 'Collection failed.');
    errEl.style.display = 'block';
  }
}

// ── Delete ────────────────────────────────────────────────────
async function del(id, name, totalInvoices) {
  if (parseInt(totalInvoices) > 0) {
    alert(`⚠ Cannot delete "${name}".\n\nThis customer has ${totalInvoices} invoice(s).\nYou can edit their details instead.`);
    return;
  }
  if (!confirm(`Delete customer "${name}"?`)) return;
  const r = await apiPost(API, { action: 'delete', id });
  if (r.success) {
    load(document.getElementById('srch')?.value || '');
  } else {
    alert('⚠ ' + (r.error || 'Delete failed.'));
  }
}

// ── Add / View Advance ───────────────────────────────────────
function openAdvance(id, name, advance) {
  showModal(`
  <div style="display:flex;flex-direction:column;gap:10px">
    <div style="display:flex;justify-content:space-between;align-items:center;
                padding:8px 12px;background:var(--accent-xlight);
                border-radius:var(--rsm)">
      <span style="font-size:12px;color:var(--text2)">Current Advance Balance</span>
      <span class="mono" style="font-weight:800;font-size:15px;color:var(--accent)">
        ${CUR}${parseFloat(advance).toFixed(2)}
      </span>
    </div>

    <div class="fg">
      <label>Add Advance Amount *</label>
      <input id="adv-amt" type="number" step="0.01" min="0.01" placeholder="0.00">
    </div>
    <div class="fg">
      <label>Account</label>
      <select id="adv-acct" style="width:100%">
        <option>Cash</option><option>Bank</option>
        <option>MFS</option><option>Card</option>
      </select>
    </div>
    <div class="fg">
      <label>Note (optional)</label>
      <input id="adv-note" placeholder="e.g. Pre-payment for order">
    </div>
    <div id="adv-err" style="color:var(--danger);font-size:11px;display:none"></div>
  </div>
  <div style="display:flex;gap:8px;justify-content:flex-end;
              margin-top:14px;padding-top:12px;border-top:1px solid var(--border)">
    <button class="btn" onclick="viewAdvLedger(${id},'${esc(name)}')">
      📋 View History
    </button>
    <button class="btn" onclick="closeModal()">Cancel</button>
    <button class="btn btn-accent" onclick="saveAdvance(${id})">
      💳 Record Advance
    </button>
  </div>`, `💳 Customer Advance — ${esc(name)}`);
  setTimeout(() => document.getElementById('adv-amt')?.focus(), 50);
}

async function saveAdvance(id) {
  const amount  = parseFloat(document.getElementById('adv-amt').value)  || 0;
  const account = document.getElementById('adv-acct').value;
  const note    = document.getElementById('adv-note').value.trim();
  const errEl   = document.getElementById('adv-err');

  if (amount <= 0) {
    errEl.textContent = '⚠ Enter a valid amount.';
    errEl.style.display = 'block'; return;
  }
  const r = await apiPost('../api/advance.php', {
    action: 'add', customer_id: id, amount, account, note
  });
  if (r.success) {
    closeModal();
    load(document.getElementById('srch')?.value || '');
  } else {
    errEl.textContent = '⚠ ' + (r.error || 'Failed.');
    errEl.style.display = 'block';
  }
}

async function viewAdvLedger(id, name) {
  const r = await apiPost('../api/advance.php', { action:'ledger', customer_id:id });
  if (!r.success) { alert('⚠ ' + r.error); return; }

  const txns = r.txns || [];
  const adjs = r.adjustments || [];
  const bal  = parseFloat(r.customer?.advance || 0);

  const txnRows = txns.length
    ? txns.map(t => `<tr>
        <td>${t.date}</td>
        <td>${esc(t.description)}</td>
        <td class="mono" style="text-align:right;color:var(--accent);font-weight:700">
          +${CUR}${parseFloat(t.amount).toFixed(2)}
        </td>
      </tr>`).join('')
    : '<tr><td colspan="3" class="empty-state">No advance payments</td></tr>';

  const adjRows = adjs.length
    ? adjs.map(a => `<tr>
        <td>${a.date}</td>
        <td class="mono" style="color:var(--brand)">${esc(a.invoice)}</td>
        <td class="mono" style="text-align:right;color:var(--danger);font-weight:700">
          -${CUR}${parseFloat(a.advance_used||0).toFixed(2)}
        </td>
      </tr>`).join('')
    : '<tr><td colspan="3" class="empty-state">No adjustments yet</td></tr>';

  showModal(`
  <div style="padding:8px 14px;background:var(--accent-xlight);
              border-radius:var(--rsm);margin-bottom:12px;
              display:flex;justify-content:space-between">
    <span style="font-weight:600">Available Balance</span>
    <span class="mono" style="font-weight:800;color:var(--accent)">
      ${CUR}${bal.toFixed(2)}
    </span>
  </div>

  <div style="font-weight:700;font-size:12px;margin-bottom:6px;color:var(--accent)">
    💳 Advance Received
  </div>
  <div class="tw" style="max-height:180px;overflow-y:auto;margin-bottom:12px">
    <table>
      <thead><tr><th>Date</th><th>Description</th><th style="text-align:right">Amount</th></tr></thead>
      <tbody>${txnRows}</tbody>
    </table>
  </div>

  <div style="font-weight:700;font-size:12px;margin-bottom:6px;color:var(--danger)">
    📋 Adjusted Against Invoices
  </div>
  <div class="tw" style="max-height:180px;overflow-y:auto">
    <table>
      <thead><tr><th>Date</th><th>Invoice</th><th style="text-align:right">Used</th></tr></thead>
      <tbody>${adjRows}</tbody>
    </table>
  </div>

  <div style="display:flex;justify-content:flex-end;margin-top:12px">
    <button class="btn" onclick="closeModal()">Close</button>
  </div>`, `📋 Advance Ledger — ${esc(name)}`);
}

function esc(s) {
  return String(s||'').replace(/&/g,'&amp;').replace(/</g,'&lt;')
                      .replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}
</script>

<?php require_once '../includes/footer.php'; ?>