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

// التحقق من تسجيل الدخول
$user_id = $_SESSION['user_id'] ?? 1;

// جلب المنتج من الرابط
$product_id = $_GET['product_id'] ?? 0;
$stmt = $pdo->prepare("SELECT * FROM products WHERE id=?");
$stmt->execute([$product_id]);
$product = $stmt->fetch();

// جلب الحسابات البنكية
$banks = $pdo->query("SELECT * FROM bank_accounts ORDER BY id ASC")->fetchAll();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $bank_id = $_POST['bank_account'];
    $sender_name = $_POST['sender_name'];
    $phone = $_POST['phone'];
    $amount = $product['price'];
    $slip = "";

    // رفع الإيصال
    if (!empty($_FILES['slip']['name'])) {
        $slip = time() . "_" . $_FILES['slip']['name'];
        move_uploaded_file($_FILES['slip']['tmp_name'], "../assets/uploads/" . $slip);
    }

    // حفظ الطلب
    $stmt = $pdo->prepare("INSERT INTO orders (user_id, product_id, bank_account_id, sender_name, phone, amount, slip, status) VALUES (?,?,?,?,?,?,?,?)");
    $stmt->execute([$user_id, $product_id, $bank_id, $sender_name, $phone, $amount, $slip, "بانتظار"]);

    header("Location: dashboard.php?order=success");
    exit;
}
?>

<section class="container" style="margin-top:40px;">
  <h2 class="section-title">إتمام الطلب</h2>

  <div class="card" style="max-width:700px;margin:auto;">
    <?php if ($product): ?>
      <h3><?= e($product['title']); ?></h3>
      <p>السعر: <span style="color:#D4AF37;"><?= formatPrice($product['price']); ?></span></p>
    <?php else: ?>
      <p style="color:#f44336;">❌ المنتج غير موجود</p>
    <?php endif; ?>
  </div>

  <form method="post" enctype="multipart/form-data" style="max-width:700px;margin:auto;background:#121212;padding:20px;border-radius:8px;margin-top:20px;">
    <label>اسم المحوِّل:</label>
    <input type="text" name="sender_name" required style="width:100%;padding:10px;margin:6px 0;">

    <label>رقم الجوال:</label>
    <input type="text" name="phone" required style="width:100%;padding:10px;margin:6px 0;">

    <label>اختر البنك:</label>
    <select name="bank_account" required style="width:100%;padding:10px;margin:6px 0;">
      <option value="">-- اختر البنك --</option>
      <?php foreach($banks as $b): ?>
        <option value="<?= $b['id']; ?>"><?= e($b['bank_name']); ?> - <?= e($b['iban']); ?></option>
      <?php endforeach; ?>
    </select>

    <label>رفع إيصال التحويل:</label>
    <input type="file" name="slip" accept="image/*" required style="margin:10px 0;">

    <button type="submit" class="btn">تأكيد الطلب</button>
  </form>
</section>

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