query('SELECT id, name, phone FROM suppliers ORDER BY name ASC')->fetchAll(); } catch (Throwable $e) { $customers = []; } if ($_SERVER['REQUEST_METHOD'] === 'POST') { $branchCode = trim((string) ($_POST['branch_code'] ?? '')); $supplierName = trim((string) ($_POST['supplier_name'] ?? '')); $paymentMethod = trim((string) ($_POST['payment_method'] ?? 'cash')); $purchaseStatus = trim((string) ($_POST['purchase_status'] ?? 'completed')); $notes = trim((string) ($_POST['notes'] ?? '')); $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'], true)) { $error = tr('اختر طريقة دفع صحيحة.', 'Choose a valid payment method.'); } elseif (!is_array($items) || $items === []) { $error = tr('أضف صنفاً واحداً على الأقل إلى الفاتورة.', 'Add at least one item to the invoice.'); } else { $normalized = []; $subtotal = 0.0; $totalVat = 0.0; $globalVat = (float) get_setting('vat_percentage', 5); $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]; $price = isset($item['price']) ? (float)$item['price'] : (float)($product['cost_price'] ?? $product['price']); $lineTotal = $price * $qty; $normalized[] = [ 'sku' => $sku, 'name_ar' => $product['name_ar'], 'name_en' => $product['name_en'], 'qty' => $qty, 'price' => $price, 'line_total' => $lineTotal, ]; $subtotal += $lineTotal; $itemVat = $lineTotal * ($globalVat / 100); $totalVat += $itemVat; $itemCount += $qty; } if ($normalized === []) { $error = tr('الفاتورة غير صالحة بعد التحقق من الأصناف.', 'The invoice is invalid after product validation.'); } else { $cashierName = current_lang() === 'ar' ? $user['name_ar'] : $user['name_en']; $purchaseId = create_purchase([ 'reference_no' => purchase_reference_code(), 'branch_code' => $branchCode, 'user_username' => $user['username'], 'user_name' => $cashierName, 'role_name' => $user['role'], 'supplier_name' => $supplierName !== '' ? $supplierName : null, 'items' => $normalized, 'item_count' => $itemCount, 'subtotal' => $subtotal, 'vat_amount' => $totalVat, 'total_amount' => $subtotal + $totalVat, 'status' => $purchaseStatus, 'notes' => $notes !== '' ? $notes : null, ]); set_flash('success', tr('تم حفظ فاتورة المشتريات بنجاح. وتم تحديث المخزون.', 'Purchase invoice saved successfully and stock updated.')); redirect_to('purchases.php'); } } } require __DIR__ . '/header.php'; ?>

0.000
0.000
0.000