34567-vm/customers/create.php
2025-10-02 20:43:00 +00:00

55 lines
1.5 KiB
PHP

<?php
require_once '../db/config.php';
header('Content-Type: application/json');
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['error' => 'Method Not Allowed']);
exit;
}
$data = json_decode(file_get_contents('php://input'), true);
$first_name = $data['first_name'] ?? null;
$last_name = $data['last_name'] ?? null;
$email = $data['email'] ?? null;
$phone = $data['phone'] ?? null;
$address = $data['address'] ?? null;
if (!$first_name || !$last_name || !$email) {
http_response_code(400);
echo json_encode(['error' => 'Missing required fields: first_name, last_name, email']);
exit;
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
http_response_code(400);
echo json_encode(['error' => 'Invalid email format']);
exit;
}
try {
$pdo = db();
$stmt = $pdo->prepare("SELECT id FROM customers WHERE email = ?");
$stmt->execute([$email]);
if ($stmt->fetch()) {
http_response_code(409);
echo json_encode(['error' => 'Customer with this email already exists']);
exit;
}
$stmt = $pdo->prepare("INSERT INTO customers (first_name, last_name, email, phone, address) VALUES (?, ?, ?, ?, ?)");
$stmt->execute([$first_name, $last_name, $email, $phone, $address]);
$id = $pdo->lastInsertId();
http_response_code(201);
echo json_encode(['success' => 'Customer created successfully', 'id' => $id]);
} catch (PDOException $e) {
http_response_code(500);
echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
}