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

$cfg = $settings;
$cur = $cfg['currency'];

// Staff list for the "Created By" filter dropdown
$staffList = db_rows("SELECT id, name FROM users ORDER BY name");

// Summary totals
$totalSales  = (int)   db_val("SELECT COUNT(*)                     FROM sales");
$totalRev    = (float) db_val("SELECT COALESCE(SUM(final_price),0)  FROM sales");
$totalPaid   = (float) db_val("SELECT COALESCE(SUM(paid),0)         FROM sales");
$totalDue    = (float) db_val("SELECT COALESCE(SUM(due),0)          FROM sales");
$totalProfit = (float) db_val("SELECT COALESCE(SUM(approx_profit),0)FROM sales");
?>

<!-- ── Page actions ───────────────────────────────── -->
<script>
document.getElementById('ph-actions').innerHTML = `
  <input type="text" id="srch"
         placeholder="🔍  Invoice # or customer…"
    style="padding:5px 10px;border:1px solid var(--border);
           border-radius:var(--rsm);font-family:inherit;
           font-size:12px;width:180px;outline:none">
  <input type="date" id="f-from" title="From date"
    style="padding:5px 8px;border:1px solid var(--border);
           border-radius:var(--rsm);font-family:inherit;
           font-size:12px;outline:none">
  <input type="date" id="f-to" title="To date"
    style="padding:5px 8px;border:1px solid var(--border);
           border-radius:var(--rsm);font-family:inherit;
           font-size:12px;outline:none">
  <select id="f-status" onchange="load()"
    style="padding:5px 8px;border:1px solid var(--border);
           border-radius:var(--rsm);font-family:inherit;
           font-size:12px;outline:none">
    <option value="">All Status</option>
    <option value="Paid">Paid</option>
    <option value="Partial">Partial</option>
    <option value="Due">Due</option>
  </select>
  <select id="f-staff" onchange="load()"
    style="padding:5px 8px;border:1px solid var(--border);
           border-radius:var(--rsm);font-family:inherit;
           font-size:12px;outline:none">
    <option value="">All Staff</option>
    <?php foreach ($staffList as $u): ?>
    <option value="<?= (int)$u['id'] ?>"><?= htmlspecialchars($u['name']) ?></option>
    <?php endforeach; ?>
  </select>
  <button class="btn btn-sm" onclick="exportCSV()">📤 Export CSV</button>
  <a class="btn btn-primary btn-sm" href="entry.php">🛒 New Sale</a>`;
</script>

<!-- ── Summary cards ──────────────────────────────── -->
<div style="display:grid;grid-template-columns:repeat(<?= can_view_profit() ? 5 : 4 ?>,1fr);
            gap:10px;margin-bottom:12px">
  <div class="sc" style="border-top:3px solid var(--brand)">
    <div class="slabel">Total Invoices</div>
    <div class="sval b"><?= $totalSales ?></div>
  </div>
  <div class="sc" style="border-top:3px solid var(--text2)">
    <div class="slabel">Total Revenue</div>
    <div class="sval b"><?= $cur . number_format($totalRev, 2) ?></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($totalPaid, 2) ?>
    </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>
  <?php if (can_view_profit()): ?>
  <div class="sc" style="border-top:3px solid var(--teal)">
    <div class="slabel">Total Profit</div>
    <div class="sval b" style="color:var(--teal)">
      <?= $cur . number_format($totalProfit, 2) ?>
    </div>
  </div>
  <?php endif; ?>
</div>

