<?php
// المسار: admin/orders.php
// صفحة إدارة الطلبات (منظمة + فلترة بسيطة + شكل حديث)

require_once __DIR__.'/../includes/functions.php';
require_once __DIR__.'/../includes/db.php';
$config = require __DIR__ . '/../config.php';

// حماية الأدمن
session_start();
if (empty($_SESSION['admin'])) {
    header('Location: login.php');
    exit;
}

/* =======================
   Helpers
======================= */
if (!function_exists('e')) {
    function e($v){
        return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('price')) {
    function price(float $v): string {
        global $config;
        $baseCurrency = $config['currency_code'] ?? 'JOD';
        $selected     = $_SESSION['currency_admin'] ?? $baseCurrency; // أو استخدم عملة ثابتة للأدمن
        $rates        = $config['currency_rates']   ?? [$baseCurrency => 1];
        $symbols      = $config['currency_symbols'] ?? [$baseCurrency => ($config['currency_symbol'] ?? 'د.أ')];

        $rate      = $rates[$selected] ?? 1;
        $converted = $v * $rate;
        $amount    = number_format($converted, 2);
        $symbol    = $symbols[$selected] ?? $selected;
        $pos       = $config['currency_position'] ?? 'after';

        return $pos === 'after' ? "$amount $symbol" : "$symbol $amount";
    }
}

/* =======================
   Filters (GET)
======================= */
$paymentStatus = $_GET['payment_status'] ?? '';
$orderStatus   = $_GET['status'] ?? '';
$paymentMethod = $_GET['payment_method'] ?? '';

$where  = ' WHERE 1 ';
$params = [];

if ($paymentStatus !== '' && $paymentStatus !== 'all') {
    $where .= ' AND o.payment_status = :ps ';
    $params[':ps'] = $paymentStatus;
}
if ($orderStatus !== '' && $orderStatus !== 'all') {
    $where .= ' AND o.status = :st ';
    $params[':st'] = $orderStatus;
}
if ($paymentMethod !== '' && $paymentMethod !== 'all') {
    $where .= ' AND o.payment_method = :pm ';
    $params[':pm'] = $paymentMethod;
}

/* =======================
   Fetch Orders
======================= */
$sql = "
  SELECT o.*, c.name AS customer_name, c.phone AS customer_phone
  FROM orders o
  LEFT JOIN customers c ON o.customer_id = c.id
  $where
  ORDER BY o.created_at DESC
";
$stmt   = $pdo->prepare($sql);
$stmt->execute($params);
$orders = $stmt->fetchAll(PDO::FETCH_ASSOC);

/* =======================
   Meta
======================= */
$pageTitle = 'إدارة الطلبات';
?>
<!doctype html>
<html lang="ar" dir="rtl">
<head>
  <meta charset="utf-8">
  <title><?= e($pageTitle) ?> - لوحة التحكم</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.rtl.min.css" rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">

  <style>
    body{
      background:#f4f6fb;
      font-family:'Cairo', system-ui, -apple-system, 'Segoe UI', sans-serif;
    }
    .admin-shell{
      max-width:1200px;
    }
    .page-header{
      display:flex;
      align-items:center;
      justify-content:space-between;
      flex-wrap:wrap;
      gap:.75rem;
      margin-bottom:1rem;
    }
    .page-title{
      font-weight:900;
      font-size:1.3rem;
      margin:0;
      display:flex;
      align-items:center;
      gap:.5rem;
    }
    .page-title-icon{
      width:36px;height:36px;
      border-radius:50%;
      display:grid;place-items:center;
      background:rgba(13,110,253,.08);
      color:#0d6efd;
    }
    .filter-card{
      background:#fff;
      border-radius:16px;
      border:1px solid #e2e8f0;
      box-shadow:0 4px 18px rgba(15,23,42,.08);
      padding:.85rem .95rem;
      margin-bottom:1rem;
    }
    .filter-row{
      display:flex;
      flex-wrap:wrap;
      gap:.6rem;
      align-items:flex-end;
    }
    .filter-row .form-select{
      border-radius:999px;
      font-size:.85rem;
    }

    .orders-card{
      background:#fff;
      border-radius:18px;
      border:1px solid #e2e8f0;
      box-shadow:0 6px 22px rgba(15,23,42,.08);
      padding:1rem;
    }
    .table thead th{
      font-size:.80rem;
      font-weight:800;
      color:#64748b;
      border-color:#e2e8f0;
    }
    .table tbody td{
      font-size:.86rem;
      vertical-align:middle;
    }

    .badge-pay{
      font-size:.75rem;
      padding:.28rem .55rem;
      border-radius:999px;
      font-weight:800;
    }
    .badge-status{
      font-size:.75rem;
      padding:.28rem .55rem;
      border-radius:999px;
      font-weight:800;
    }

    .status-pill{
      display:inline-flex;
      align-items:center;
      gap:.3rem;
    }
    .status-dot{
      width:8px;height:8px;
      border-radius:50%;
      background:currentColor;
    }

    .orders-empty{
      padding:2.5rem 1rem;
      text-align:center;
      color:#94a3b8;
    }

    .btn-pill{
      border-radius:999px;
    }

    @media (max-width:575.98px){
      .page-header{
        align-items:flex-start;
      }
    }
  </style>
</head>
<body>
<div class="container py-4 admin-shell">

  <div class="page-header">
    <div>
      <h1 class="page-title">
        <span class="page-title-icon"><i class="bi bi-bag-check"></i></span>
        <span><?= e($pageTitle) ?></span>
      </h1>
      <div class="text-muted small mt-1">
        عرض وإدارة جميع طلبات المتجر، مع إمكانية الفلترة حسب حالة الدفع أو حالة الطلب.
      </div>
    </div>
    <a href="dashboard.php" class="btn btn-outline-secondary btn-sm btn-pill">
      <i class="bi bi-speedometer2"></i> عودة للوحة التحكم
    </a>
  </div>

  <!-- Filters -->
  <div class="filter-card">
    <form method="get" class="filter-row">
      <div>
        <label class="form-label small mb-1">حالة الدفع</label>
        <select name="payment_status" class="form-select form-select-sm">
          <?php $ps = $paymentStatus ?: 'all'; ?>
          <option value="all" <?= $ps==='all'?'selected':'' ?>>الكل</option>
          <option value="pending" <?= $ps==='pending'?'selected':'' ?>>قيد الانتظار</option>
          <option value="awaiting_transfer" <?= $ps==='awaiting_transfer'?'selected':'' ?>>بانتظار التحويل</option>
          <option value="initiated" <?= $ps==='initiated'?'selected':'' ?>>تم البدء</option>
          <option value="paid" <?= $ps==='paid'?'selected':'' ?>>مدفوع</option>
          <option value="failed" <?= $ps==='failed'?'selected':'' ?>>فشل الدفع</option>
        </select>
      </div>

      <div>
        <label class="form-label small mb-1">حالة الطلب</label>
        <select name="status" class="form-select form-select-sm">
          <?php $st = $orderStatus ?: 'all'; ?>
          <option value="all" <?= $st==='all'?'selected':'' ?>>الكل</option>
          <option value="new" <?= $st==='new'?'selected':'' ?>>جديد</option>
          <option value="waiting_payment" <?= $st==='waiting_payment'?'selected':'' ?>>بانتظار الدفع</option>
          <option value="processing" <?= $st==='processing'?'selected':'' ?>>قيد المعالجة</option>
          <option value="shipped" <?= $st==='shipped'?'selected':'' ?>>تم الشحن</option>
          <option value="completed" <?= $st==='completed'?'selected':'' ?>>مكتمل</option>
          <option value="cancelled" <?= $st==='cancelled'?'selected':'' ?>>ملغي</option>
        </select>
      </div>

      <div>
        <label class="form-label small mb-1">طريقة الدفع</label>
        <select name="payment_method" class="form-select form-select-sm">
          <?php $pm = $paymentMethod ?: 'all'; ?>
          <option value="all" <?= $pm==='all'?'selected':'' ?>>الكل</option>
          <option value="cod" <?= $pm==='cod'?'selected':'' ?>>الدفع عند التوصيل (COD)</option>
          <option value="cliq" <?= $pm==='cliq'?'selected':'' ?>>كليك (تحويل فوري)</option>
          <option value="card" <?= $pm==='card'?'selected':'' ?>>بطاقة (فيزا / ماستر)</option>
        </select>
      </div>

      <div>
        <button class="btn btn-primary btn-sm btn-pill mt-3 mt-sm-0" type="submit">
          <i class="bi bi-funnel"></i> تطبيق الفلاتر
        </button>
        <a href="orders.php" class="btn btn-outline-secondary btn-sm btn-pill mt-2 mt-sm-0">
          إعادة الضبط
        </a>
      </div>

      <div class="ms-auto text-muted small mt-2 mt-sm-0">
        إجمالي: <?= count($orders) ?> طلب
      </div>
    </form>
  </div>

  <!-- Orders Table -->
  <div class="orders-card">
    <?php if (!$orders): ?>
      <div class="orders-empty">
        <i class="bi bi-inbox fs-3 d-block mb-2"></i>
        لا توجد طلبات مطابقة للفلاتر الحالية.
      </div>
    <?php else: ?>
      <div class="table-responsive">
        <table class="table table-hover align-middle mb-0">
          <thead>
            <tr>
              <th>#</th>
              <th>الزبون</th>
              <th>الهاتف</th>
              <th>الإجمالي</th>
              <th>طريقة الدفع</th>
              <th>حالة الدفع</th>
              <th>حالة الطلب</th>
              <th class="text-end">تاريخ الإنشاء</th>
              <th class="text-end">إجراءات</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($orders as $order): ?>
              <?php
                $payStatus = $order['payment_status'] ?? 'pending';
                $orderStatusVal = $order['status'] ?? 'new';

                // ألوان حالة الدفع
                $payClass = 'bg-warning text-dark';
                if ($payStatus === 'paid') {
                    $payClass = 'bg-success';
                } elseif ($payStatus === 'failed') {
                    $payClass = 'bg-danger';
                } elseif (in_array($payStatus, ['awaiting_transfer','initiated'], true)) {
                    $payClass = 'bg-info text-dark';
                }

                // ألوان حالة الطلب
                $statusClass = 'bg-secondary';
                switch ($orderStatusVal) {
                    case 'completed':
                        $statusClass = 'bg-success';
                        break;
                    case 'shipped':
                        $statusClass = 'bg-info text-dark';
                        break;
                    case 'cancelled':
                        $statusClass = 'bg-danger';
                        break;
                    case 'processing':
                        $statusClass = 'bg-primary';
                        break;
                    case 'waiting_payment':
                        $statusClass = 'bg-warning text-dark';
                        break;
                    case 'new':
                        $statusClass = 'bg-secondary';
                        break;
                }

                $methodLabel = $order['payment_method'] ?? '';
                if ($methodLabel === 'cod') {
                    $methodLabel = 'الدفع عند التوصيل';
                } elseif ($methodLabel === 'cliq') {
                    $methodLabel = 'تحويل كليك';
                } elseif ($methodLabel === 'card') {
                    $methodLabel = 'بطاقة (فيزا / ماستر)';
                }
              ?>
              <tr>
                <td class="fw-semibold">#<?= (int)$order['id'] ?></td>
                <td>
                  <div class="fw-semibold"><?= e($order['customer_name'] ?? '-') ?></div>
                </td>
                <td><?= e($order['customer_phone'] ?? '-') ?></td>
                <td><?= e(price((float)$order['total'])) ?></td>
                <td><?= e($methodLabel) ?></td>
                <td>
                  <span class="badge-pay badge <?= $payClass ?>">
                    <?= e($payStatus) ?>
                  </span>
                </td>
                <td>
                  <span class="badge-status badge <?= $statusClass ?>">
                    <span class="status-pill">
                      <span class="status-dot"></span>
                      <span><?= e($orderStatusVal) ?></span>
                    </span>
                  </span>
                </td>
                <td class="text-end">
                  <?= e(date('Y-m-d H:i', strtotime($order['created_at']))) ?>
                </td>
                <td class="text-end">
                  <a href="order_view.php?id=<?= (int)$order['id'] ?>"
                     class="btn btn-sm btn-outline-primary btn-pill">
                    <i class="bi bi-eye"></i> تفاصيل
                  </a>
                  <a href="order_delete.php?id=<?= (int)$order['id'] ?>"
                     class="btn btn-sm btn-outline-danger btn-pill"
                     onclick="return confirm('هل أنت متأكد من حذف الطلب؟');">
                    <i class="bi bi-trash"></i> حذف
                  </a>
                </td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    <?php endif; ?>
  </div>

</div>
</body>
</html>