0; }); if (empty($url_ids)) { throw new Exception('Invalid URL IDs'); } // Get database connection $pdo = getClientDBConnection(); // Verify project belongs to client $stmt = $pdo->prepare(" SELECT project_id, project_name FROM projects WHERE project_id = ? AND client_id = ? "); $stmt->execute([$project_id, $client_id]); $project = $stmt->fetch(); if (!$project) { throw new Exception('Project not found or access denied'); } // Start transaction $pdo->beginTransaction(); try { // Delete only unsent URLs that belong to this project and batch $placeholders = str_repeat('?,', count($url_ids) - 1) . '?'; $stmt = $pdo->prepare(" DELETE FROM survey_urls WHERE id IN ($placeholders) AND project_id = ? AND batch_number = ? AND is_sent = 0 "); $params = array_merge($url_ids, [$project_id, $batch_number]); $stmt->execute($params); $deleted_count = $stmt->rowCount(); if ($deleted_count === 0) { throw new Exception('No URLs were deleted. They may have already been sent or do not exist.'); } // Update batch totals $stmt = $pdo->prepare(" UPDATE survey_url_batches SET total_urls = total_urls - ? WHERE project_id = ? AND batch_number = ? "); $stmt->execute([$deleted_count, $project_id, $batch_number]); // Check if batch is now empty and delete it if so $stmt = $pdo->prepare(" SELECT total_urls FROM survey_url_batches WHERE project_id = ? AND batch_number = ? "); $stmt->execute([$project_id, $batch_number]); $batch = $stmt->fetch(); if ($batch && $batch['total_urls'] <= 0) { // Delete empty batch $stmt = $pdo->prepare(" DELETE FROM survey_url_batches WHERE project_id = ? AND batch_number = ? "); $stmt->execute([$project_id, $batch_number]); } // Commit transaction $pdo->commit(); // Log activity error_log(sprintf( "Client %d deleted %d URLs from project %s batch %d", $client_id, $deleted_count, $project_id, $batch_number )); echo json_encode([ 'success' => true, 'deleted' => $deleted_count, 'message' => "Successfully deleted $deleted_count URL" . ($deleted_count > 1 ? 's' : '') ]); } catch (Exception $e) { // Rollback on error $pdo->rollBack(); throw $e; } } catch (Exception $e) { error_log("Delete URLs Error: " . $e->getMessage()); echo json_encode([ 'success' => false, 'message' => $e->getMessage() ]); } ?>