<?php
require_once __DIR__ . '/auth_guard.php';
require_once __DIR__ . '/../backend/config/database.php';
require_once __DIR__ . '/../backend/includes/order_stock.php';

$db = getDB();
$adminUserName = $_SESSION['user_name'];
$adminPage     = 'orders';
$adminPageTitle= 'Manage Orders';

// AJAX status update (called by JS fetch)
if($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['ajax_update_status'])){
    header('Content-Type: application/json');
    $orderId   = $_POST['order_id'] ?? '';
    $newStatus = $_POST['status'] ?? '';
    $allowed = ['pending','confirmed','out_for_delivery','delivered','cancelled'];
    if($orderId && in_array($newStatus, $allowed)){
      $ok = transitionOrderStatusWithStock($db, $orderId, $newStatus);
      echo json_encode(['ok'=>$ok]);
    } else {
        echo json_encode(['ok'=>false]);
    }
    exit;
}

// Filter
$filter = $_GET['status'] ?? 'all';
$search = trim($_GET['q'] ?? '');

if($filter !== 'all'){
    $stmt = $db->prepare("SELECT o.*,u.name AS customer,u.phone AS cust_phone,u.email AS cust_email FROM orders o LEFT JOIN users u ON o.user_id=u.id WHERE o.status=? ORDER BY o.created_at DESC");
    $stmt->execute([$filter]);
} else {
    $stmt = $db->query("SELECT o.*,u.name AS customer,u.phone AS cust_phone,u.email AS cust_email FROM orders o LEFT JOIN users u ON o.user_id=u.id ORDER BY o.created_at DESC");
}
$orders = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch order items for all orders
$orderIds = array_column($orders, 'id');
$itemsMap = [];
if($orderIds){
    $placeholders = implode(',', array_fill(0, count($orderIds), '?'));
    $istmt = $db->prepare("SELECT order_id, product_name, quantity, price FROM order_items WHERE order_id IN ($placeholders)");
    $istmt->execute($orderIds);
    foreach($istmt->fetchAll(PDO::FETCH_ASSOC) as $item){
        $itemsMap[$item['order_id']][] = $item;
    }
}

$statuses = ['all','pending','confirmed','out_for_delivery','delivered','cancelled'];
function statusStyle($s){
    $map=['pending'=>['bg'=>'#fef3c7','color'=>'#d97706','border'=>'#fde68a'],'confirmed'=>['bg'=>'#dbeafe','color'=>'#2563eb','border'=>'#bfdbfe'],'out_for_delivery'=>['bg'=>'#ede9fe','color'=>'#7c3aed','border'=>'#ddd6fe'],'delivered'=>['bg'=>'#d1fae5','color'=>'#059669','border'=>'#a7f3d0'],'cancelled'=>['bg'=>'#fee2e2','color'=>'#dc2626','border'=>'#fecaca']];
    return $map[$s]??['bg'=>'#f1f5f9','color'=>'#475569','border'=>'#e2e8f0'];
}
?>
<?php require_once __DIR__ . '/layout_top.php'; ?>

<!-- Toast notification -->
<div id="statusToast" style="display:none;position:fixed;bottom:2rem;right:2rem;z-index:9999;background:#0f172a;color:#fff;padding:.85rem 1.5rem;border-radius:14px;font-size:.875rem;font-weight:600;box-shadow:0 8px 32px rgba(0,0,0,.25);display:none;align-items:center;gap:.6rem">
  <svg width="16" height="16" fill="none" stroke="#22c55e" stroke-width="2.5" viewBox="0 0 24 24"><polyline stroke-linecap="round" stroke-linejoin="round" points="20 6 9 17 4 12"/></svg>
  <span id="toastMsg">Status updated</span>
</div>

