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

$cur          = $settings['currency'];
$totalSuppliers = (int)   db_val("SELECT COUNT(*)              FROM suppliers");
$totalPayable   = (float) db_val("SELECT COALESCE(SUM(balance),0) FROM suppliers");
$totalPaid      = (float) db_val("SELECT COALESCE(SUM(IF(type='out',amount,0)),0)
                                    FROM cash_ledger WHERE ref LIKE 'SUP-%'");
?>

<!-- ── Page actions ───────────────────────────────── -->
<script>
document.getElementById('ph-actions').innerHTML = `
  <input type="text" id="srch" placeholder="🔍  Search supplier…"
    style="padding:5px 10px;border:1px solid var(--border);border-radius:var(--rsm);
           font-family:inherit;font-size:12px;width:200px;outline:none">
  <button class="btn btn-primary btn-sm" onclick="openAdd()">➕ Add Supplier</button>`;
</script>

<!-- ── Summary cards ──────────────────────────────── -->
<div style="display:grid;grid-template-columns:repeat(3,1fr);gap:10px;margin-bottom:12px">
  <div class="sc" style="border-top:3px solid var(--brand)">
    <div class="slabel">Total Suppliers</div>
    <div class="sval b"><?= $totalSuppliers ?></div>
  </div>
  <div class="sc" style="border-top:3px solid var(--danger)">
    <div class="slabel">Total Payable</div>
    <div class="sval b" style="color:var(--danger)"><?= $cur . number_format($totalPayable, 2) ?></div>
    <div style="font-size:10px;color:var(--text2);margin-top:2px">Outstanding balance</div>
  </div>
  <div class="sc" style="border-top:3px solid var(--accent)">
    <div class="slabel">Total Paid</div>
    <div class="sval b" style="color:var(--accent)"><?= $cur . number_format($totalPaid, 2) ?></div>
    <div style="font-size:10px;color:var(--text2);margin-top:2px">All time payments</div>
  </div>
</div>

<!-- ── Table ──────────────────────────────────────── -->
<div class="card" style="padding:0">
  <div class="tw">
    <table id="sup-table">
      <thead>
        <tr>
          <th style="width:40px">#</th>
          <th>Supplier Name</th>
          <th>Contact Person</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">Balance Due</th>
          <th style="text-align:center;width:160px">Actions</th>
        </tr>
      </thead>
      <tbody id="sup-body">
        <tr><td colspan="9" class="empty-state">Loading…</td></tr>
      </tbody>
    </table>
  </div>
  <div id="sup-footer"
       style="padding:8px 14px;font-size:11px;color:var(--text3);
              border-top:1px solid var(--border)"></div>
</div>

<script>
const API = '../api/suppliers.php';
const CUR = '<?= addslashes($cur) ?>';
let timer = null;

// ── Load ──────────────────────────────────────────────────────
async function load(q = '') {
  const tbody = document.getElementById('sup-body');
  tbody.innerHTML = '<tr><td colspan="9" class="empty-state">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;
  }

  const rows = r.data;
  document.getElementById('sup-footer').textContent =
    `Showing ${rows.length} supplier${rows.length === 1 ? '' : 's'}`;

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

  tbody.innerHTML = rows.map((s, i) => {
    const bal     = parseFloat(s.balance || 0);
    const balCell = bal > 0
      ? `<span style="font-weight:700;color:var(--danger)">${CUR}${bal.toFixed(2)}</span>`
      : `<span style="color:var(--accent)">✓ Cleared</span>`;

    return `<tr data-id="${s.id}">
      <td style="color:var(--text3)">${i + 1}</td>
      <td>
        <div style="font-weight:600">${esc(s.name)}</div>
      </td>
      <td style="color:var(--text2)">${esc(s.contact || '—')}</td>
      <td class="mono" style="font-size:11.5px">${esc(s.phone || '—')}</td>
      <td style="color:var(--text2);font-size:11px;max-width:160px;
                 overflow:hidden;text-overflow:ellipsis;white-space:nowrap"
          title="${esc(s.address||'')}">
        ${esc(s.address || '—')}
      </td>
      <td class="mono" style="text-align:right">${CUR}${parseFloat(s.total_purchase||0).toFixed(2)}</td>
      <td class="mono" style="text-align:right;color:var(--accent)">
        ${CUR}${parseFloat(s.total_paid||0).toFixed(2)}
      </td>
      <td style="text-align:right">${balCell}</td>
      <td style="text-align:center;white-space:nowrap">
        <button class="btn btn-sm btn-teal"
                onclick="openEdit(${s.id})">✏ Edit</button>
        <button class="btn btn-sm btn-warn"
                onclick="openPay(${s.id},'${esc(s.name).replace(/'/g,"\\'")}',${bal})"
                ${bal <= 0 ? 'disabled style="opacity:.4;cursor:not-allowed"' : ''}>
          💳 Pay
        </button>
        <button class="btn btn-sm btn-danger"
                onclick="del(${s.id},'${esc(s.name).replace(/'/g,"\\'")}',${s.total_purchase||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 form ────────────────────────────────────
function supForm(s = {}) {
  return `
  <div style="display:flex;flex-direction:column;gap:10px">
    <div class="fg">
      <label>Supplier Name *</label>
      <input id="f-name" value="${esc(s.name||'')}"
             placeholder="e.g. Popular Drug House Ltd.">
    </div>
    <div class="fg2">
      <div class="fg">
        <label>Contact Person</label>
        <input id="f-contact" value="${esc(s.contact||'')}"
               placeholder="Name of sales rep">
      </div>
      <div class="fg">
        <label>Phone</label>
        <input id="f-phone" value="${esc(s.phone||'')}"
               placeholder="01700-000000">
      </div>
    </div>
    <div class="fg">
      <label>Address</label>
      <textarea id="f-address" rows="2"
        style="padding:6px 9px;border:1px solid var(--border);border-radius:var(--rsm);
               font-family:inherit;font-size:12px;resize:vertical;outline:none"
        placeholder="Full address">${esc(s.address||'')}</textarea>
    </div>
    ${!s.id ? `
    <div class="fg">
      <label>Opening Balance (amount already owed)</label>
      <input id="f-balance" type="number" step="0.01" min="0" value="0"
             placeholder="0.00">
      <span style="font-size:10px;color:var(--text3);margin-top:2px">
        Enter if you already owe this supplier money before using this system.
      </span>
    </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="saveSup(${s.id||0})">
      ${s.id ? '💾 Save Changes' : '➕ Add Supplier'}
    </button>
  </div>`;
}

function openAdd() {
  showModal(supForm(), '➕ Add Supplier');
  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 supplier.'); return; }
  showModal(supForm(r.data), '✏ Edit Supplier');
  setTimeout(() => document.getElementById('f-name')?.focus(), 50);
}

// ── Pay modal ─────────────────────────────────────────────────
function openPay(id, name, balance) {
  showModal(`
  <div style="margin-bottom:12px">
    <div style="font-size:12px;color:var(--text2);margin-bottom:6px">Paying to:</div>
    <div style="font-weight:700;font-size:14px">${esc(name)}</div>
    <div style="margin-top:6px;font-size:12px">
      Current Balance:
      <span style="font-weight:700;color:var(--danger)">${CUR}${parseFloat(balance).toFixed(2)}</span>
    </div>
  </div>

  <div style="display:flex;flex-direction:column;gap:10px">
    <div class="fg">
      <label>Payment Amount *</label>
      <input id="p-amount" type="number" step="0.01" min="0.01"
             max="${balance}" value="${parseFloat(balance).toFixed(2)}"
             placeholder="0.00">
      <span style="font-size:10px;color:var(--text3);margin-top:2px">
        Max payable: ${CUR}${parseFloat(balance).toFixed(2)}
      </span>
    </div>
    <div class="fg">
      <label>Payment Account *</label>
      <select id="p-account">
        <option>Cash</option>
        <option>Bank</option>
        <option>MFS</option>
        <option>Card</option>
      </select>
    </div>
    <div class="fg">
      <label>Note (optional)</label>
      <input id="p-note" placeholder="e.g. Invoice #1234 payment">
    </div>
    <div id="p-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-warn" onclick="doPay(${id}, ${balance})">
      💳 Confirm Payment
    </button>
  </div>`, `💳 Pay Supplier — ${esc(name)}`);

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

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

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

  const payload = {
    action:   id ? 'edit' : 'add',
    id,
    name,
    contact:  document.getElementById('f-contact')?.value.trim() || '',
    phone:    document.getElementById('f-phone')?.value.trim()   || '',
    address:  document.getElementById('f-address')?.value.trim() || '',
    balance:  parseFloat(document.getElementById('f-balance')?.value || 0),
  };

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

// ── Process payment ───────────────────────────────────────────
async function doPay(id, maxBalance) {
  const amount  = parseFloat(document.getElementById('p-amount').value)  || 0;
  const account = document.getElementById('p-account').value;
  const note    = document.getElementById('p-note').value.trim();
  const errEl   = document.getElementById('p-err');

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

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

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

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'; ?>
