<?php
// ============================================================
//  MediCore — Purchase Order Approvals
//  File: purchase/approvals.php
//  Review queue for POs held pending sign-off (see includes/po_approval.php
//  and api/purchases.php's api_approve()/api_reject()). Approve/Reject are
//  restricted to Admin + Manager (can_approve_po()); everyone with access
//  to Purchase Record can view the queue read-only.
// ============================================================
$page  = 'purchase/approvals';
$title = 'PO Approvals';
require_once '../includes/header.php';
require_once '../includes/po_approval.php';

ensure_soft_delete('purchases');
ensure_po_approval_columns();

$cfg    = $settings;
$cur    = $cfg['currency'];
$canAct = can_approve_po();

$pendingCount = (int) db_val(
    "SELECT COUNT(*) FROM purchases WHERE is_deleted = 0 AND approval_status = 'pending'"
);
?>

<!-- ── Page actions ───────────────────────────────── -->
<script>
document.getElementById('ph-actions').innerHTML = `
  <select id="f-status"
    style="padding:5px 10px;border:1px solid var(--border);
           border-radius:var(--rsm);font-family:inherit;
           font-size:12px;outline:none">
    <option value="pending">Pending Approval</option>
    <option value="approved">Approved</option>
    <option value="rejected">Rejected</option>
    <option value="">All</option>
  </select>
  <a class="btn btn-sm" href="list.php">📥 Purchase Record</a>`;
</script>

<?php if (!po_approval_enabled()): ?>
<div class="flash-error" style="background:#fff4d6;border-color:#e8b93a;color:#8a6d00">
  ⚠ The Purchase Order Approval workflow is currently <strong>disabled</strong> in Settings.
  Newly saved POs will take effect immediately. This page still shows any orders
  that were submitted while the workflow was on.
</div>
<?php endif; ?>

<!-- ── 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 #e8b93a">
    <div class="slabel">Awaiting Approval</div>
    <div class="sval b" id="sum-pending"><?= $pendingCount ?></div>
  </div>
  <div class="sc" style="border-top:3px solid var(--accent)">
    <div class="slabel">Approval Threshold</div>
    <div class="sval b"><?= $cur . number_format(po_approval_threshold(), 2) ?></div>
  </div>
  <div class="sc" style="border-top:3px solid var(--brand)">
    <div class="slabel">Your Role</div>
    <div class="sval b" style="font-size:14px">
      <?= $canAct ? '✅ Can Approve / Reject' : '👁 View Only' ?>
    </div>
  </div>
</div>

<!-- ── Table ──────────────────────────────────────── -->
<div class="card" style="padding:0">
  <div class="tw">
    <table id="ap-table">
      <thead>
        <tr>
          <th style="width:38px">#</th>
          <th>PO #</th>
          <th>Supplier</th>
          <th>Date</th>
          <th style="text-align:right">Amount</th>
          <th>Submitted By</th>
          <th>Status</th>
          <th style="text-align:center;width:190px">Actions</th>
        </tr>
      </thead>
      <tbody id="ap-body">
        <tr><td colspan="8" class="empty-state loading-row"><span class="spin"></span>Loading…</td></tr>
      </tbody>
    </table>
  </div>
  <div id="ap-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 CAN_ACT  = <?= $canAct ? 'true' : 'false' ?>;

