<?php
// ============================================================
//  MediCore — Online Orders (Approval Queue)
//  File: sale/online-orders.php
//  Review queue for orders placed through the customer web portal
//  (see includes/customer_portal.php, api/customer-shop.php, and
//  api/online-orders.php's api_approve()/api_reject()). Approve
//  only flips the order's status — staff are then routed into
//  Sale Entry (sale/entry.php?online_order=<id>) with the order's
//  items pre-filled, where discounts/quantities can be adjusted
//  before it's saved as a real sale. Mirrors purchase/approvals.php's
//  UI pattern for the queue/table itself.
// ============================================================
$page  = 'sale/online-orders';
$title = 'Online Orders';
require_once '../includes/header.php';

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

$pendingCount = (int) db_val("SELECT COUNT(*) FROM online_orders WHERE status = 'pending'");
?>

<!-- ── Page actions ───────────────────────────────── -->
<script>
document.getElementById('ph-actions').innerHTML = `
  <select id="f-status" onchange="load()"
    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 Review</option>
    <option value="approved">Approved</option>
    <option value="rejected">Rejected</option>
    <option value="">All</option>
  </select>
  <a class="btn btn-sm" href="<?= base_url('settings.php') ?>">⚙️ Portal Settings</a>`;
</script>

<?php if (!portal_enabled()): ?>
<div class="flash-error" style="background:#fff4d6;border-color:#e8b93a;color:#8a6d00">
  ⚠ The customer web-ordering portal is currently <strong>disabled</strong> in Settings.
  Customers cannot place new orders, but any orders already submitted still show here.
</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 Review</div>
    <div class="sval b" id="sum-pending"><?= $pendingCount ?></div>
  </div>
  <div class="sc" style="border-top:3px solid var(--accent)">
    <div class="slabel">Portal Status</div>
    <div class="sval b" style="font-size:14px">
      <?= portal_enabled() ? '🟢 Online' : '⚪ Offline' ?>
    </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="oo-table">
      <thead>
        <tr>
          <th style="width:38px">#</th>
          <th>Order #</th>
          <th>Customer</th>
          <th>Date</th>
          <th style="text-align:right">Amount</th>
          <th>Status</th>
          <th style="text-align:center;width:190px">Actions</th>
        </tr>
      </thead>
      <tbody id="oo-body">
        <tr><td colspan="7" class="empty-state loading-row"><span class="spin"></span>Loading…</td></tr>
      </tbody>
    </table>
  </div>
  <div id="oo-footer"
       style="padding:8px 14px;font-size:11px;color:var(--text3);
              border-top:1px solid var(--border)"></div>
</div>

<script>
const API      = '../api/online-orders.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' },
  cancelled: { bg: 'var(--surface2)', cl: 'var(--text2)', tx: 'Cancelled' },
};

// ── Load ──────────────────────────────────────────────────────
async function load() {
  const tbody = document.getElementById('oo-body');
  tbody.innerHTML =
    '<tr><td colspan="7" 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', status });

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

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

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

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

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

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

    return `<tr data-id="${o.id}">
      <td style="color:var(--text3)">${i + 1}</td>
      <td>
        <span class="mono" style="font-weight:700;color:var(--brand);cursor:pointer"
              onclick="viewDetail(${o.id})" title="Click to view detail">
          ${esc(o.order_no)}
        </span>
      </td>
      <td style="font-weight:500">${esc(o.customer_name || '—')}
        <div style="font-size:10px;color:var(--text3)">${esc(o.customer_phone || '')}</div>
      </td>
      <td style="color:var(--text2)">${o.created_at || '—'}</td>
      <td class="mono" style="text-align:right;font-weight:700">
        ${CUR}${parseFloat(o.total||0).toFixed(2)}
      </td>
      <td>
        <span class="badge" style="background:${meta.bg};color:${meta.cl}">${meta.tx}</span>
        ${o.status === 'rejected' && o.rejection_reason
          ? `<div style="font-size:10px;color:var(--text3);margin-top:2px">${esc(o.rejection_reason)}</div>`
          : ''}
      </td>
      <td style="text-align:center;white-space:nowrap">${actions}</td>
    </tr>`;
  }).join('');
}

// ── Approve → mark approved, then hand off to Sale Entry so staff
//    can apply discounts / adjust quantities before it becomes a
//    real sale. Nothing is deducted or posted to the ledger here.
async function approveOrder(id, orderNo) {
  if (!confirm(`Approve order "${orderNo}"?\n\nYou'll be taken to Sale Entry to finish it — apply discounts or adjust quantities before saving as a sale.`)) return;
  const r = await apiPost(API, { action: 'approve', id });
  if (r.success) {
    window.location.href = '../sale/entry.php?online_order=' + id;
  } else {
    alert('⚠ ' + (r.error || 'Approval failed.'));
  }
}

// ── Reject ────────────────────────────────────────────────────
function rejectOrder(id, orderNo) {
  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. Out of stock, unable to fulfil…"
        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 Order <span class="mono" style="color:var(--danger)">${esc(orderNo)}</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>`,
    '📦 Online 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 o     = r.data;
  const items = r.items || [];
  const total = parseFloat(o.total || 0);
  const meta  = STATUS_META[o.status] || STATUS_META.pending;

  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>
      </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:right;font-weight:700">${CUR}${parseFloat(it.total||0).toFixed(2)}</td>
    </tr>`).join('');

  document.querySelector('.mbox').innerHTML = `
    <div class="mtitle">
      📦 Order: <span class="mono" style="color:var(--brand)">${esc(o.order_no)}</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)">Customer</div>
        <div style="font-weight:700">${esc(o.customer_name||'—')}</div>
      </div>
      <div>
        <div style="font-size:10px;color:var(--text3)">Phone</div>
        <div style="font-weight:600">${esc(o.customer_phone||'—')}</div>
      </div>
      <div>
        <div style="font-size:10px;color:var(--text3)">Date</div>
        <div>${o.created_at}</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>
      ${o.delivery_address ? `
      <div style="grid-column:1 / -1">
        <div style="font-size:10px;color:var(--text3)">Delivery / Pickup Address</div>
        <div>${esc(o.delivery_address)}</div>
      </div>` : ''}
      ${o.notes ? `
      <div style="grid-column:1 / -1">
        <div style="font-size:10px;color:var(--text3)">Notes</div>
        <div>${esc(o.notes)}</div>
      </div>` : ''}
      ${o.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(o.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">Qty</th>
          <th style="text-align:right">Price</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">
      ${o.status === 'pending' && CAN_ACT ? `
        <button class="btn btn-sm" style="background:#fde8e8;color:var(--danger);border-color:#f5a0a0"
                onclick="closeModal();rejectOrder(${o.id},'${esc(o.order_no).replace(/'/g,"\\'")}')">✘ Reject</button>
        <button class="btn btn-sm" style="background:#d4f0e6;color:var(--accent);border-color:#8fd9bb"
                onclick="approveOrder(${o.id},'${esc(o.order_no).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('online-order-badge');
  if (!badge) return;
  apiPost(API, { action: 'list', 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'; ?>