<!-- Filter + Search -->
<div style="display:flex;flex-wrap:wrap;gap:1rem;align-items:center;margin-bottom:1.75rem">
  <div style="position:relative;flex:1;min-width:220px">
    <div style="position:absolute;left:13px;top:50%;transform:translateY(-50%);pointer-events:none">
      <svg width="16" height="16" fill="none" stroke="#94a3b8" stroke-width="2" viewBox="0 0 24 24"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
    </div>
    <input type="text" id="orderSearch" placeholder="Search customer, order ID or address…"
      value="<?= htmlspecialchars($search) ?>"
      style="font-family:inherit;font-size:.875rem;padding:.65rem 1rem .65rem 2.4rem;border:2px solid #e2e8f0;border-radius:12px;outline:none;width:100%;box-sizing:border-box;transition:border-color .2s"
      onfocus="this.style.borderColor='#f97316'" onblur="this.style.borderColor='#e2e8f0'"
      oninput="filterOrders(this.value)">
  </div>
  <div style="display:flex;flex-wrap:wrap;gap:.4rem">
    <?php foreach($statuses as $s): ?>
    <a href="/stile-lpg/admin/orders.php?status=<?= $s ?>" style="padding:.45rem .9rem;border-radius:50px;font-size:.78rem;font-weight:700;border:1.5px solid <?= $filter===$s?'transparent':'#e2e8f0' ?>;background:<?= $filter===$s?'linear-gradient(135deg,#0f172a,#1e293b)':'#fff' ?>;color:<?= $filter===$s?'#fff':'#475569' ?>;text-decoration:none;white-space:nowrap">
      <?= ucwords(str_replace('_',' ',$s)) ?>
    </a>
    <?php endforeach; ?>
  </div>
</div>

