34394-vm/delete-note.php
2025-09-26 19:57:10 +00:00

57 lines
1.7 KiB
PHP

<?php
session_start();
require_once __DIR__ . '/db/config.php';
require_once __DIR__ . '/includes/audit.php';
header('Content-Type: application/json');
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
echo json_encode(['success' => false, 'message' => 'Invalid request method.']);
exit;
}
// If user is not logged in, return error
if (!isset($_SESSION['user_id'])) {
echo json_encode(['success' => false, 'message' => 'User not logged in.']);
exit;
}
$noteId = $_POST['note_id'] ?? null;
if ($noteId) {
try {
$pdo = db();
// Verify that the note belongs to a client of the logged-in user
$stmt = $pdo->prepare(
"SELECT n.note_id FROM notes n " .
"JOIN clients c ON n.client_id = c.client_id " .
"WHERE n.note_id = ? AND c.user_id = ?"
);
$stmt->execute([$noteId, $_SESSION['user_id']]);
$note = $stmt->fetch(PDO::FETCH_ASSOC);
if ($note) {
log_audit_event('note_delete', $_SESSION['user_id'], 'note', $noteId);
// Now, delete the note
$deleteStmt = $pdo->prepare("DELETE FROM notes WHERE note_id = ?");
$deleteStmt->execute([$noteId]);
echo json_encode(['success' => true]);
exit;
} else {
echo json_encode(['success' => false, 'message' => 'Note not found or you do not have permission to delete it.']);
exit;
}
} catch (PDOException $e) {
// Optional: Log error
error_log("Error deleting note: " . $e->getMessage());
echo json_encode(['success' => false, 'message' => 'Database error.']);
exit;
}
} else {
echo json_encode(['success' => false, 'message' => 'Note ID is required.']);
exit;
}
?>