<?php
// ============================================================
//  MediCore — Customer Portal: My Orders (history / detail / reorder)
//  File: shop/orders.php
// ============================================================
require_once '../includes/customer_auth.php';
require_customer_login();

$shopPage = 'orders';
$title    = 'My Orders';
require_once '../includes/shop_header.php';

$cur = get_settings()['currency'];
?>
<h2 style="font-size:16px;margin-bottom:14px">📦 My Orders</h2>

<div id="orders-list">
  <div class="empty-state loading-row"><span class="spin"></span>Loading…</div>
</div>

<script>
const CUR      = '<?= addslashes($cur) ?>';
const API_SHOP = '<?= base_url("api/customer-shop.php") ?>';

const STATUS_META = {
  pending:   { bg: '#fff4d6', cl: '#8a6d00', tx: '⏳ Pending Review' },
  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' },
};

async function loadOrders() {
  const list = document.getElementById('orders-list');
  const r = await apiPost(API_SHOP, { action: 'my_orders' });

  if (!r.success) {
    if (r.session_expired) { window.location.href = '<?= base_url("shop/login.php") ?>'; return; }
    list.innerHTML = `<div class="empty-state" style="color:var(--danger)">⚠ ${esc(r.error || 'Failed to load orders.')}</div>`;
    return;
  }
  if (!r.data.length) {
    list.innerHTML = `<div class="empty-state">
      📭 No orders yet. <a href="<?= base_url('shop/index.php') ?>" style="color:var(--brand);font-weight:700">Start shopping →</a>
    </div>`;
    return;
  }

  list.innerHTML = r.data.map(o => {
    const meta = STATUS_META[o.status] || STATUS_META.pending;
    return `<div class="card" style="padding:14px;margin-bottom:10px;cursor:pointer" onclick="viewOrder(${o.id})">
      <div style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px">
        <div>
          <span class="mono" style="font-weight:700;color:var(--brand)">${esc(o.order_no)}</span>
          <span style="font-size:11px;color:var(--text3);margin-left:8px">${o.created_at}</span>
        </div>
        <span class="badge" style="background:${meta.bg};color:${meta.cl};font-weight:700">${meta.tx}</span>
      </div>
      <div style="display:flex;justify-content:space-between;align-items:center;margin-top:8px">
        <span style="font-size:11.5px;color:var(--text2)">${o.item_count} item(s)</span>
        <span class="mono" style="font-weight:800;font-size:14px;color:var(--brand)">${CUR}${parseFloat(o.total).toFixed(2)}</span>
      </div>
      ${o.status === 'rejected' && o.rejection_reason
        ? `<div style="font-size:11px;color:var(--danger);margin-top:6px">Reason: ${esc(o.rejection_reason)}</div>`
        : ''}
    </div>`;
  }).join('');
}

async function viewOrder(id) {
  showModal('<div style="text-align:center;padding:20px;color:var(--text3)">⏳ Loading…</div>', '📦 Order Detail', 'lg');

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

  const o     = r.data;
  const items = r.items || [];
  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>${formIconName(it.form, it.product_name)}</td>
    <td class="mono" style="text-align:center">${it.qty}</td>
    <td class="mono" style="text-align:right">${CUR}${parseFloat(it.price).toFixed(2)}</td>
    <td class="mono" style="text-align:right;font-weight:700">${CUR}${parseFloat(it.total).toFixed(2)}</td>
  </tr>`).join('');

  document.querySelector('.mbox').innerHTML = `
    <div class="mtitle">
      📦 <span class="mono" style="color:var(--brand)">${esc(o.order_no)}</span>
      <button class="mclose" onclick="closeModal()">×</button>
    </div>
    <div style="padding:10px 14px;display:flex;justify-content:space-between;align-items:center;
                border-bottom:1px solid var(--border)">
      <span style="font-size:11.5px;color:var(--text3)">${o.created_at}</span>
      <span class="badge" style="background:${meta.bg};color:${meta.cl};font-weight:700">${meta.tx}</span>
    </div>
    ${o.delivery_address ? `<div style="padding:8px 14px;font-size:11.5px;color:var(--text2)">📍 ${esc(o.delivery_address)}</div>` : ''}
    <div class="tw" style="max-height:280px;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}${parseFloat(o.total).toFixed(2)}</div>
      </div>
    </div>
    ${o.rejection_reason ? `<div style="padding:10px 14px;color:var(--danger);font-size:12px">Reason: ${esc(o.rejection_reason)}</div>` : ''}
    <div style="padding:10px 14px;display:flex;gap:8px;justify-content:flex-end">
      <button class="btn btn-sm btn-primary" onclick='reorder(${JSON.stringify(items).replace(/'/g,"&apos;")})'>🔁 Reorder</button>
      <button class="btn" onclick="closeModal()">Close</button>
    </div>`;
}

function reorder(items) {
  const cart = getCart();
  items.forEach(it => {
    const id = String(it.product_id);
    if (cart[id]) cart[id].qty += it.qty;
    else cart[id] = { name: it.product_name, form: it.form || '', price: parseFloat(it.price) || 0, qty: it.qty };
  });
  setCart(cart);
  closeModal();
  window.location.href = window.SHOP_BASE + 'shop/index.php';
}

document.addEventListener('DOMContentLoaded', loadOrders);
</script>

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