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

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

// Guarantee is_deleted/deleted_at/deleted_by exist before querying them —
// this page reads them directly for the summary cards below, ahead of
// any call into api/purchases.php (which also calls this, but too late
// for these queries).
ensure_soft_delete('purchases');

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

// Summary totals
$totalPOs   = (int)   db_val("SELECT COUNT(*)                    FROM purchases WHERE is_deleted = 0");
$totalValue = (float) db_val("SELECT COALESCE(SUM(final_price),0) FROM purchases WHERE is_deleted = 0");
$totalPaid  = (float) db_val("SELECT COALESCE(SUM(paid),0)        FROM purchases WHERE is_deleted = 0");
$totalDue   = (float) db_val("SELECT COALESCE(SUM(due),0)         FROM purchases WHERE is_deleted = 0");
?>

<!-- ── Page actions ───────────────────────────────── -->
<script>
document.getElementById('ph-actions').innerHTML = `
  <input type="text" id="srch"
         placeholder="🔍  PO # or supplier…"
    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-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>
  <a class="btn btn-sm" href="approvals.php">🧾 PO Approvals</a>
  <button class="btn btn-sm" onclick="exportCSV()">📤 Export CSV</button>
  <a class="btn btn-primary btn-sm" href="entry.php">📦 New Purchase</a>`;
</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 Purchase Orders</div>
    <div class="sval b"><?= $totalPOs ?></div>
  </div>
  <div class="sc" style="border-top:3px solid var(--text2)">
    <div class="slabel">Total Purchase Value</div>
    <div class="sval b"><?= $cur . number_format($totalValue, 2) ?></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>
  <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>
</div>

<!-- ── Table ──────────────────────────────────────── -->
<div class="card" style="padding:0">
  <div class="tw">
    <table id="po-table">
      <thead>
        <tr>
          <th style="width:38px">#</th>
          <th>PO #</th>
          <th>Supplier</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>
          <th style="text-align:center">Status</th>
          <th style="text-align:center">Approval</th>
          <th>Staff</th>
          <th style="text-align:center;width:150px">Actions</th>
        </tr>
      </thead>
      <tbody id="po-body">
        <tr><td colspan="12" class="empty-state loading-row"><span class="spin"></span>Loading…</td></tr>
      </tbody>
    </table>
  </div>
  <div id="po-footer"
       style="padding:8px 14px;font-size:11px;color:var(--text3);
              border-top:1px solid var(--border)"></div>
</div>

<script>
const API      = '../api/purchases.php';
const CUR      = '<?= addslashes($cur) ?>';
const IS_ADMIN = <?= is_admin() ? 'true' : 'false' ?>;
let timer = null;

const APPROVAL_META = {
  pending:      { bg: '#fff4d6', cl: '#8a6d00', tx: '⏳ Pending' },
  approved:     { bg: '#d4f0e6', cl: 'var(--accent)', tx: '✅ Approved' },
  rejected:     { bg: '#fde8e8', cl: 'var(--danger)', tx: '⛔ Rejected' },
  not_required: { bg: 'var(--surface2)', cl: 'var(--text2)', tx: '—' },
};

