0) { $stmt = db()->prepare('SELECT * FROM sales_orders WHERE id = :id'); $stmt->execute([':id' => $editSaleId]); $editSale = $stmt->fetch(); } if ($editSale) { $editSale['items'] = json_decode((string) ($editSale['items_json'] ?? '[]'), true) ?: []; } if (!$editSale) { die(tr('الفاتورة غير موجودة.', 'Invoice not found.')); } if ($user['role'] !== 'owner' && $editSale['branch_code'] !== $user['branch_code']) { die(tr('غير مصرح لك.', 'Unauthorized.')); } $pageTitle = tr('تعديل فاتورة', 'Edit Invoice') . ' #' . h($editSale['receipt_no']); $isEidSale = (($editSale['order_type'] ?? 'standard') === 'eid'); $activeNav = $isEidSale ? 'eid_orders' : 'sales'; $error = ''; $editPaymentSummary = sale_payment_summary($editSale); $paymentAmountInput = (string) ($_POST['payment_amount'] ?? number_format((float) $editPaymentSummary['paid_amount'], 3, '.', '')); $catalog = catalog(); $allowedBranches = get_user_branches($user); $deliveryOptions = eid_delivery_status_options(); $deliveryStatusInput = trim((string) ($_POST['delivery_status'] ?? ($editSale['delivery_status'] ?? ($isEidSale ? 'pending' : '')))); $deliveryDateInput = trim((string) ($_POST['delivery_date'] ?? ($editSale['delivery_date'] ?? ''))); $notesInput = trim((string) ($_POST['notes'] ?? ($editSale['notes'] ?? ''))); $saleStatusInput = trim((string) ($_POST['sale_status'] ?? ($editSale['status'] ?? 'completed'))); $itemNotePlaceholder = $isEidSale ? tr('مثال: بدون سكر، تغليف هدية، لون معين، كتابة اسم...', 'Example: no sugar, gift wrap, specific color, write a name...') : tr('ملاحظة داخلية لهذا الصنف...', 'Internal note for this item...'); $itemNoteHelper = $isEidSale ? tr('ملاحظة داخلية لهذا الصنف فقط — لا تُطبع في الإيصال.', 'Internal for this item only — not printed on the receipt.') : tr('ملاحظة محفوظة لهذا الصنف داخل النظام.', 'This note is saved for this item inside the system.'); try { $customers = db()->query('SELECT id, name, phone FROM customers ORDER BY name ASC')->fetchAll(); } catch (Throwable $e) { $customers = []; } if ($_SERVER['REQUEST_METHOD'] === 'POST') { $branchCode = trim((string) ($_POST['branch_code'] ?? '')); $customerId = isset($_POST['customer_id']) && $_POST['customer_id'] !== '' ? (int)$_POST['customer_id'] : null; $customerName = trim((string) ($_POST['customer_name'] ?? '')); $paymentMethod = trim((string) ($_POST['payment_method'] ?? 'cash')); $paymentAmountInput = trim((string) ($_POST['payment_amount'] ?? '')); $paymentAmountForCalculation = $paymentAmountInput === '' ? '0' : $paymentAmountInput; $saleStatus = trim((string) ($_POST['sale_status'] ?? 'completed')); $saleStatusInput = $saleStatus; $notes = trim((string) ($_POST['notes'] ?? '')); $notesInput = $notes; $deliveryStatus = trim((string) ($_POST['delivery_status'] ?? ($editSale['delivery_status'] ?? ($isEidSale ? 'pending' : '')))); $deliveryStatusInput = $deliveryStatus; $deliveryDate = trim((string) ($_POST['delivery_date'] ?? ($editSale['delivery_date'] ?? ''))); $deliveryDateInput = $deliveryDate; $cartJson = (string) ($_POST['cart_json'] ?? '[]'); $items = json_decode($cartJson, true); if (!in_array($branchCode, $allowedBranches, true)) { $error = tr('اختر فرعاً صالحاً لهذه الصلاحية.', 'Choose a valid branch for this role.'); } elseif (!in_array($paymentMethod, ['cash', 'card', 'transfer', 'pay_later'], true)) { $error = tr('اختر طريقة دفع صحيحة.', 'Choose a valid payment method.'); } elseif ($isEidSale && !isset($deliveryOptions[$deliveryStatus])) { $error = tr('اختر حالة تجهيز صحيحة لطلب العيد.', 'Choose a valid prep status for the Eid order.'); } elseif ($isEidSale && ($deliveryDate === '' || !preg_match('/^\d{4}-\d{2}-\d{2}$/', $deliveryDate))) { $error = tr('حدد تاريخ تسليم صحيح لطلب العيد.', 'Choose a valid delivery date for the Eid order.'); } elseif (!is_array($items) || $items === []) { $error = tr('أضف صنفاً واحداً على الأقل إلى الفاتورة.', 'Add at least one item to the invoice.'); } else { $normalized = []; $subtotal = 0.0; $totalVat = 0.0; $itemCount = 0; foreach ($items as $item) { $sku = (string) ($item['sku'] ?? ''); $qty = (int) ($item['qty'] ?? 0); if (!isset($catalog[$sku]) || $qty < 1) { continue; } $product = $catalog[$sku]; $itemNote = trim((string) ($item['item_note'] ?? '')); $price = (float) $product['price']; $lineTotal = $price * $qty; $vatPercent = (float) ($product['vat'] ?? 0); $itemVat = $lineTotal * ($vatPercent / 100); $totalVat += $itemVat; $normalized[] = [ 'sku' => $sku, 'name_ar' => $product['name_ar'], 'name_en' => $product['name_en'], 'qty' => $qty, 'price' => $price, 'item_note' => $itemNote, 'line_total' => $lineTotal, 'vat_percent' => $vatPercent, 'vat_amount' => $itemVat ]; $subtotal += $lineTotal; $itemCount += $qty; } if ($normalized === []) { $error = tr('الفاتورة غير صالحة بعد التحقق من الأصناف.', 'The invoice is invalid after product validation.'); } else { $totalAmount = $subtotal + $totalVat; if ($paymentAmountInput !== '' && !is_numeric($paymentAmountInput)) { $error = tr('أدخل مبلغاً مدفوعاً صحيحاً.', 'Enter a valid paid amount.'); } else { $paymentMeta = sale_payment_breakdown($totalAmount, $paymentMethod, $paymentAmountForCalculation); if ($paymentMeta['due_amount'] > 0.0005 && !$customerId) { $error = tr('يجب اختيار عميل مسجل عند وجود مبلغ متبقٍ أو دفعة جزئية.', 'Select a registered customer when there is a remaining balance or partial payment.'); } } } if ($error === '') { $cashierName = current_lang() === 'ar' ? $user['name_ar'] : $user['name_en']; db()->beginTransaction(); try { sync_order_stock_reservation( $editSale['items'] ?? [], (string) ($editSale['status'] ?? 'completed'), $normalized, $saleStatus ); $stmt = db()->prepare('UPDATE sales_orders SET branch_code = :branch_code, customer_id = :customer_id, customer_name = :customer_name, payment_method = :payment_method, payment_status = :payment_status, paid_amount = :paid_amount, due_amount = :due_amount, items_json = :items_json, item_count = :item_count, subtotal = :subtotal, vat_amount = :vat_amount, total_amount = :total_amount, status = :status, delivery_status = :delivery_status, delivery_date = :delivery_date, notes = :notes WHERE id = :id'); $stmt->execute([ ':branch_code' => $branchCode, ':customer_id' => $customerId, ':customer_name' => $customerName !== '' ? $customerName : null, ':payment_method' => $paymentMethod, ':payment_status' => $paymentMeta['payment_status'], ':paid_amount' => $paymentMeta['paid_amount'], ':due_amount' => $paymentMeta['due_amount'], ':items_json' => json_encode($normalized, JSON_UNESCAPED_UNICODE), ':item_count' => $itemCount, ':subtotal' => $subtotal, ':vat_amount' => $totalVat, ':total_amount' => $totalAmount, ':status' => $saleStatus, ':delivery_status' => $isEidSale ? $deliveryStatus : ($editSale['delivery_status'] ?? 'pending'), ':delivery_date' => $isEidSale && $deliveryDate !== '' ? $deliveryDate : ($isEidSale ? null : ($editSale['delivery_date'] ?? null)), ':notes' => $notes !== '' ? $notes : null, ':id' => $editSaleId, ]); db()->commit(); } catch (Throwable $e) { if (db()->inTransaction()) { db()->rollBack(); } $error = tr('تعذر تحديث الفاتورة.', 'Could not update the invoice.'); } if ($error === '') { $flashType = 'success'; $flashMessage = tr('تم تحديث الفاتورة بنجاح.', 'Invoice updated successfully.'); if ($isEidSale && wablas_is_configured()) { $wablasResult = wablas_notify_sale_invoice($editSaleId); if (!empty($wablasResult['success'])) { $flashMessage = tr('تم تحديث الفاتورة وإعادة إرسالها عبر واتساب بنجاح.', 'Invoice updated and resent via WhatsApp successfully.'); } else { $flashType = 'warning'; $flashMessage = tr('تم تحديث الفاتورة، لكن تعذر إعادة إرسالها عبر واتساب. تحقق من رقم واتساب العميل أو إعدادات واتساب.', 'Invoice updated, but resending via WhatsApp failed. Check the customer WhatsApp number or WhatsApp settings.'); } } set_flash($flashType, $flashMessage); redirect_to($isEidSale ? 'eid_orders.php' : 'sales.php'); } } } } require __DIR__ . '/includes/header.php'; ?>

0.000
0.000
0.000
0.000
0.000