39728-vm/api/customers.php
2026-04-26 17:57:47 +00:00

41 lines
1.9 KiB
PHP

<?php
require_once __DIR__ . '/../includes/app.php';
$user = require_permission('customers', 'add');
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
header('Content-Type: application/json');
$name = trim($_POST['name'] ?? '');
$phoneInput = trim($_POST['phone'] ?? '');
$phone = $phoneInput === '' ? '' : normalize_oman_phone($phoneInput);
$phoneForStorage = $phone === '' ? null : $phone;
if (!$name) {
echo json_encode(['success' => false, 'error' => tr('الاسم مطلوب', 'Name is required')]);
exit;
}
if ($phoneInput !== '' && $phone === '') {
echo json_encode(['success' => false, 'error' => tr('رقم الهاتف يجب أن يكون عمانياً من 8 خانات.', 'Phone must be an 8-digit Oman number.')]);
exit;
}
if ($phone !== '' && customer_phone_exists($phone)) {
echo json_encode(['success' => false, 'error' => tr('رقم الهاتف هذا مسجل لعميل آخر بالفعل.', 'This phone number is already assigned to another customer.')]);
exit;
}
try {
$pdo = db();
$stmt = $pdo->prepare('INSERT INTO customers (name, phone, phone_normalized) VALUES (?, ?, ?)');
$stmt->execute([$name, $phoneForStorage, $phoneForStorage]);
$id = $pdo->lastInsertId();
echo json_encode(['success' => true, 'customer' => ['id' => $id, 'name' => $name, 'phone' => $phone]]);
} catch (Throwable $e) {
if (is_customer_phone_unique_violation($e)) {
echo json_encode(['success' => false, 'error' => tr('رقم الهاتف هذا مسجل لعميل آخر بالفعل.', 'This phone number is already assigned to another customer.')]);
} else {
echo json_encode(['success' => false, 'error' => tr('تعذر حفظ العميل حالياً.', 'Could not save the customer right now.')]);
}
}
exit;
}