const STATUS_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: 'Not Required' },
};

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

  const status = document.getElementById('f-status').value;
  const r = await apiPost(API, { action: 'list', approval_status: status });

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

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

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

  const total = rows.reduce((s,r) => s + parseFloat(r.final_price||0), 0);
  footer.innerHTML =
    `<strong>${rows.length}</strong> purchase order(s) &nbsp;·&nbsp;
     Total value: <strong>${CUR}${total.toFixed(2)}</strong>`;

  tbody.innerHTML = rows.map((p, i) => {
    const meta = STATUS_META[p.approval_status] || STATUS_META.not_required;
    const isPending = p.approval_status === 'pending';

    let actions = `<button class="btn btn-sm btn-teal" onclick="viewDetail(${p.id})">🔍 View</button>`;
    if (isPending && CAN_ACT) {
      actions += `
        <button class="btn btn-sm" style="background:#d4f0e6;color:var(--accent);border-color:#8fd9bb"
                onclick="approvePO(${p.id},'${esc(p.invoice).replace(/'/g,"\\'")}')">✔ Approve</button>
        <button class="btn btn-sm" style="background:#fde8e8;color:var(--danger);border-color:#f5a0a0"
                onclick="rejectPO(${p.id},'${esc(p.invoice).replace(/'/g,"\\'")}')">✘ Reject</button>`;
    }

    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 class="mono" style="text-align:right;font-weight:700">
        ${CUR}${parseFloat(p.final_price||0).toFixed(2)}
      </td>
      <td>${esc(p.submitted_by_name || '—')}</td>
      <td>
        <span class="badge" style="background:${meta.bg};color:${meta.cl}">${meta.tx}</span>
        ${p.approval_status === 'rejected' && p.rejection_reason
          ? `<div style="font-size:10px;color:var(--text3);margin-top:2px">${esc(p.rejection_reason)}</div>`
          : ''}
      </td>
      <td style="text-align:center;white-space:nowrap">${actions}</td>
    </tr>`;
  }).join('');
}

// ── Approve ───────────────────────────────────────────────────
async function approvePO(id, invoice) {
  if (!confirm(`Approve PO "${invoice}"?\n\nThis will add its items to stock and post any due/paid amounts to the supplier balance and cash ledger.`)) return;
  const r = await apiPost(API, { action: 'approve', id });
  if (r.success) { load(); refreshBadge(); }
  else alert('⚠ ' + (r.error || 'Approval failed.'));
}

// ── Reject ────────────────────────────────────────────────────
function rejectPO(id, invoice) {
  showModal(`
    <div style="padding:16px">
      <label style="font-size:11px;color:var(--text3);display:block;margin-bottom:6px">
        Reason for rejection (required)
      </label>
      <textarea id="reject-reason" rows="3" placeholder="e.g. Wrong pricing, duplicate order…"
        style="width:100%;padding:8px;border:1px solid var(--border);border-radius:var(--rsm);
               font-family:inherit;font-size:12px;outline:none;resize:vertical"></textarea>
      <div style="display:flex;gap:8px;justify-content:flex-end;margin-top:14px">
        <button class="btn btn-sm" onclick="closeModal()">Cancel</button>
        <button class="btn btn-sm btn-danger" onclick="confirmReject(${id})">✘ Reject Order</button>
      </div>
    </div>`, `✘ Reject PO <span class="mono" style="color:var(--danger)">${esc(invoice)}</span>`, 'sm');
}

async function confirmReject(id) {
  const reason = document.getElementById('reject-reason').value.trim();
  if (!reason) { alert('Please provide a reason for rejection.'); return; }
  const r = await apiPost(API, { action: 'reject', id, reason });
  if (r.success) { closeModal(); load(); refreshBadge(); }
  else alert('⚠ ' + (r.error || 'Rejection failed.'));
}

// ── 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 total = parseFloat(p.final_price || 0);
  const meta  = STATUS_META[p.approval_status] || STATUS_META.not_required;

  const itemRows = items.map((it, i) => `<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.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_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>
    <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)">Submitted By</div>
        <div>${esc(p.submitted_by_name || '—')}</div>
      </div>
      <div>
        <div style="font-size:10px;color:var(--text3)">Status</div>
        <div><span class="badge" style="background:${meta.bg};color:${meta.cl}">${meta.tx}</span></div>
      </div>
      ${p.approved_by_name ? `
      <div>
        <div style="font-size:10px;color:var(--text3)">${p.approval_status === 'rejected' ? 'Rejected' : 'Approved'} By</div>
        <div>${esc(p.approved_by_name)}</div>
      </div>
      <div>
        <div style="font-size:10px;color:var(--text3)">${p.approval_status === 'rejected' ? 'Rejected' : 'Approved'} At</div>
        <div>${esc(p.approved_at || '—')}</div>
      </div>` : ''}
      ${p.rejection_reason ? `
      <div style="grid-column:1 / -1">
        <div style="font-size:10px;color:var(--text3)">Rejection Reason</div>
        <div style="color:var(--danger)">${esc(p.rejection_reason)}</div>
      </div>` : ''}
    </div>
    <div class="tw" style="max-height:300px;overflow-y:auto">
      <table>
        <thead><tr>
          <th>#</th><th>Product</th>
          <th style="text-align:center">Boxes</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>
    <div style="display:grid;grid-template-columns:1fr 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)</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>
    <div style="padding:10px 14px;display:flex;gap:8px;justify-content:flex-end">
      ${p.approval_status === 'pending' && CAN_ACT ? `
        <button class="btn btn-sm" style="background:#fde8e8;color:var(--danger);border-color:#f5a0a0"
                onclick="closeModal();rejectPO(${p.id},'${esc(p.invoice).replace(/'/g,"\\'")}')">✘ Reject</button>
        <button class="btn btn-sm" style="background:#d4f0e6;color:var(--accent);border-color:#8fd9bb"
                onclick="approvePO(${p.id},'${esc(p.invoice).replace(/'/g,"\\'")}');closeModal();">✔ Approve</button>
      ` : ''}
      <button class="btn" onclick="closeModal()">Close</button>
    </div>`;
}

// ── Refresh the sidebar nav badge after an approve/reject ──────
function refreshBadge() {
  const badge = document.getElementById('po-approval-badge');
  if (!badge) return;
  apiPost(API, { action: 'list', approval_status: 'pending' }).then(r => {
    if (!r.success) return;
    const n = r.data.length;
    document.getElementById('sum-pending').textContent = n;
    if (n > 0) { badge.textContent = n; badge.style.display = ''; }
    else badge.style.display = 'none';
  });
}

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

document.addEventListener('DOMContentLoaded', () => {
  load();
  document.getElementById('f-status').addEventListener('change', load);
});
</script>

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