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

68 lines
1.9 KiB
PHP

<?php
require_once '../db/config.php';
header('Content-Type: application/json');
if ($_SERVER['REQUEST_METHOD'] !== 'POST') { // Should be PUT or POST
http_response_code(405);
echo json_encode(['error' => 'Method Not Allowed']);
exit;
}
$id = $_GET['id'] ?? null;
if (!$id) {
http_response_code(400);
echo json_encode(['error' => 'Customer ID is required']);
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 id = ?");
$stmt->execute([$id]);
if (!$stmt->fetch()) {
http_response_code(404);
echo json_encode(['error' => 'Customer not found']);
exit;
}
$stmt = $pdo->prepare("SELECT id FROM customers WHERE email = ? AND id != ?");
$stmt->execute([$email, $id]);
if ($stmt->fetch()) {
http_response_code(409);
echo json_encode(['error' => 'Another customer with this email already exists']);
exit;
}
$stmt = $pdo->prepare("UPDATE customers SET first_name = ?, last_name = ?, email = ?, phone = ?, address = ? WHERE id = ?");
$stmt->execute([$first_name, $last_name, $email, $phone, $address, $id]);
echo json_encode(['success' => 'Customer updated successfully']);
} catch (PDOException $e) {
http_response_code(500);
echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
}