<?php
require_once "config/db.php";

$order_id = intval($_GET['order_id'] ?? 0);

if ($order_id > 0) {
    $sql = "SELECT o.*, 
                   p.name AS product_name, 
                   p.weight, 
                   u.name AS customer_name, 
                   u.email, 
                   u.phone
            FROM orders o
            LEFT JOIN products p ON o.product_id = p.id
            LEFT JOIN users u ON o.user_id = u.id
            WHERE o.id = ? LIMIT 1";
    $stmt = db()->prepare($sql);
    $stmt->execute([$order_id]);
    $order = $stmt->fetch();
}

if (empty($order)) {
    die("⚠️ الطلب غير موجود.");
}
?>

<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
  <meta charset="UTF-8">
  <title>فاتورة #<?= $order['id'] ?></title>
  <style>
    body { font-family: 'Cairo', sans-serif; margin: 40px; }
    h2 { color: #333; }
    table { border-collapse: collapse; width: 100%; margin-top: 20px; }
    table, th, td { border: 1px solid #ddd; }
    th, td { padding: 12px; text-align: center; }
    th { background: #f4f4f4; }
    .total { font-weight: bold; color: #D4AF37; }
    .print-btn { margin-top: 20px; padding:10px 20px; background:#28a745; color:#fff; border:none; cursor:pointer; border-radius:5px; }
  </style>
</head>
<body onload="window.print()">

  <h2>فاتورة طلب #<?= $order['id'] ?></h2>
  <p><strong>العميل:</strong> <?= htmlspecialchars($order['customer_name']) ?></p>
  <p><strong>البريد الإلكتروني:</strong> <?= htmlspecialchars($order['email']) ?></p>
  <p><strong>الهاتف:</strong> <?= htmlspecialchars($order['phone']) ?></p>
  <p><strong>تاريخ الطلب:</strong> <?= $order['created_at'] ?></p>

  <table>
    <tr>
      <th>السبيكة</th>
      <th>الوزن (جرام)</th>
      <th>الكمية</th>
      <th>الإجمالي (ريال)</th>
    </tr>
    <tr>
      <td><?= htmlspecialchars($order['product_name']) ?></td>
      <td><?= $order['weight'] ?></td>
      <td><?= $order['quantity'] ?></td>
      <td class="total"><?= number_format($order['total'], 2) ?></td>
    </tr>
  </table>

</body>
</html>
