69 lines
2.0 KiB
PHP
69 lines
2.0 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' => 'Employee 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;
|
|
$role_id = $data['role_id'] ?? null;
|
|
$hire_date = $data['hire_date'] ?? null;
|
|
|
|
if (!$first_name || !$last_name || !$email || !$role_id) {
|
|
http_response_code(400);
|
|
echo json_encode(['error' => 'Missing required fields: first_name, last_name, email, role_id']);
|
|
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 employees WHERE id = ?");
|
|
$stmt->execute([$id]);
|
|
if (!$stmt->fetch()) {
|
|
http_response_code(404);
|
|
echo json_encode(['error' => 'Employee not found']);
|
|
exit;
|
|
}
|
|
|
|
$stmt = $pdo->prepare("SELECT id FROM employees WHERE email = ? AND id != ?");
|
|
$stmt->execute([$email, $id]);
|
|
if ($stmt->fetch()) {
|
|
http_response_code(409);
|
|
echo json_encode(['error' => 'Another employee with this email already exists']);
|
|
exit;
|
|
}
|
|
|
|
$stmt = $pdo->prepare("UPDATE employees SET first_name = ?, last_name = ?, email = ?, phone = ?, role_id = ?, hire_date = ? WHERE id = ?");
|
|
$stmt->execute([$first_name, $last_name, $email, $phone, $role_id, $hire_date, $id]);
|
|
|
|
echo json_encode(['success' => 'Employee updated successfully']);
|
|
|
|
} catch (PDOException $e) {
|
|
http_response_code(500);
|
|
echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
|
|
}
|