<!-- ── Table ──────────────────────────────────────── -->
<div class="card" style="padding:0">
  <div class="tw">
    <table id="sale-table">
      <thead>
        <tr>
          <th style="width:38px">#</th>
          <th>Invoice #</th>
          <th>Customer</th>
          <th>Date</th>
          <th style="text-align:center">Items</th>
          <th style="text-align:right">Amount</th>
          <th style="text-align:right">Paid</th>
          <th style="text-align:right">Due</th>
          <?php if (can_view_profit()): ?>
          <th style="text-align:right">Profit</th>
          <?php endif; ?>
          <th style="text-align:center">Type</th>
          <th style="text-align:center">Status</th>
          <th>Staff</th>
          <th style="text-align:center;width:160px">Actions</th>
        </tr>
      </thead>
      <tbody id="sale-body">
        <tr><td colspan="<?= can_view_profit() ? 13 : 12 ?>" class="empty-state loading-row"><span class="spin"></span>Loading…</td></tr>
      </tbody>
    </table>
  </div>
  <div id="sale-footer"
       style="padding:8px 14px;font-size:11px;color:var(--text3);
              border-top:1px solid var(--border)"></div>
</div>

<script>
const API      = '../api/sales.php';
const CUR      = '<?= addslashes($cur) ?>';
const SHOP     = <?= json_encode([
  'name'    => $settings['shop_name'],
  'address' => $settings['address'],
  'phone'   => $settings['phone'],
  'note'    => $settings['invoice_note'],
]) ?>;
const IS_ADMIN = <?= is_admin() ? 'true' : 'false' ?>;
// Gates the "Total Profit" summary card, the Profit column, and the
// PROFIT figure in the invoice detail modal — same "Profit Visibility"
// permission used across Sale Entry/Product List/Dashboard.
const CAN_VIEW_PROFIT = <?= can_view_profit() ? 'true' : 'false' ?>;
const COLS = CAN_VIEW_PROFIT ? 13 : 12; // total <th> count, varies with the Profit column
let timer = null;

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

  const r = await apiPost(API, {
    action:     'list',
    q:          document.getElementById('srch')?.value.trim()   || '',
    from:       document.getElementById('f-from')?.value        || '',
    to:         document.getElementById('f-to')?.value          || '',
    status:     document.getElementById('f-status')?.value      || '',
    created_by: document.getElementById('f-staff')?.value       || '',
  });

  if (!r.success) {
    tbody.innerHTML = `<tr><td colspan="${COLS}" class="empty-state"
      style="color:var(--danger)">Error: ${r.error}</td></tr>`;
    return;
  }
  renderTable(r.data);
}

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

  if (!rows.length) {
    tbody.innerHTML =
      `<tr><td colspan="${COLS}" class="empty-state">No sales found.</td></tr>`;
    footer.textContent = ''; return;
  }

  const fRev    = rows.reduce((s,r) => s + parseFloat(r.final_price||0), 0);
  const fPaid   = rows.reduce((s,r) => s + parseFloat(r.paid||0),        0);
  const fDue    = rows.reduce((s,r) => s + parseFloat(r.due||0),         0);
  const fProfit = rows.reduce((s,r) => s + parseFloat(r.approx_profit||0),0);
  footer.innerHTML =
    `<strong>${rows.length}</strong> invoice(s) &nbsp;·&nbsp;
     Revenue: <strong>${CUR}${fRev.toFixed(2)}</strong> &nbsp;·&nbsp;
     Paid: <strong style="color:var(--accent)">${CUR}${fPaid.toFixed(2)}</strong> &nbsp;·&nbsp;
     Due: <strong style="color:var(--danger)">${CUR}${fDue.toFixed(2)}</strong>${CAN_VIEW_PROFIT ? ` &nbsp;·&nbsp;
     Profit: <strong style="color:var(--teal)">${CUR}${fProfit.toFixed(2)}</strong>` : ''}`;

  const payIcons = { Cash:'💵', Card:'💳', Bank:'🏦', MFS:'📱' };

  tbody.innerHTML = rows.map((s, i) => {
    const due    = parseFloat(s.due    || 0);
    const paid   = parseFloat(s.paid   || 0);
    const profit = parseFloat(s.approx_profit || 0);

    const stBg = s.status === 'Paid'
      ? '#d4f0e6' : s.status === 'Partial' ? '#fff3dc' : '#fde8e8';
    const stCl = s.status === 'Paid'
      ? 'var(--accent)' : s.status === 'Partial' ? 'var(--warn)' : 'var(--danger)';

    return `<tr data-id="${s.id}">
      <td style="color:var(--text3)">${i + 1}</td>
      <td>
        <span class="mono"
              style="font-weight:700;color:var(--brand);cursor:pointer"
              onclick="viewDetail(${s.id})"
              title="Click to view detail">
          ${esc(s.invoice)}
        </span>
      </td>
      <td style="font-weight:500">${esc(s.customer_name || 'Walk-in')}</td>
      <td style="color:var(--text2)">${s.date || '—'}</td>
      <td style="text-align:center">
        <span class="badge" style="background:var(--surface2);color:var(--text2)">
          ${s.item_count}
        </span>
      </td>
      <td class="mono" style="text-align:right;font-weight:700">
        ${CUR}${parseFloat(s.final_price||0).toFixed(2)}
      </td>
      <td class="mono" style="text-align:right;color:var(--accent)">
        ${CUR}${paid.toFixed(2)}
      </td>
      <td style="text-align:right">
        ${due > 0
          ? `<span class="mono" style="font-weight:700;color:var(--danger)">${CUR}${due.toFixed(2)}</span>`
          : `<span style="color:var(--accent)">✓</span>`}
      </td>
      ${CAN_VIEW_PROFIT ? `<td class="mono" style="text-align:right;font-size:11px;
                               color:${profit>=0?'var(--teal)':'var(--danger)'}">
        ${CUR}${profit.toFixed(2)}
      </td>` : ''}
      <td style="text-align:center;font-size:12px">
        ${payIcons[s.payment_type] || ''}
        <span style="font-size:10px;color:var(--text3)">${esc(s.payment_type||'')}</span>
      </td>
      <td style="text-align:center">
        <span class="badge" style="background:${stBg};color:${stCl}">
          ${s.status}
        </span>
      </td>
      <td style="font-size:11px;color:var(--text2)">${esc(s.created_by_name || '—')}</td>
      <td style="text-align:center;white-space:nowrap">
        <button class="btn btn-sm btn-teal"
                onclick="viewDetail(${s.id})">🔍 View</button>
        <button class="btn btn-sm"
                style="background:#fde8e8;color:var(--danger);border-color:#f5a0a0"
                onclick="window.location.href='return.php?invoice=${encodeURIComponent(s.invoice)}'">
          ↩ Return
        </button>
        ${s.status !== 'Paid'
          ? `<button class="btn btn-sm"
                     style="background:#fff3dc;color:var(--warn);border-color:#f5c842"
                     onclick="openPayDue(${s.id},'${esc(s.invoice).replace(/'/g,"\\'")}',${due})">
               💰 Pay</button>`
          : ''}
        ${IS_ADMIN
          ? `<button class="btn btn-sm btn-danger"
                     onclick="delSale(${s.id},'${esc(s.invoice).replace(/'/g,"\\'")}')">🗑</button>`
          : ''}
      </td>
    </tr>`;
  }).join('');
}

// ── View detail modal ─────────────────────────────────────────
async function viewDetail(id) {
  showModal(
    `<div style="text-align:center;padding:20px;color:var(--text3)">⏳ Loading…</div>`,
    '🧾 Invoice Detail', 'xl'
  );

  const r = await apiPost(API, { action: 'detail', id });
  if (!r.success) {
    document.querySelector('.mbox').innerHTML =
      `<div style="padding:20px;color:var(--danger)">Error: ${r.error}</div>`;
    return;
  }

  const s     = r.data;
  const items = r.items || [];
  const due   = parseFloat(s.due  || 0);
  const paid  = parseFloat(s.paid || 0);
  const total = parseFloat(s.final_price || 0);
  const profit = parseFloat(s.approx_profit || 0);

  const stCl = s.status==='Paid' ? 'var(--accent)'
             : s.status==='Partial' ? 'var(--warn)' : 'var(--danger)';

  const itemRows = items.map((it, i) => {
    const lineTotal = parseFloat(it.after_disc || it.total || 0);
    return `<tr>
      <td style="color:var(--text3)">${i+1}</td>
      <td>
        <div style="font-weight:600;font-size:12px">${formIconName(it.form, it.product_name)}</div>
        <div style="font-size:10px;color:var(--text3)">
          ${it.strength||''} ${it.form ? '· '+it.form : ''}
          ${it.rack ? '· Rack: '+esc(it.rack) : ''}
        </div>
      </td>
      <td class="mono" style="text-align:center">${it.qty}</td>
      <td class="mono" style="text-align:right">${CUR}${parseFloat(it.price||0).toFixed(2)}</td>
      <td class="mono" style="text-align:center;color:var(--danger)">
        ${parseFloat(it.discount_pct||0) > 0
          ? parseFloat(it.discount_pct).toFixed(1)+'%' : '—'}
      </td>
      <td class="mono" style="text-align:right;font-weight:700">
        ${CUR}${lineTotal.toFixed(2)}
      </td>
    </tr>`;
  }).join('');

  document.querySelector('.mbox').innerHTML = `
    <div class="mtitle">
      🧾 Invoice:
      <span class="mono" style="color:var(--brand)">${esc(s.invoice)}</span>
      <button class="mclose" onclick="closeModal()">×</button>
    </div>

    <!-- Header info -->
    <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:8px;
                padding:10px 14px;border-bottom:1px solid var(--border)">
      <div>
        <div style="font-size:10px;color:var(--text3)">Customer</div>
        <div style="font-weight:700">${esc(s.customer_name||'Walk-in')}</div>
      </div>
      <div>
        <div style="font-size:10px;color:var(--text3)">Date</div>
        <div style="font-weight:600">${s.date}</div>
      </div>
      <div>
        <div style="font-size:10px;color:var(--text3)">Payment</div>
        <div>${s.payment_type}</div>
      </div>
      <div>
        <div style="font-size:10px;color:var(--text3)">Status</div>
        <div style="font-weight:700;color:${stCl}">${s.status}</div>
      </div>
    </div>

    <!-- Items -->
    <div class="tw" style="max-height:320px;overflow-y:auto">
      <table>
        <thead><tr>
          <th>#</th><th>Product</th>
          <th style="text-align:center">Qty</th>
          <th style="text-align:right">Price/pc</th>
          <th style="text-align:center">Disc%</th>
          <th style="text-align:right">Total</th>
        </tr></thead>
        <tbody>${itemRows}</tbody>
      </table>
    </div>

    <!-- Totals -->
    <div style="display:grid;grid-template-columns:1fr auto auto auto${CAN_VIEW_PROFIT ? ' auto' : ''};
                gap:14px;padding:10px 16px;align-items:center;
                background:var(--brand-xlight);border-top:2px solid var(--brand-light)">
      <div style="font-size:11px;color:var(--text2)">
        ${items.length} item(s)
        ${parseFloat(s.discount_pct||0) > 0
          ? `· Invoice disc: ${parseFloat(s.discount_pct).toFixed(1)}%` : ''}
        ${s.notes ? `· ${esc(s.notes)}` : ''}
      </div>
      <div style="text-align:right">
        <div style="font-size:9px;color:var(--text3)">TOTAL</div>
        <div class="mono" style="font-weight:800;font-size:15px;color:var(--brand)">
          ${CUR}${total.toFixed(2)}
        </div>
      </div>
      <div style="text-align:right">
        <div style="font-size:9px;color:var(--accent)">PAID</div>
        <div class="mono" style="font-weight:700;color:var(--accent)">
          ${CUR}${paid.toFixed(2)}
        </div>
      </div>
      <div style="text-align:right">
        <div style="font-size:9px;color:${due>0?'var(--danger)':'var(--accent)'}">DUE</div>
        <div class="mono" style="font-weight:700;color:${due>0?'var(--danger)':'var(--accent)'}">
          ${CUR}${due.toFixed(2)}
        </div>
      </div>
      ${CAN_VIEW_PROFIT ? `<div style="text-align:right">
        <div style="font-size:9px;color:var(--teal)">PROFIT</div>
        <div class="mono" style="font-weight:700;color:var(--teal)">
          ${CUR}${profit.toFixed(2)}
        </div>
      </div>` : ''}
    </div>

    <div style="padding:10px 14px;display:flex;gap:8px;justify-content:flex-end">
      ${due > 0
        ? `<button class="btn btn-sm"
                   style="background:#fff3dc;color:var(--warn);border-color:#f5c842"
                   onclick="closeModal();openPayDue(${s.id},'${esc(s.invoice)}',${due})">
             💰 Collect Due</button>` : ''}
      <button class="btn btn-sm"
              style="background:#fde8e8;color:var(--danger);border-color:#f5a0a0"
              onclick="closeModal();window.location.href='return.php?invoice=${encodeURIComponent(s.invoice)}'">
        ↩ Return
      </button>
      <button class="btn btn-sm btn-teal"
              onclick="printInvoice(${s.id})">🖨 Print</button>
      <button class="btn" onclick="closeModal()">Close</button>
    </div>`;
}

// ── Pay Due modal ─────────────────────────────────────────────
function openPayDue(id, invoice, due) {
  showModal(`
  <div style="margin-bottom:12px">
    <div style="font-size:11px;color:var(--text2);margin-bottom:3px">Invoice</div>
    <div class="mono" style="font-weight:700;font-size:14px;color:var(--brand)">
      ${esc(invoice)}
    </div>
    <div style="margin-top:8px;padding:8px 12px;
                background:#fde8e8;border-radius:var(--rsm)">
      <span style="font-size:12px;color:var(--danger)">Outstanding Due: </span>
      <strong style="color:var(--danger)">${CUR}${parseFloat(due).toFixed(2)}</strong>
    </div>
  </div>
  <div style="display:flex;flex-direction:column;gap:9px">
    <div class="fg">
      <label>Collecting Amount *</label>
      <input id="pd-amount" type="number" step="0.01"
             min="0.01" max="${due}"
             value="${parseFloat(due).toFixed(2)}">
    </div>
    <div class="fg">
      <label>Account *</label>
      <select id="pd-account">
        <option>Cash</option><option>Bank</option>
        <option>MFS</option><option>Card</option>
      </select>
    </div>
    <div id="pd-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="doPayDue(${id},${due})">
      💰 Confirm Collection
    </button>
  </div>`, `💰 Collect Due — ${esc(invoice)}`);

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

async function doPayDue(id, maxDue) {
  const amount  = parseFloat(document.getElementById('pd-amount').value)  || 0;
  const account = document.getElementById('pd-account').value;
  const errEl   = document.getElementById('pd-err');

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

  const r = await apiPost(API, { action: 'pay_due', id, amount, account });
  if (r.success) { closeModal(); load(); }
  else {
    errEl.textContent = '⚠ ' + (r.error || 'Failed.');
    errEl.style.display = 'block';
  }
}

// ── Print Invoice ─────────────────────────────────────────────
function printInvoice(id) {
  window.open(`../sale/print.php?id=${id}`, '_blank',
    'width=820,height=700,scrollbars=yes');
}

// ── Delete ────────────────────────────────────────────────────
async function delSale(id, invoice) {
  if (!confirm(
    `Delete invoice "${invoice}"?\n\n` +
    `⚠ This will:\n• Remove the sale record\n` +
    `• Restore stock for all items\n` +
    `• Reduce customer due\n\nCannot be undone.`
  )) return;
  const r = await apiPost(API, { action: 'delete', id });
  if (r.success) load();
  else alert('⚠ ' + (r.error || 'Delete failed.'));
}

// ── Search & filters ──────────────────────────────────────────
document.addEventListener('DOMContentLoaded', () => {
  load();
  document.getElementById('srch').addEventListener('input', () => {
    clearTimeout(timer); timer = setTimeout(load, 300);
  });
  document.getElementById('f-from').addEventListener('change', load);
  document.getElementById('f-to').addEventListener('change',   load);
});

function exportCSV() {
  window.open('../api/sales.php?action=export_csv', '_blank');
}
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'; ?>