// ── Load ──────────────────────────────────────────────────────
async function load() {
  const tbody = document.getElementById('po-body');
  tbody.innerHTML =
    '<tr><td colspan="12" 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        || '',
    submitted_by: document.getElementById('f-staff')?.value     || '',
  });

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

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

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

  const fVal  = 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);
  footer.innerHTML =
    `<strong>${rows.length}</strong> purchase order(s) &nbsp;·&nbsp;
     Value: <strong>${CUR}${fVal.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>`;

  tbody.innerHTML = rows.map((p, i) => {
    const due  = parseFloat(p.due  || 0);
    const paid = parseFloat(p.paid || 0);
    const isPaid = due <= 0.001;

    const stBg = isPaid ? '#d4f0e6' : '#fde8e8';
    const stCl = isPaid ? 'var(--accent)' : 'var(--danger)';
    const stTx = isPaid ? 'Paid' : 'Due';

    const aMeta = APPROVAL_META[p.approval_status] || APPROVAL_META.not_required;

    return `<tr data-id="${p.id}">
      <td style="color:var(--text3)">${i + 1}</td>
      <td>
        <span class="mono"
              style="font-weight:700;color:var(--brand);cursor:pointer"
              onclick="viewDetail(${p.id})"
              title="Click to view detail">
          ${esc(p.invoice)}
        </span>
      </td>
      <td style="font-weight:500">${esc(p.supplier_name || '—')}</td>
      <td style="color:var(--text2)">${p.date || '—'}</td>
      <td style="text-align:center">
        <span class="badge" style="background:var(--surface2);color:var(--text2)">
          ${p.item_count}
        </span>
      </td>
      <td class="mono" style="text-align:right;font-weight:700">
        ${CUR}${parseFloat(p.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>
      <td style="text-align:center">
        <span class="badge" style="background:${stBg};color:${stCl}">${stTx}</span>
      </td>
      <td style="text-align:center">
        ${p.approval_status && p.approval_status !== 'not_required'
          ? `<span class="badge" style="background:${aMeta.bg};color:${aMeta.cl};cursor:${p.approval_status==='pending'?'pointer':'default'}"
                   ${p.approval_status==='pending' ? `onclick="window.location.href='approvals.php'"` : ''}>${aMeta.tx}</span>`
          : `<span style="color:var(--text3)">—</span>`}
      </td>
      <td style="font-size:11px;color:var(--text2)">${esc(p.submitted_by_name || '—')}</td>
      <td style="text-align:center;white-space:nowrap">
        <button class="btn btn-sm btn-teal"
                onclick="viewDetail(${p.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(p.invoice)}'">
          ↩ Return
        </button>
        ${IS_ADMIN
          ? `<button class="btn btn-sm btn-danger"
                     onclick="delPurchase(${p.id},'${esc(p.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>`,
    '📦 Purchase Order 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 p     = r.data;
  const items = r.items || [];
  const due   = parseFloat(p.due  || 0);
  const paid  = parseFloat(p.paid || 0);
  const total = parseFloat(p.final_price || 0);
  const isPaid = due <= 0.001;
  const stCl = isPaid ? 'var(--accent)' : 'var(--danger)';
  const stTx = isPaid ? 'Paid' : 'Due';

  const itemRows = items.map((it, i) => {
    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.rack ? 'Rack: '+esc(it.rack) : ''}
          ${it.barcode ? ' · '+esc(it.barcode) : ''}
          ${it.exp ? ' · Exp: '+esc(it.exp) : ''}
        </div>
      </td>
      <td class="mono" style="text-align:center">${it.boxes}</td>
      <td class="mono" style="text-align:center">${it.qty_in_box}</td>
      <td class="mono" style="text-align:center">${it.qty_pcs}</td>
      <td class="mono" style="text-align:center;color:var(--text2)">${it.free || 0}</td>
      <td class="mono" style="text-align:right">${CUR}${parseFloat(it.btp_vat||0).toFixed(2)}</td>
      <td class="mono" style="text-align:right;font-weight:700">
        ${CUR}${parseFloat(it.total_price||0).toFixed(2)}
      </td>
    </tr>`;
  }).join('');

  document.querySelector('.mbox').innerHTML = `
    <div class="mtitle">
      📦 PO:
      <span class="mono" style="color:var(--brand)">${esc(p.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)">Supplier</div>
        <div style="font-weight:700">${esc(p.supplier_name||'—')}</div>
      </div>
      <div>
        <div style="font-size:10px;color:var(--text3)">Date</div>
        <div style="font-weight:600">${p.date}</div>
      </div>
      <div>
        <div style="font-size:10px;color:var(--text3)">Supplier Inv. #</div>
        <div>${esc(p.inv_no || '—')}</div>
      </div>
      <div>
        <div style="font-size:10px;color:var(--text3)">Status</div>
        <div style="font-weight:700;color:${stCl}">${stTx}</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">Boxes</th>
          <th style="text-align:center">Qty/Box</th>
          <th style="text-align:center">Pcs</th>
          <th style="text-align:center">Free</th>
          <th style="text-align:right">TP+VAT/Box</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;
                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(p.discount_pct||0) > 0
          ? `· PO disc: ${parseFloat(p.discount_pct).toFixed(1)}%` : ''}
        ${p.notes ? `· ${esc(p.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>
    </div>

    <div style="padding:10px 14px;display:flex;gap:8px;justify-content:flex-end">
      <button class="btn btn-sm"
              style="background:#fde8e8;color:var(--danger);border-color:#f5a0a0"
              onclick="closeModal();window.location.href='return.php?invoice=${encodeURIComponent(p.invoice)}'">
        ↩ Return
      </button>
      <button class="btn btn-sm btn-teal"
              onclick="printPO(${p.id})">🖨 Print</button>
      <button class="btn" onclick="closeModal()">Close</button>
    </div>`;
}

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

// ── Delete ────────────────────────────────────────────────────
async function delPurchase(id, invoice) {
  if (!confirm(
    `Delete PO "${invoice}"?\n\n` +
    `⚠ This will:\n• Remove the purchase record\n` +
    `• Reverse stock added by this PO (if it was approved/applied)\n` +
    `• Reduce supplier balance\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/purchases.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'; ?>
