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

// جلب الطلبات + بيانات العميل + الحساب البنكي
$sql = "SELECT o.id, o.total, o.status, o.created_at, 
               u.name AS user_name, 
               b.bank_name, b.account_holder,
               o.receipt
        FROM orders o
        JOIN users u ON o.user_id = u.id
        JOIN bank_accounts b ON o.bank_account_id = b.id
        ORDER BY o.id DESC";
$orders = db()->query($sql)->fetchAll();
?>

<div class="admin-content">
  <h2>🧾 إدارة الطلبات</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><?= htmlspecialchars($o['user_name']) ?></td>
          <td><?= $o['created_at'] ?></td>
          <td><?= number_format($o['total'], 2) ?> ر.س</td>
          <td>
            <form method="post" action="update_order_status.php" style="margin:0;">
              <input type="hidden" name="order_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><?= htmlspecialchars($o['bank_name']) ?> - <?= htmlspecialchars($o['account_holder']) ?></td>
          <td>
            <?php if ($o['receipt']): ?>
              <a href="../uploads/receipts/<?= $o['receipt'] ?>" target="_blank" style="color:blue;">عرض</a>
            <?php else: ?>
              —
            <?php endif; ?>
          </td>
          <td>
            <a href="order_view.php?id=<?= $o['id'] ?>" class="btn">تفاصيل</a>
          </td>
        </tr>
      <?php endforeach; ?>
    </tbody>
  </table>
</div>

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