<!-- Orders Table -->
<div style="background:#fff;border-radius:20px;border:1px solid #e2e8f0;box-shadow:0 2px 12px rgba(0,0,0,.05);overflow:hidden">
  <?php if(empty($orders)): ?>
  <div style="text-align:center;padding:4rem;color:#94a3b8">
    <div style="width:72px;height:72px;border-radius:20px;background:#f1f5f9;display:flex;align-items:center;justify-content:center;margin:0 auto 1.25rem;opacity:.5">
      <svg width="36" height="36" fill="none" stroke="#94a3b8" stroke-width="1.5" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M21 16V8a2 2 0 00-1-1.73l-7-4a2 2 0 00-2 0l-7 4A2 2 0 003 8v8a2 2 0 001 1.73l7 4a2 2 0 002 0l7-4A2 2 0 0021 16z"/></svg>
    </div>
    <p style="margin:0;font-weight:600">No orders found.</p>
  </div>
  <?php else: ?>
  <div style="overflow-x:auto">
    <table style="width:100%;border-collapse:collapse">
      <thead>
        <tr style="background:#f8f9fb">
          <?php foreach(['Order ID','Customer','Contact','Items & Total','Address','Date','Status','Update Status'] as $h): ?>
          <th style="padding:.85rem 1.25rem;text-align:left;font-size:.72rem;font-weight:700;color:#94a3b8;text-transform:uppercase;letter-spacing:.06em;white-space:nowrap"><?= $h ?></th>
          <?php endforeach; ?>
        </tr>
      </thead>
      <tbody id="ordersTableBody">
        <?php foreach($orders as $o):
          $st = statusStyle($o['status']);
          $label = ucwords(str_replace('_',' ',$o['status']));
          $items = $itemsMap[$o['id']] ?? [];
          $itemCount = count($items);
          $itemQty = 0;
          foreach($items as $it){ $itemQty += (int)($it['quantity'] ?? 0); }
          $itemSummaryParts = [];
          foreach(array_slice($items, 0, 2) as $it){
            $itemSummaryParts[] = ($it['product_name'] ?? 'Item') . ' x' . ((int)($it['quantity'] ?? 0));
          }
          $itemSummaryText = $itemSummaryParts ? implode(', ', $itemSummaryParts) : 'No line items';
          $itemsJsonEscaped = htmlspecialchars(json_encode($items), ENT_QUOTES);
        ?>
        <tr style="border-top:1px solid #f1f5f9" onmouseover="this.style.background='#fafafa'" onmouseout="this.style.background=''">

          <!-- Order ID -->
          <td style="padding:.85rem 1.25rem;font-size:.78rem;font-family:monospace;color:#475569;white-space:nowrap">#<?= substr($o['id'],-8) ?></td>

          <!-- Customer -->
          <td style="padding:.85rem 1.25rem">
            <div style="font-weight:700;font-size:.875rem;color:#0f172a"><?= htmlspecialchars($o['customer']??'—') ?></div>
            <?php if($o['cust_email']??''): ?><div style="color:#94a3b8;font-size:.72rem"><?= htmlspecialchars($o['cust_email']) ?></div><?php endif; ?>
          </td>

          <!-- Contact (Phone from Order) -->
          <td style="padding:.85rem 1.25rem">
            <?php if($o['phone']??''): ?>
              <div style="font-size:.82rem;color:#0f172a;font-weight:600">
                <svg width="12" height="12" fill="none" stroke="#f97316" stroke-width="2" viewBox="0 0 24 24" style="display:inline;vertical-align:middle;margin-right:.25rem"><path d="M22 16.92v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07A19.5 19.5 0 013.07 9.81 19.79 19.79 0 01.06 1.18 2 2 0 012 0h3a2 2 0 012 1.72 12.84 12.84 0 00.7 2.81 2 2 0 01-.45 2.11L6.09 7.91a16 16 0 006 6l1.27-1.27a2 2 0 012.11-.45 12.84 12.84 0 002.81.7A2 2 0 0122 14z"/></svg>
                <?= htmlspecialchars($o['phone']) ?>
              </div>
            <?php elseif($o['cust_phone']??''): ?>
              <div style="font-size:.82rem;color:#94a3b8;font-weight:600">
                <svg width="12" height="12" fill="none" stroke="#94a3b8" stroke-width="2" viewBox="0 0 24 24" style="display:inline;vertical-align:middle;margin-right:.25rem"><path d="M22 16.92v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07A19.5 19.5 0 013.07 9.81 19.79 19.79 0 01.06 1.18 2 2 0 012 0h3a2 2 0 012 1.72 12.84 12.84 0 00.7 2.81 2 2 0 01-.45 2.11L6.09 7.91a16 16 0 006 6l1.27-1.27a2 2 0 012.11-.45 12.84 12.84 0 002.81.7A2 2 0 0122 14z"/></svg>
                <?= htmlspecialchars($o['cust_phone']) ?>
              </div>
            <?php else: ?>
              <span style="color:#cbd5e1;font-size:.8rem">—</span>
            <?php endif; ?>
          </td>

          <!-- Items & Total -->
          <td style="padding:.85rem 1.25rem;min-width:180px">
            <div style="font-size:.8rem;color:#0f172a;font-weight:700"><?= $itemCount ?> item<?= $itemCount===1 ? '' : 's' ?> <span style="color:#94a3b8;font-weight:600">(qty <?= $itemQty ?>)</span></div>
            <div style="font-size:.76rem;color:#64748b;line-height:1.45;margin-top:.2rem"><?= htmlspecialchars($itemSummaryText) ?><?= $itemCount > 2 ? ', ...' : '' ?></div>
            <div style="margin-top:.35rem;font-weight:800;color:#f97316;font-size:.9rem">₦<?= number_format($o['total']) ?></div>
            <?php if($itemCount > 0): ?>
            <button type="button"
              onclick="openOrderItemsModal(this)"
              data-order-id="<?= htmlspecialchars($o['id']) ?>"
              data-order-code="#<?= htmlspecialchars(substr($o['id'],-8)) ?>"
              data-items="<?= $itemsJsonEscaped ?>"
              style="margin-top:.5rem;background:#fff7ed;border:1px solid #fed7aa;color:#c2410c;font-size:.72rem;font-weight:700;padding:.25rem .6rem;border-radius:8px;cursor:pointer">
              View Details
            </button>
            <?php endif; ?>
            <div style="margin-top:.25rem">
              <span style="background:#f1f5f9;color:#475569;font-size:.7rem;font-weight:600;padding:.15rem .55rem;border-radius:6px"><?= ucfirst($o['fulfillment']??'—') ?></span>
              <span style="background:#f1f5f9;color:#475569;font-size:.7rem;font-weight:600;padding:.15rem .55rem;border-radius:6px;margin-left:.25rem"><?= ucfirst($o['payment_method']??'cod') ?></span>
            </div>
          </td>

          <!-- Address -->
          <td style="padding:.85rem 1.25rem;max-width:180px">
            <?php if($o['address']??''): ?>
              <div style="font-size:.8rem;color:#475569;line-height:1.5"><?= htmlspecialchars($o['address']) ?></div>
            <?php else: ?>
              <span style="color:#cbd5e1;font-size:.8rem;font-style:italic"><?= ($o['fulfillment']??'')==='pickup'?'Pickup — no address':'—' ?></span>
            <?php endif; ?>
            <?php if($o['notes']??''): ?>
              <div style="font-size:.72rem;color:#94a3b8;margin-top:.25rem;font-style:italic">"<?= htmlspecialchars($o['notes']) ?>"</div>
            <?php endif; ?>
          </td>

          <!-- Date -->
          <td style="padding:.85rem 1.25rem;font-size:.82rem;color:#64748b;white-space:nowrap"><?= date('M j, Y', strtotime($o['created_at'])) ?><br><span style="font-size:.72rem;color:#cbd5e1"><?= date('g:i A', strtotime($o['created_at'])) ?></span></td>

          <!-- Current Status badge -->
          <td style="padding:.85rem 1.25rem">
            <span id="badge-<?= htmlspecialchars($o['id']) ?>" style="background:<?= $st['bg'] ?>;color:<?= $st['color'] ?>;border:1px solid <?= $st['border'] ?>;font-size:.72rem;font-weight:700;padding:.25rem .75rem;border-radius:20px;white-space:nowrap"><?= $label ?></span>
          </td>

          <!-- Auto-save status dropdown -->
          <td style="padding:.85rem 1.25rem">
            <select onchange="updateStatus('<?= htmlspecialchars($o['id']) ?>',this)"
              style="font-family:inherit;font-size:.8rem;padding:.4rem .7rem;border:1.5px solid #e2e8f0;border-radius:10px;outline:none;cursor:pointer;background:#fff;color:#0f172a;font-weight:600;transition:border-color .2s"
              onfocus="this.style.borderColor='#f97316'" onblur="this.style.borderColor='#e2e8f0'">
              <?php foreach(['pending','confirmed','out_for_delivery','delivered','cancelled'] as $ss): ?>
              <option value="<?= $ss ?>" <?= $o['status']===$ss?'selected':'' ?>><?= ucwords(str_replace('_',' ',$ss)) ?></option>
              <?php endforeach; ?>
            </select>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
  <?php endif; ?>
