0) { $stmt = db()->prepare('SELECT * FROM online_orders WHERE id = :id'); $stmt->execute([':id' => $editOrderId]); $editOrder = $stmt->fetch(); } if (!$editOrder) { die(tr('الطلب غير موجود.', 'Order not found.')); } $pageTitle = tr('تعديل طلب', 'Edit Order') . ' #' . $editOrderId; $activeNav = 'online_orders'; $error = ''; $catalog = catalog(); if ($_SERVER['REQUEST_METHOD'] === 'POST') { $customerName = trim((string) ($_POST['customer_name'] ?? '')); $customerPhone = trim((string) ($_POST['customer_phone'] ?? '')); $customerAddress = trim((string) ($_POST['customer_address'] ?? '')); $saleStatus = trim((string) ($_POST['sale_status'] ?? 'pending')); $cartJson = (string) ($_POST['cart_json'] ?? '[]'); $items = json_decode($cartJson, true); if ($customerName === '' || $customerPhone === '' || $customerAddress === '') { $error = tr('الرجاء تعبئة بيانات العميل الأساسية.', 'Please fill the main customer details.'); } elseif (!is_array($items) || $items === []) { $error = tr('أضف صنفاً واحداً على الأقل إلى الطلب.', 'Add at least one item to the order.'); } else { $normalized = []; $subtotal = 0.0; $totalVat = 0.0; foreach ($items as $item) { $sku = (string) ($item['sku'] ?? ''); $qty = (int) ($item['qty'] ?? 0); if (!isset($catalog[$sku]) || $qty < 1) { continue; // if sku doesn't exist in catalog or qty invalid } $product = $catalog[$sku]; $price = (float) $product['price']; $lineTotal = $price * $qty; $vatPercent = (float) ($product['vat'] ?? 0); $itemVat = $lineTotal * ($vatPercent / 100); $totalVat += $itemVat; $normalized[] = [ 'id' => $product['id'] ?? 0, 'sku' => $sku, 'name' => current_lang() === 'ar' ? $product['name_ar'] : $product['name_en'], 'name_ar' => $product['name_ar'], 'name_en' => $product['name_en'], 'qty' => $qty, 'price' => $price, 'line_total' => $lineTotal, 'vat_percent' => $vatPercent, 'vat_amount' => $itemVat ]; $subtotal += $lineTotal; } if ($normalized === []) { $error = tr('الطلب غير صالح بعد التحقق من الأصناف.', 'The order is invalid after product validation.'); } else { $stmt = db()->prepare('UPDATE online_orders SET customer_name = :customer_name, customer_phone = :customer_phone, customer_address = :customer_address, items_json = :items_json, subtotal = :subtotal, vat_amount = :vat_amount, total_amount = :total_amount, status = :status WHERE id = :id'); $stmt->execute([ ':customer_name' => $customerName, ':customer_phone' => $customerPhone, ':customer_address' => $customerAddress, ':items_json' => json_encode($normalized, JSON_UNESCAPED_UNICODE), ':subtotal' => $subtotal, ':vat_amount' => $totalVat, ':total_amount' => $subtotal + $totalVat, ':status' => $saleStatus, ':id' => $editOrderId, ]); set_flash('success', tr('تم تحديث الطلب بنجاح.', 'Order updated successfully.')); redirect_to('online_orders.php'); } } } require __DIR__ . '/includes/header.php'; ?>