<?php
require_once __DIR__ . "/../config/db.php";
include __DIR__ . "/partials/header.php";

// جلب الطلبات مع بيانات البنك
$stmt = db()->query("
  SELECT o.*, b.bank_name, b.account_holder 
  FROM orders o 
  LEFT JOIN bank_accounts b ON o.bank_account_id = b.id 
  ORDER BY o.created_at DESC
");
$orders = $stmt->fetchAll();
?>

<div class="container">
  <h2 class="admin-title">📋 إدارة الطلبات</h2>

  <table class="table">
    <thead>
      <tr>
        <th>#</th>
        <th>العميل</th>
        <th>التاريخ</th>
        <th>المبلغ</th>
        <th>الحالة</th>
        <th>الحساب البنكي</th>
        <th>الإيصال</th>
        <th>إجراءات</th>
      </tr>
    </thead>
    <tbody>
      <?php foreach ($orders as $o): ?>
        <tr>
          <td><?= $o['id'] ?></td>
          <td><?= $o['user_id'] ?? "زائر" ?></td>
          <td><?= $o['created_at'] ?></td>
          <td><?= number_format($o['total'], 2) ?> ر.س</td>
          <td>
            <form action="order_status_update.php" method="post" style="display:inline;">
              <input type="hidden" name="id" value="<?= $o['id'] ?>">
              <select name="status" onchange="this.form.submit()">
                <option value="معلق" <?= $o['status']=='معلق'?'selected':'' ?>>معلق</option>
                <option value="قيد المراجعة" <?= $o['status']=='قيد المراجعة'?'selected':'' ?>>قيد المراجعة</option>
                <option value="مكتمل" <?= $o['status']=='مكتمل'?'selected':'' ?>>مكتمل</option>
                <option value="مرفوض" <?= $o['status']=='مرفوض'?'selected':'' ?>>مرفوض</option>
              </select>
            </form>
          </td>
          <td><?= $o['bank_name'] ?> - <?= $o['account_holder'] ?></td>
          <td>
            <?php if ($o['receipt']): ?>
              <a href="../uploads/receipts/<?= htmlspecialchars($o['receipt']) ?>" target="_blank">📄 عرض</a>
            <?php else: ?>
              لا يوجد
            <?php endif; ?>
          </td>
          <td>
            <a href="order_items.php?id=<?= $o['id'] ?>" class="btn btn-sm btn-info">تفاصيل</a>
          </td>
        </tr>
      <?php endforeach; ?>
    </tbody>
  </table>
</div>

<?php include __DIR__ . "/partials/footer.php"; ?>