</div>

<!-- Order items details modal -->
<div id="orderItemsModal" onclick="closeOrderItemsModal()" style="display:none;position:fixed;inset:0;background:rgba(15,23,42,.68);backdrop-filter:blur(3px);z-index:9998;padding:1rem;align-items:center;justify-content:center">
  <div onclick="event.stopPropagation()" style="width:min(760px,100%);max-height:88vh;overflow:auto;background:#fff;border:1px solid #e2e8f0;border-radius:18px;box-shadow:0 20px 60px rgba(0,0,0,.25)">
    <div style="display:flex;align-items:center;justify-content:space-between;padding:1rem 1.1rem;border-bottom:1px solid #f1f5f9;position:sticky;top:0;background:#fff">
      <div>
        <div style="font-size:.73rem;font-weight:700;color:#94a3b8;letter-spacing:.06em;text-transform:uppercase">Order Items</div>
        <div id="orderItemsModalTitle" style="font-size:1rem;color:#0f172a;font-weight:800;margin-top:.1rem">Order</div>
      </div>
      <button type="button" onclick="closeOrderItemsModal()" style="width:34px;height:34px;border-radius:10px;border:1px solid #e2e8f0;background:#fff;color:#64748b;cursor:pointer;font-size:1rem">×</button>
    </div>
    <div style="padding:1rem 1.1rem">
      <div style="overflow-x:auto">
        <table style="width:100%;border-collapse:collapse;min-width:520px">
          <thead>
            <tr style="background:#f8fafc">
              <th style="text-align:left;padding:.65rem .7rem;font-size:.72rem;color:#94a3b8;text-transform:uppercase">Item</th>
              <th style="text-align:right;padding:.65rem .7rem;font-size:.72rem;color:#94a3b8;text-transform:uppercase">Qty</th>
              <th style="text-align:right;padding:.65rem .7rem;font-size:.72rem;color:#94a3b8;text-transform:uppercase">Unit Price</th>
              <th style="text-align:right;padding:.65rem .7rem;font-size:.72rem;color:#94a3b8;text-transform:uppercase">Line Total</th>
            </tr>
          </thead>
          <tbody id="orderItemsModalBody"></tbody>
        </table>
      </div>
      <div id="orderItemsModalFooter" style="margin-top:.8rem;text-align:right;font-weight:800;color:#0f172a"></div>
    </div>
  </div>
</div>

