'Permission denied.']); exit; } header('Content-Type: application/json'); $method = $_SERVER['REQUEST_METHOD']; $response = []; try { if ($method === 'GET') { $tab_id = filter_input(INPUT_GET, 'tab_id', FILTER_VALIDATE_INT); if ($tab_id) { $stmt = $pdo->prepare("SELECT user_id FROM tab_viewer_access WHERE tab_id = ?"); $stmt->execute([$tab_id]); // Fetch just the user_id column into a simple array $response = $stmt->fetchAll(PDO::FETCH_COLUMN, 0); } else { http_response_code(400); // Bad Request $response = ['error' => 'Tab ID is required.']; } } elseif ($method === 'POST') { $data = json_decode(file_get_contents('php://input'), true); $tab_id = $data['tab_id'] ?? null; $viewer_ids = $data['viewer_ids'] ?? []; if ($tab_id && is_array($viewer_ids)) { // Start transaction $pdo->beginTransaction(); // 1. Delete existing entries for this tab $delete_stmt = $pdo->prepare("DELETE FROM tab_viewer_access WHERE tab_id = ?"); $delete_stmt->execute([$tab_id]); // 2. Insert new entries if (!empty($viewer_ids)) { $insert_stmt = $pdo->prepare("INSERT INTO tab_viewer_access (tab_id, user_id) VALUES (?, ?)"); foreach ($viewer_ids as $user_id) { $insert_stmt->execute([$tab_id, $user_id]); } } // Commit transaction $pdo->commit(); $response = ['success' => true]; } else { http_response_code(400); // Bad Request $response = ['error' => 'Tab ID and a list of viewer IDs are required.']; } } else { http_response_code(405); // Method Not Allowed $response = ['error' => 'Method not allowed']; } } catch (PDOException $e) { if ($pdo->inTransaction()) { $pdo->rollBack(); } http_response_code(500); // Internal Server Error $response = ['error' => 'Database error: ' . $e->getMessage()]; } echo json_encode($response);