<?php
session_start();
require_once __DIR__ . "/config/db.php";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $user_id = $_SESSION['user_id'] ?? null; // لو عندك تسجيل دخول
    $bank_account_id = $_POST['bank_account_id'] ?? 0;
    $total = $_POST['total'] ?? 0;
    $notes = $_POST['notes'] ?? '';

    // السلة
    $cart = $_SESSION['cart'] ?? [];
    if (!$cart || !is_array($cart)) {
        echo "❌ لا توجد منتجات في السلة";
        exit;
    }

    // رفع الإيصال
    $receiptFile = null;
    if (isset($_FILES['receipt']) && $_FILES['receipt']['error'] === UPLOAD_ERR_OK) {
        $ext = pathinfo($_FILES['receipt']['name'], PATHINFO_EXTENSION);
        $receiptFile = "receipt_" . time() . "_" . rand(1000,9999) . "." . $ext;
        $uploadDir = __DIR__ . "/uploads/receipts/";
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }
        $uploadPath = $uploadDir . $receiptFile;
        move_uploaded_file($_FILES['receipt']['tmp_name'], $uploadPath);
    }

    // إدخال الطلب الأساسي
    $stmt = db()->prepare("INSERT INTO orders (user_id, bank_account_id, total, receipt, notes, status, created_at) 
                           VALUES (?, ?, ?, ?, ?, 'معلق', NOW())");
    $stmt->execute([$user_id, $bank_account_id, $total, $receiptFile, $notes]);
    $order_id = db()->lastInsertId();

    // إدخال تفاصيل المنتجات في order_items
    foreach ($cart as $product_id => $item) {
        if (!is_array($item)) continue;

        $qty   = $item['qty'];
        $price = $item['price']; // السعر المخزن لحظة الإضافة للسلة
        $lineTotal = $price * $qty;

        $stmt = db()->prepare("INSERT INTO order_items (order_id, product_id, quantity, price) 
                               VALUES (?, ?, ?, ?)");
        $stmt->execute([$order_id, $product_id, $qty, $lineTotal]);
    }

    // تفريغ السلة
    unset($_SESSION['cart']);

    header("Location: thank_you.php");
    exit;
} else {
    echo "❌ وصول غير صحيح";
}