<script>
// Auto-save status via AJAX — no Save button needed
function updateStatus(orderId, selectEl) {
  var newStatus = selectEl.value;
  var statusColors = {
    pending:          {bg:'#fef3c7',color:'#d97706',border:'#fde68a'},
    confirmed:        {bg:'#dbeafe',color:'#2563eb',border:'#bfdbfe'},
    out_for_delivery: {bg:'#ede9fe',color:'#7c3aed',border:'#ddd6fe'},
    delivered:        {bg:'#d1fae5',color:'#059669',border:'#a7f3d0'},
    cancelled:        {bg:'#fee2e2',color:'#dc2626',border:'#fecaca'}
  };
  var labels = {pending:'Pending',confirmed:'Confirmed',out_for_delivery:'Out For Delivery',delivered:'Delivered',cancelled:'Cancelled'};

  selectEl.style.opacity = '.5';
  selectEl.disabled = true;

  var fd = new FormData();
  fd.append('ajax_update_status','1');
  fd.append('order_id', orderId);
  fd.append('status', newStatus);

  fetch('/stile-lpg/admin/orders.php', {method:'POST', body:fd})
    .then(r => r.json())
    .then(data => {
      selectEl.style.opacity = '1';
      selectEl.disabled = false;
      if (data.ok) {
        // Update badge
        var badge = document.getElementById('badge-' + orderId);
        if (badge) {
          var c = statusColors[newStatus] || {bg:'#f1f5f9',color:'#475569',border:'#e2e8f0'};
          badge.style.background = c.bg;
          badge.style.color = c.color;
          badge.style.borderColor = c.border;
          badge.textContent = labels[newStatus] || newStatus;
        }
        showToast('Status updated to ' + (labels[newStatus] || newStatus));
      } else {
        showToast('Update failed — please try again', true);
      }
    })
    .catch(() => { selectEl.style.opacity='1'; selectEl.disabled=false; showToast('Network error', true); });
}

function showToast(msg, error) {
  var toast = document.getElementById('statusToast');
  var icon  = toast.querySelector('svg');
  document.getElementById('toastMsg').textContent = msg;
  icon.querySelector('polyline').setAttribute('stroke', error ? '#f87171' : '#22c55e');
  toast.style.display = 'flex';
  clearTimeout(toast._timer);
  toast._timer = setTimeout(function(){ toast.style.display='none'; }, 2800);
}

// Live table filter
function filterOrders(q) {
  q = q.toLowerCase().trim();
  var rows = document.querySelectorAll('#ordersTableBody tr');
  rows.forEach(function(row) {
    row.style.display = (!q || row.innerText.toLowerCase().indexOf(q) !== -1) ? '' : 'none';
  });
}

function escapeHtml(str){
  return String(str)
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#039;');
}

function openOrderItemsModal(btn){
  var modal = document.getElementById('orderItemsModal');
  var body = document.getElementById('orderItemsModalBody');
  var title = document.getElementById('orderItemsModalTitle');
  var footer = document.getElementById('orderItemsModalFooter');

  var code = btn.getAttribute('data-order-code') || 'Order';
  title.textContent = code + ' Item Details';

  var items = [];
  try {
    items = JSON.parse(btn.getAttribute('data-items') || '[]');
  } catch (e) {
    items = [];
  }

  if(!items.length){
    body.innerHTML = '<tr><td colspan="4" style="padding:1rem;color:#94a3b8;text-align:center">No item details available.</td></tr>';
    footer.textContent = '';
  } else {
    var qtyTotal = 0;
    var amountTotal = 0;
    body.innerHTML = items.map(function(item){
      var qty = parseInt(item.quantity || 0, 10);
      var unit = Number(item.price || 0);
      var line = qty * unit;
      qtyTotal += qty;
      amountTotal += line;
      return '<tr style="border-top:1px solid #f1f5f9">'
        + '<td style="padding:.65rem .7rem;color:#0f172a;font-weight:600">' + escapeHtml(item.product_name || 'Item') + '</td>'
        + '<td style="padding:.65rem .7rem;color:#475569;text-align:right">' + qty + '</td>'
        + '<td style="padding:.65rem .7rem;color:#475569;text-align:right">₦' + unit.toLocaleString() + '</td>'
        + '<td style="padding:.65rem .7rem;color:#0f172a;font-weight:700;text-align:right">₦' + line.toLocaleString() + '</td>'
        + '</tr>';
    }).join('');
    footer.textContent = 'Total Qty: ' + qtyTotal + ' | Order Total: ₦' + amountTotal.toLocaleString();
  }

  modal.style.display = 'flex';
  document.body.style.overflow = 'hidden';
}

function closeOrderItemsModal(){
  var modal = document.getElementById('orderItemsModal');
  modal.style.display = 'none';
  document.body.style.overflow = '';
}

window.addEventListener('DOMContentLoaded', function() {
  var input = document.getElementById('orderSearch');
  if (input && input.value) filterOrders(input.value);
  document.addEventListener('keydown', function(e){
    if(e.key === 'Escape') closeOrderItemsModal();
  });
});
</script>

<?php require_once __DIR__ . '/layout_bottom.php'; ?>
